narcolepticchicken commited on
Commit
9221a43
Β·
verified Β·
1 Parent(s): 996a6e0

Upload training/router_v6_hybrid.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. training/router_v6_hybrid.py +338 -0
training/router_v6_hybrid.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Trained Router v6: Hybrid heuristic + ML safety net.
3
+
4
+ Key insight from v5: The ML classifiers alone can't beat the heuristic
5
+ because difficulty is the dominant feature. But they CAN detect when
6
+ the heuristic is wrong.
7
+
8
+ Architecture:
9
+ 1. Heuristic: difficulty+1 with safety floor (this is the base)
10
+ 2. ML SAFETY NET: Check if P(success@heuristic_tier) < LOW_THRESHOLD
11
+ If so, escalate to next tier (the ML caught a case the heuristic missed)
12
+ 3. ML COST SAVER: Check if P(success@tier-1) >= HIGH_THRESHOLD
13
+ If so, DOWNGRADE one tier (the ML says a cheaper tier would work)
14
+ """
15
+ import json, os, sys, random, uuid, pickle
16
+ import numpy as np
17
+ from collections import defaultdict
18
+ from typing import Dict, List, Optional, Tuple
19
+
20
+ TASK_TYPES = ["quick_answer","coding","research","document_drafting",
21
+ "legal_regulated","tool_heavy","retrieval_heavy",
22
+ "long_horizon","unknown_ambiguous"]
23
+ TT2IDX = {t:i for i,t in enumerate(TASK_TYPES)}
24
+
25
+ CODE_KW = ["python","javascript","code","function","bug","debug","refactor",
26
+ "implement","test","compile","runtime","class","module","async","thread"]
27
+ LEGAL_KW = ["contract","legal","compliance","gdpr","privacy","policy","regulatory","liability"]
28
+ RESEARCH_KW = ["research","find sources","literature","investigate","compare","analyze","survey"]
29
+ TOOL_KW = ["search","fetch","retrieve","query","api","database","scrape","aggregate"]
30
+ LONG_KW = ["plan","project","roadmap","orchestrate","multi-step","migrate","pipeline","deploy"]
31
+ MATH_KW = ["calculate","compute","solve","equation","formula","optimize","probability"]
32
+
33
+ TIER_STR = {1:0.35,2:0.55,3:0.80,4:0.93,5:0.97}
34
+ TIER_COST = {1:0.05,2:0.15,3:0.75,4:1.0,5:1.5}
35
+ TASK_FLOOR = {"legal_regulated":4,"long_horizon":3,"research":3,"coding":3,
36
+ "unknown_ambiguous":3,"quick_answer":1,"document_drafting":2,
37
+ "tool_heavy":2,"retrieval_heavy":2}
38
+
39
+ TASK_TEMPLATES = {
40
+ "quick_answer":["What is the capital of France?","Explain quantum computing briefly.",
41
+ "What is 237*452?","Define photosynthesis.","Who wrote Hamlet?",
42
+ "What is the speed of light?","List the primary colors.","What is GDP?"],
43
+ "coding":["Write a Python function to reverse a linked list.",
44
+ "Fix the bug in this React component.","Refactor auth module to JWT.",
45
+ "Implement LRU cache in Go.","Debug segfault in C++ thread pool.",
46
+ "Add unit tests for the payment module.","Optimize this SQL query.",
47
+ "Create a REST API for user management.","Implement binary search in Rust."],
48
+ "research":["Research latest transformer advances.",
49
+ "Find sources comparing LoRA and full FT.",
50
+ "Investigate data center climate impact.",
51
+ "Survey privacy-preserving ML techniques."],
52
+ "document_drafting":["Draft project proposal for ML pipeline.",
53
+ "Write email to team about deployment.","Create technical report on performance."],
54
+ "legal_regulated":["Review this contract for liability clauses.",
55
+ "Check GDPR compliance for data pipeline.","Draft privacy policy section."],
56
+ "tool_heavy":["Search open issues and create summary.",
57
+ "Fetch API docs and generate client code.","Query Q3 sales and produce chart."],
58
+ "retrieval_heavy":["Answer based on 50-page document.",
59
+ "Find all payment processing mentions.","Retrieve relevant cases for legal query."],
60
+ "long_horizon":["Plan 3-month roadmap.","Orchestrate multi-region deployment.",
61
+ "Redesign data architecture end-to-end."],
62
+ "unknown_ambiguous":["Help me with this thing.",
63
+ "I need something about the server.","Can you look into that issue?"],
64
+ }
65
+
66
+ def tsp(tier, diff):
67
+ return TIER_STR[tier] ** (diff * 0.6)
68
+
69
+ def extract_features(request, task_type, difficulty=3):
70
+ r = request.lower()
71
+ f = {"req_len":len(request),"num_words":len(request.split()),
72
+ "has_code":int(any(k in r for k in CODE_KW)),
73
+ "n_code":sum(1 for k in CODE_KW if k in r),
74
+ "has_legal":int(any(k in r for k in LEGAL_KW)),
75
+ "n_legal":sum(1 for k in LEGAL_KW if k in r),
76
+ "has_research":int(any(k in r for k in RESEARCH_KW)),
77
+ "n_research":sum(1 for k in RESEARCH_KW if k in r),
78
+ "has_tool":int(any(k in r for k in TOOL_KW)),
79
+ "n_tool":sum(1 for k in TOOL_KW if k in r),
80
+ "has_long":int(any(k in r for k in LONG_KW)),
81
+ "has_math":int(any(k in r for k in MATH_KW)),
82
+ "tt_idx":TT2IDX.get(task_type,8),"difficulty":difficulty}
83
+ for tt in TASK_TYPES:
84
+ f[f"tt_{tt}"] = int(task_type == tt)
85
+ return f
86
+
87
+ def gen_trace(idx, rng):
88
+ tt = rng.choice(list(TASK_TEMPLATES.keys()))
89
+ diff = {"quick_answer":1,"document_drafting":2,"tool_heavy":2,"retrieval_heavy":2,
90
+ "research":3,"coding":3,"unknown_ambiguous":3,"long_horizon":4,"legal_regulated":5}[tt]
91
+ tier_out = {t: rng.random() < tsp(t, diff) for t in range(1,6)}
92
+ opt = 5
93
+ for t in range(1,6):
94
+ if tier_out[t]: opt = t; break
95
+ if diff <= 2: actual = rng.choices([1,2,3,4,5],weights=[3,4,2,1,0.5])[0]
96
+ elif diff == 3: actual = rng.choices([1,2,3,4,5],weights=[1,2,4,2,1])[0]
97
+ elif diff == 4: actual = rng.choices([1,2,3,4,5],weights=[0.5,1,2,4,2])[0]
98
+ else: actual = rng.choices([1,2,3,4,5],weights=[0.2,0.5,1,3,4])[0]
99
+ outcome = "success" if tier_out[actual] else "failure"
100
+ req = rng.choice(TASK_TEMPLATES[tt])
101
+ feats = extract_features(req, tt, diff)
102
+ return {"feats":feats,"opt":opt,"actual":actual,"outcome":outcome,
103
+ "tier_out":tier_out,"tt":tt,"diff":diff,"req":req}
104
+
105
+ print("="*80)
106
+ print("ACO TRAINED ROUTER v6: HYBRID HEURISTIC + ML SAFETY NET")
107
+ print("="*80)
108
+
109
+ # ─── Train Models ────────────────────────────────────────────────────
110
+ print("\n[1] Generating 50K training traces...")
111
+ rng = random.Random(42)
112
+ traces = [gen_trace(i, rng) for i in range(50000)]
113
+ FEAT_KEYS = sorted(traces[0]["feats"].keys())
114
+ def f2v(feats):
115
+ return np.array([float(feats.get(k, 0.0)) for k in FEAT_KEYS], dtype=np.float32)
116
+
117
+ X_all = np.array([f2v(t["feats"]) for t in traces])
118
+ y_opt = np.array([t["opt"] for t in traces])
119
+ per_tier_labels = {}
120
+ for tier in range(1,6):
121
+ per_tier_labels[tier] = np.array([1 if t["tier_out"].get(tier,False) else 0 for t in traces])
122
+
123
+ from sklearn.model_selection import train_test_split
124
+ from sklearn.metrics import accuracy_score, f1_score
125
+ from sklearn.calibration import IsotonicRegression
126
+ import xgboost as xgb
127
+
128
+ X_train, X_test, idx_train, idx_test = train_test_split(X_all, range(len(traces)), test_size=0.2, random_state=42, stratify=y_opt)
129
+ print(f" Train: {len(X_train)}, Test: {len(X_test)}")
130
+
131
+ print("\n[2] Training per-tier classifiers...")
132
+ tier_clfs = {}
133
+ tier_calibs = {}
134
+ for tier in range(1,6):
135
+ y_tr = per_tier_labels[tier][idx_train]
136
+ y_te = per_tier_labels[tier][idx_test]
137
+ neg = (y_tr==0).sum(); pos = (y_tr==1).sum()
138
+ spw = neg/max(pos,1)
139
+ clf = xgb.XGBClassifier(n_estimators=200,max_depth=5,learning_rate=0.1,
140
+ subsample=0.8,colsample_bytree=0.8,scale_pos_weight=min(spw,5.0),
141
+ objective="binary:logistic",eval_metric="logloss",random_state=42,verbosity=0)
142
+ clf.fit(X_train, y_tr)
143
+ y_prob = clf.predict_proba(X_test)[:,1]
144
+ iso = IsotonicRegression(out_of_bounds="clip")
145
+ iso.fit(y_prob, y_te)
146
+ tier_clfs[tier] = clf
147
+ tier_calibs[tier] = iso
148
+ acc = accuracy_score(y_te, clf.predict(X_test))
149
+ f1 = f1_score(y_te, clf.predict(X_test), zero_division=0)
150
+ print(f" Tier {tier}: acc={acc:.3f}, f1={f1:.3f}")
151
+
152
+ def get_calibrated_psuccess(x, tier):
153
+ """Get calibrated P(success@tier) for a feature vector."""
154
+ p_raw = tier_clfs[tier].predict_proba(x)[0, 1]
155
+ return float(tier_calibs[tier].transform([p_raw])[0])
156
+
157
+ # ─── Hybrid Router ────────────────────────────────────────────────────
158
+ print("\n[3] Building hybrid heuristic + ML safety net router...")
159
+
160
+ def route_hybrid(request, task_type, difficulty,
161
+ safety_threshold=0.35, downgrade_threshold=0.80):
162
+ """Hybrid: heuristic base + ML safety net + ML cost saver.
163
+
164
+ 1. Start with heuristic tier (difficulty+1, safety floor)
165
+ 2. SAFETY NET: If P(success@heuristic_tier) < safety_threshold, ESCALATE
166
+ 3. COST SAVER: If P(success@tier-1) >= downgrade_threshold AND
167
+ tier-1 >= safety_floor, DOWNGRADE one tier
168
+ 4. Never go below safety floor or above 5
169
+ """
170
+ heuristic_tier = min(difficulty + 1, 5)
171
+ floor = TASK_FLOOR.get(task_type, 2)
172
+ heuristic_tier = max(heuristic_tier, floor)
173
+
174
+ feats = extract_features(request, task_type, difficulty)
175
+ x = f2v(feats).reshape(1, -1)
176
+
177
+ tier = heuristic_tier
178
+
179
+ # SAFETY NET: Check if heuristic tier is likely to fail
180
+ p_success = get_calibrated_psuccess(x, tier)
181
+ if p_success < safety_threshold and tier < 5:
182
+ tier += 1
183
+ p_success = get_calibrated_psuccess(x, tier)
184
+
185
+ # COST SAVER: Check if a cheaper tier would also work
186
+ # Only downgrade if: cheaper tier >= floor, P(success) high, and we're not already escalated
187
+ if tier > floor and tier == heuristic_tier: # only if we didn't escalate
188
+ cheaper_tier = tier - 1
189
+ p_cheaper = get_calibrated_psuccess(x, cheaper_tier)
190
+ if p_cheaper >= downgrade_threshold and cheaper_tier >= floor:
191
+ tier = cheaper_tier
192
+
193
+ return tier
194
+
195
+ # ─── Generate Eval ─────────────────────────────────────────────────────
196
+ print("\n[4] Generating 2K eval traces (seed=999)...")
197
+ eval_rng = random.Random(999)
198
+ eval_traces = []
199
+ for i in range(2000):
200
+ tt = eval_rng.choice(list(TASK_TEMPLATES.keys()))
201
+ diff = {"quick_answer":1,"document_drafting":2,"tool_heavy":2,"retrieval_heavy":2,
202
+ "research":3,"coding":3,"unknown_ambiguous":3,"long_horizon":4,"legal_regulated":5}[tt]
203
+ tier_out = {t: eval_rng.random() < tsp(t, diff) for t in range(1,6)}
204
+ opt = 5
205
+ for t in range(1,6):
206
+ if tier_out[t]: opt = t; break
207
+ req = eval_rng.choice(TASK_TEMPLATES[tt])
208
+ eval_traces.append({"tt":tt,"diff":diff,"opt":opt,"tier_out":tier_out,"req":req})
209
+ print(f" Generated {len(eval_traces)} traces")
210
+
211
+ # ─── Evaluate ──────────────────────────────────────────────────────────
212
+ print("\n[5] Evaluating all routers...")
213
+ n_test = len(eval_traces)
214
+ results = {}
215
+
216
+ def eval_router(name, route_fn):
217
+ succ=0; cost=0.0; unsafe=0; fd=0; td=defaultdict(int)
218
+ escalations=0; downgrades=0; heuristic_only=0
219
+ for t in eval_traces:
220
+ pred = route_fn(t)
221
+ td[pred] += 1
222
+ h_tier = min(t["diff"]+1, 5)
223
+ h_tier = max(h_tier, TASK_FLOOR.get(t["tt"], 2))
224
+ if pred > h_tier: escalations += 1
225
+ elif pred < h_tier: downgrades += 1
226
+ else: heuristic_only += 1
227
+ if t["tier_out"].get(pred, False): succ += 1
228
+ elif pred < t["opt"]: unsafe += 1
229
+ else: fd += 1
230
+ cost += TIER_COST[pred]
231
+ return {"success":succ/n_test, "avg_cost":cost/n_test, "unsafe_rate":unsafe/n_test,
232
+ "false_done":fd/n_test, "tier_dist":dict(td),
233
+ "escalations":escalations, "downgrades":downgrades, "heuristic_only":heuristic_only}
234
+
235
+ results["always_frontier"] = eval_router("always_frontier", lambda t: 4)
236
+ results["always_cheap"] = eval_router("always_cheap", lambda t: 1)
237
+ results["heuristic_diff+1"] = eval_router("heuristic_diff+1", lambda t: min(t["diff"]+1, 5))
238
+ results["heuristic_floor"] = eval_router("heuristic_floor", lambda t: TASK_FLOOR.get(t["tt"], 2))
239
+ results["oracle"] = eval_router("oracle", lambda t: t["opt"])
240
+
241
+ # Hybrid at different thresholds
242
+ for st in [0.25, 0.30, 0.35, 0.40]:
243
+ for dt in [0.70, 0.75, 0.80, 0.85]:
244
+ name = f"hybrid_s{st:.2f}_d{dt:.2f}"
245
+ results[name] = eval_router(name,
246
+ lambda t, s=st, d=dt: route_hybrid(t["req"], t["tt"], t["diff"], s, d))
247
+
248
+ # Print top results
249
+ print(f"\n{'Router':<30} {'Success':>10} {'AvgCost':>10} {'CostRed':>10} {'Unsafe':>10} {'F-DONE':>10}")
250
+ print("-"*80)
251
+ fc = results["always_frontier"]["avg_cost"]
252
+
253
+ # Only show key results + top 10 hybrids
254
+ shown = set()
255
+ for name in ["always_frontier","always_cheap","heuristic_diff+1","heuristic_floor","oracle"]:
256
+ r = results[name]
257
+ cr = (1 - r["avg_cost"]/fc)*100
258
+ print(f"{name:<30} {r['success']:>10.3f} {r['avg_cost']:>10.4f} {cr:>9.1f}% {r['unsafe_rate']:>10.3f} {r['false_done']:>10.3f}")
259
+ shown.add(name)
260
+
261
+ # Top 10 hybrids by composite score
262
+ hybrid_scores = []
263
+ for name, r in results.items():
264
+ if name in shown or not name.startswith("hybrid"): continue
265
+ score = r["success"]*20 - r["avg_cost"]*30 - r["unsafe_rate"]*100
266
+ hybrid_scores.append((score, name, r))
267
+ hybrid_scores.sort(reverse=True)
268
+
269
+ for score, name, r in hybrid_scores[:10]:
270
+ cr = (1 - r["avg_cost"]/fc)*100
271
+ esc = r["escalations"]; down = r["downgrades"]; honly = r["heuristic_only"]
272
+ print(f"{name:<30} {r['success']:>10.3f} {r['avg_cost']:>10.4f} {cr:>9.1f}% {r['unsafe_rate']:>10.3f} {r['false_done']:>10.3f} esc={esc} down={down} same={honly}")
273
+
274
+ # ─── Per-task breakdown for best hybrid ────────────────────────────────
275
+ best_hybrid_name = hybrid_scores[0][1] if hybrid_scores else "heuristic_diff+1"
276
+ print(f"\n\n[6] Per-task breakdown for {best_hybrid_name}...")
277
+
278
+ for tt in sorted(set(t["tt"] for t in eval_traces)):
279
+ tt_traces = [t for t in eval_traces if t["tt"] == tt]
280
+ n_tt = len(tt_traces)
281
+ if n_tt == 0: continue
282
+ print(f"\n {tt} (n={n_tt}):")
283
+ for rname, rfn in [("frontier", lambda t:4),
284
+ ("heuristic", lambda t:min(t["diff"]+1,5)),
285
+ ("hybrid", lambda t:route_hybrid(t["req"],t["tt"],t["diff"],0.35,0.80)),
286
+ ("oracle", lambda t:t["opt"])]:
287
+ succ = sum(1 for t in tt_traces if t["tier_out"].get(rfn(t), False))
288
+ cost = sum(TIER_COST[rfn(t)] for t in tt_traces)
289
+ sr = succ/n_tt; ac = cost/n_tt
290
+ cr = (1-ac/fc)*100
291
+ print(f" {rname:<12} success={sr:.3f} cost={ac:.4f} costRed={cr:.1f}%")
292
+
293
+ # ─── Pareto ────────────────────────────────────────────────────────────
294
+ print(f"\n\n[7] Pareto frontier...")
295
+ for name, r in results.items():
296
+ if name == "always_cheap": continue
297
+ dominated = False
298
+ for name2, r2 in results.items():
299
+ if name == name2: continue
300
+ if r2["success"] >= r["success"] and r2["avg_cost"] <= r["avg_cost"]:
301
+ if r2["success"] > r["success"] or r2["avg_cost"] < r["avg_cost"]:
302
+ dominated = True; break
303
+ if not dominated:
304
+ cr = (1-r["avg_cost"]/fc)*100
305
+ print(f" {name:<30} success={r['success']:.3f} cost={r['avg_cost']:.4f} costRed={cr:.1f}% unsafe={r['unsafe_rate']:.3f}")
306
+
307
+ # ─── Save ──────────────────────────────────────────────────────────────
308
+ print("\n[8] Saving final model...")
309
+ os.makedirs("/app/router_models", exist_ok=True)
310
+
311
+ bundle = {
312
+ "tier_clfs": {str(k):v for k,v in tier_clfs.items()},
313
+ "tier_calibrators": {str(k):v for k,v in tier_calibs.items()},
314
+ "feat_keys": FEAT_KEYS,
315
+ "tier_config": {"tier_cost":TIER_COST,"tier_str":TIER_STR,
316
+ "task_floor":TASK_FLOOR,
317
+ "safety_threshold":0.35,"downgrade_threshold":0.80},
318
+ "version": "6.0",
319
+ "description": "ACO Hybrid Router: heuristic base + ML safety net + ML cost saver",
320
+ }
321
+ with open("/app/router_models/router_bundle_v6.pkl","wb") as f:
322
+ pickle.dump(bundle, f)
323
+ print(f" Saved router_bundle_v6.pkl ({os.path.getsize('/app/router_models/router_bundle_v6.pkl')/1024:.0f} KB)")
324
+
325
+ with open("/app/router_models/v6_eval_results.json","w") as f:
326
+ json.dump(results, f, indent=2, default=str)
327
+
328
+ print(f"\n\n{'='*80}")
329
+ print("FINAL v6 COMPARISON")
330
+ print(f"{'='*80}")
331
+ print(f"\n{'Router':<30} {'Success':>10} {'AvgCost':>10} {'CostRed':>10} {'Unsafe':>10} {'F-DONE':>10}")
332
+ print("-"*80)
333
+ for name, r in sorted(results.items(), key=lambda x: (-x[1]["success"], x[1]["avg_cost"])):
334
+ if name.startswith("hybrid") and name != best_hybrid_name: continue
335
+ cr = (1-r["avg_cost"]/fc)*100
336
+ print(f"{name:<30} {r['success']:>10.3f} {r['avg_cost']:>10.4f} {cr:>9.1f}% {r['unsafe_rate']:>10.3f} {r['false_done']:>10.3f}")
337
+
338
+ print(f"\nDONE!")