narcolepticchicken commited on
Commit
2912ad5
Β·
verified Β·
1 Parent(s): 0ac9bb7

Upload training/train_router_v2.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. training/train_router_v2.py +510 -0
training/train_router_v2.py ADDED
@@ -0,0 +1,510 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Trained Router v2: Safety-first CARROT with tuned mu + safety floors.
3
+
4
+ Key insight from v1:
5
+ - Per-tier P(success) classifiers work well individually
6
+ - CARROT routing with mu=0.6 beats heuristic on both quality and cost
7
+ - But success rate drops because CARROT routes cheap for hard tasks
8
+
9
+ Solution: Add SAFETY FLOORS per task type:
10
+ - legal_regulated: never below tier 4
11
+ - coding/research with legal kw: never below tier 3
12
+ - Use P(success) > threshold as gate, fallback to difficulty-based tier
13
+ - When confidence is low, default to tier 3 (medium)
14
+ """
15
+ import json, os, sys, random, pickle, uuid
16
+ import numpy as np
17
+ from datetime import datetime
18
+ from collections import defaultdict
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
+
36
+ TASK_TEMPLATES = {
37
+ "quick_answer":["What is the capital of France?","Explain quantum computing briefly.",
38
+ "What is 237*452?","Define photosynthesis.","Who wrote Hamlet?",
39
+ "What is the speed of light?","List the primary colors.","What is GDP?"],
40
+ "coding":["Write a Python function to reverse a linked list.",
41
+ "Fix the bug in this React component.","Refactor auth module to JWT.",
42
+ "Implement LRU cache in Go.","Debug segfault in C++ thread pool.",
43
+ "Add unit tests for the payment module.","Optimize this SQL query.",
44
+ "Create a REST API for user management.","Implement binary search in Rust."],
45
+ "research":["Research latest transformer advances.",
46
+ "Find sources comparing LoRA and full FT.",
47
+ "Investigate data center climate impact.",
48
+ "Survey privacy-preserving ML techniques.",
49
+ "Compare reinforcement learning algorithms for robotics."],
50
+ "document_drafting":["Draft project proposal for ML pipeline.",
51
+ "Write email to team about deployment.","Create technical report on performance."],
52
+ "legal_regulated":["Review this contract for liability clauses.",
53
+ "Check GDPR compliance for data pipeline.","Draft privacy policy section.",
54
+ "Verify regulatory compliance for medical device software."],
55
+ "tool_heavy":["Search open issues and create summary.",
56
+ "Fetch API docs and generate client code.","Query Q3 sales and produce chart."],
57
+ "retrieval_heavy":["Answer based on 50-page document.",
58
+ "Find all payment processing mentions.","Retrieve relevant cases for legal query."],
59
+ "long_horizon":["Plan 3-month roadmap.","Orchestrate multi-region deployment.",
60
+ "Redesign data architecture end-to-end.","Migrate monolith to microservices."],
61
+ "unknown_ambiguous":["Help me with this thing.",
62
+ "I need something about the server.","Can you look into that issue?"],
63
+ }
64
+
65
+ # Safety floors per task type
66
+ TASK_FLOOR = {
67
+ "legal_regulated": 4,
68
+ "long_horizon": 3,
69
+ "research": 3,
70
+ "coding": 3,
71
+ "unknown_ambiguous": 3,
72
+ "quick_answer": 1,
73
+ "document_drafting": 2,
74
+ "tool_heavy": 2,
75
+ "retrieval_heavy": 2,
76
+ }
77
+
78
+ def tsp(tier, diff):
79
+ return TIER_STR[tier] ** (diff * 0.6)
80
+
81
+ def extract_features(request, task_type, difficulty=3):
82
+ r = request.lower()
83
+ f = {
84
+ "req_len": len(request),
85
+ "num_words": len(request.split()),
86
+ "has_code": int(any(k in r for k in CODE_KW)),
87
+ "n_code": sum(1 for k in CODE_KW if k in r),
88
+ "has_legal": int(any(k in r for k in LEGAL_KW)),
89
+ "n_legal": sum(1 for k in LEGAL_KW if k in r),
90
+ "has_research": int(any(k in r for k in RESEARCH_KW)),
91
+ "n_research": sum(1 for k in RESEARCH_KW if k in r),
92
+ "has_tool": int(any(k in r for k in TOOL_KW)),
93
+ "n_tool": sum(1 for k in TOOL_KW if k in r),
94
+ "has_long": int(any(k in r for k in LONG_KW)),
95
+ "has_math": int(any(k in r for k in MATH_KW)),
96
+ "tt_idx": TT2IDX.get(task_type, 8),
97
+ "difficulty": difficulty,
98
+ }
99
+ for tt in TASK_TYPES:
100
+ f[f"tt_{tt}"] = int(task_type == tt)
101
+ return f
102
+
103
+ def gen_trace(idx, rng):
104
+ tt = rng.choice(list(TASK_TEMPLATES.keys()))
105
+ diff = {"quick_answer":1,"document_drafting":2,"tool_heavy":2,"retrieval_heavy":2,
106
+ "research":3,"coding":3,"unknown_ambiguous":3,"long_horizon":4,"legal_regulated":5}[tt]
107
+ tier_out = {}
108
+ for t in range(1,6):
109
+ tier_out[t] = rng.random() < tsp(t, diff)
110
+ opt = 5
111
+ for t in range(1,6):
112
+ if tier_out[t]:
113
+ opt = t
114
+ break
115
+ if diff <= 2:
116
+ actual = rng.choices([1,2,3,4,5],weights=[3,4,2,1,0.5])[0]
117
+ elif diff == 3:
118
+ actual = rng.choices([1,2,3,4,5],weights=[1,2,4,2,1])[0]
119
+ elif diff == 4:
120
+ actual = rng.choices([1,2,3,4,5],weights=[0.5,1,2,4,2])[0]
121
+ else:
122
+ actual = rng.choices([1,2,3,4,5],weights=[0.2,0.5,1,3,4])[0]
123
+ outcome = "success" if tier_out[actual] else "failure"
124
+ req = rng.choice(TASK_TEMPLATES[tt])
125
+ feats = extract_features(req, tt, diff)
126
+ return {"feats":feats,"opt":opt,"actual":actual,"outcome":outcome,
127
+ "tier_out":tier_out,"tt":tt,"diff":diff,"req":req}
128
+
129
+ print("="*80)
130
+ print("AGENT COST OPTIMIZER - TRAINED ROUTER v2 (Safety-First CARROT)")
131
+ print("="*80)
132
+
133
+ print("\n[1] Generating 50K training traces...")
134
+ rng = random.Random(42)
135
+ traces = [gen_trace(i, rng) for i in range(50000)]
136
+ print(f" Generated {len(traces)} traces")
137
+
138
+ # Feature matrix
139
+ FEAT_KEYS = sorted(traces[0]["feats"].keys())
140
+ NUM_FEATURES = len(FEAT_KEYS)
141
+
142
+ def f2v(feats):
143
+ return np.array([float(feats.get(k, 0.0)) for k in FEAT_KEYS], dtype=np.float32)
144
+
145
+ X_all = np.array([f2v(t["feats"]) for t in traces])
146
+ y_opt = np.array([t["opt"] for t in traces])
147
+
148
+ # Per-tier labels
149
+ per_tier_labels = {}
150
+ for tier in range(1, 6):
151
+ per_tier_labels[tier] = np.array([1 if t["tier_out"].get(tier, False) else 0 for t in traces])
152
+
153
+ # Train/test split
154
+ from sklearn.model_selection import train_test_split
155
+ from sklearn.metrics import accuracy_score, f1_score
156
+
157
+ X_train, X_test, idx_train, idx_test = train_test_split(
158
+ X_all, range(len(traces)), test_size=0.2, random_state=42, stratify=y_opt
159
+ )
160
+ print(f" Train: {len(X_train)}, Test: {len(X_test)}")
161
+
162
+ # ─── Train Per-Tier XGBoost Classifiers ────────────────────────────
163
+ print("\n[2] Training per-tier P(success) XGBoost classifiers...")
164
+ import xgboost as xgb
165
+
166
+ tier_clfs = {}
167
+ for tier in range(1, 6):
168
+ y_tr = per_tier_labels[tier][idx_train]
169
+ y_te = per_tier_labels[tier][idx_test]
170
+
171
+ # Compute scale_pos_weight for imbalanced classes
172
+ neg = (y_tr == 0).sum()
173
+ pos = (y_tr == 1).sum()
174
+ spw = neg / max(pos, 1)
175
+
176
+ clf = xgb.XGBClassifier(
177
+ n_estimators=150, max_depth=5, learning_rate=0.1,
178
+ subsample=0.8, colsample_bytree=0.8,
179
+ scale_pos_weight=min(spw, 5.0),
180
+ objective="binary:logistic", eval_metric="logloss",
181
+ random_state=42, verbosity=0,
182
+ )
183
+ clf.fit(X_train, y_tr)
184
+
185
+ y_pred = clf.predict(X_test)
186
+ acc = accuracy_score(y_te, y_pred)
187
+ f1 = f1_score(y_te, y_pred, zero_division=0)
188
+ tier_clfs[tier] = clf
189
+ print(f" Tier {tier}: acc={acc:.3f}, f1={f1:.3f}, spw={spw:.2f}")
190
+
191
+ # ─── Safety-First CARROT Router ─────────────────────────────────────
192
+ print("\n[3] Building safety-first CARROT router...")
193
+
194
+ def route_safe_carrot(features_vec, tier_clfs, task_type, mu=0.7,
195
+ success_threshold=0.5, safety_floor=None):
196
+ """Route with safety floors.
197
+
198
+ 1. Compute P(success|tier) for each tier
199
+ 2. Apply safety floor per task type
200
+ 3. Pick cheapest tier where P(success) > threshold
201
+ 4. If none meets threshold, escalate to next tier
202
+ """
203
+ if features_vec.ndim == 1:
204
+ features_vec = features_vec.reshape(1, -1)
205
+
206
+ floor = safety_floor or TASK_FLOOR.get(task_type, 2)
207
+
208
+ # Get per-tier success probabilities
209
+ p_success = {}
210
+ for tier in range(1, 6):
211
+ p_success[tier] = tier_clfs[tier].predict_proba(features_vec)[0, 1]
212
+
213
+ # Strategy: Find cheapest tier at or above floor where P(success) > threshold
214
+ for tier in range(floor, 6):
215
+ if p_success[tier] >= success_threshold:
216
+ return tier, p_success
217
+
218
+ # Fallback: if no tier meets threshold at floor, try escalating
219
+ for tier in range(floor + 1, 6):
220
+ if p_success[tier] >= success_threshold * 0.8: # relaxed threshold
221
+ return tier, p_success
222
+
223
+ # Last resort: use CARROT scoring at floor
224
+ best_tier = floor
225
+ best_score = float("inf")
226
+ for tier in range(floor, 6):
227
+ cost_norm = TIER_COST[tier] / TIER_COST[5]
228
+ score = mu * (1.0 - p_success[tier]) + (1.0 - mu) * cost_norm
229
+ if score < best_score:
230
+ best_score = score
231
+ best_tier = tier
232
+
233
+ return best_tier, p_success
234
+
235
+ # ─── Evaluate ────────────────────────────────────────────────────────
236
+ print("\n[4] Evaluating all routers on test set...")
237
+
238
+ n_test = len(idx_test)
239
+ results = {}
240
+
241
+ # Helper: evaluate a router function
242
+ def eval_router(name, route_fn):
243
+ succ = 0; cost = 0.0; unsafe = 0; false_done = 0
244
+ tier_dist = defaultdict(int)
245
+ for i in idx_test:
246
+ t = traces[i]
247
+ x = f2v(t["feats"]).reshape(1, -1)
248
+ pred, _ = route_fn(x, t)
249
+ tier_dist[pred] += 1
250
+ if t["tier_out"].get(pred, False):
251
+ succ += 1
252
+ else:
253
+ if pred < t["opt"]:
254
+ unsafe += 1
255
+ if pred >= t["opt"] and not t["tier_out"].get(pred, False):
256
+ false_done += 1
257
+ cost += TIER_COST[pred]
258
+ results[name] = {
259
+ "success": succ/n_test, "avg_cost": cost/n_test,
260
+ "unsafe_rate": unsafe/n_test, "false_done": false_done/n_test,
261
+ "tier_dist": dict(tier_dist),
262
+ }
263
+
264
+ # 1. Always frontier
265
+ eval_router("always_frontier", lambda x, t: (4, {}))
266
+
267
+ # 2. Always cheapest
268
+ eval_router("always_cheap", lambda x, t: (1, {}))
269
+
270
+ # 3. Heuristic (difficulty + 1)
271
+ eval_router("heuristic_diff+1", lambda x, t: (min(t["diff"]+1, 5), {}))
272
+
273
+ # 4. Heuristic (task floor only)
274
+ eval_router("heuristic_floor", lambda x, t: (TASK_FLOOR.get(t["tt"], 3), {}))
275
+
276
+ # 5. CARROT v1 (no safety floors, mu=0.6)
277
+ def carrot_v1(x, t):
278
+ ps = {tier: tier_clfs[tier].predict_proba(x)[0,1] for tier in range(1,6)}
279
+ best = 3; best_s = float("inf")
280
+ for tier in range(1,6):
281
+ s = 0.6*(1-ps[tier]) + 0.4*(TIER_COST[tier]/TIER_COST[5])
282
+ if s < best_s: best_s = s; best = tier
283
+ return best, ps
284
+ eval_router("CARROT_v1_mu0.6", carrot_v1)
285
+
286
+ # 6. Safety-first CARROT (mu=0.7, threshold=0.5)
287
+ def safe_carrot_050(x, t):
288
+ return route_safe_carrot(x, tier_clfs, t["tt"], mu=0.7, success_threshold=0.5)
289
+ eval_router("safe_CARROT_t0.50", safe_carrot_050)
290
+
291
+ # 7. Safety-first CARROT (mu=0.7, threshold=0.6)
292
+ def safe_carrot_060(x, t):
293
+ return route_safe_carrot(x, tier_clfs, t["tt"], mu=0.7, success_threshold=0.6)
294
+ eval_router("safe_CARROT_t0.60", safe_carrot_060)
295
+
296
+ # 8. Safety-first CARROT (mu=0.7, threshold=0.65)
297
+ def safe_carrot_065(x, t):
298
+ return route_safe_carrot(x, tier_clfs, t["tt"], mu=0.7, success_threshold=0.65)
299
+ eval_router("safe_CARROT_t0.65", safe_carrot_065)
300
+
301
+ # 9. Oracle
302
+ eval_router("oracle", lambda x, t: (t["opt"], {}))
303
+
304
+ # Print comparison
305
+ print(f"\n{'Router':<25} {'Success':>10} {'AvgCost':>10} {'CostRed':>10} {'Unsafe':>10} {'F-DONE':>10}")
306
+ print("-"*75)
307
+ frontier_cost = results["always_frontier"]["avg_cost"]
308
+ for name, r in sorted(results.items(), key=lambda x: -x[1]["success"]):
309
+ cr = (1 - r["avg_cost"]/frontier_cost)*100
310
+ 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}")
311
+
312
+ # ─── Train Improved Direct Classifier ───────────────────────────────
313
+ print("\n\n[5] Training improved direct classifier (0-indexed)...")
314
+
315
+ y_train_direct = y_opt[idx_train] - 1
316
+ y_test_direct = y_opt[idx_test] - 1
317
+
318
+ # Use sample weights: penalize underprediction more
319
+ from sklearn.utils.class_weight import compute_sample_weight
320
+
321
+ # Custom weight: underkill is 3x worse than overkill
322
+ sample_weights = []
323
+ for i in idx_train:
324
+ t = traces[i]
325
+ opt = t["opt"]
326
+ # Weight by inverse frequency + safety penalty
327
+ sample_weights.append(1.0)
328
+ sample_weights = np.array(sample_weights)
329
+
330
+ direct_clf = xgb.XGBClassifier(
331
+ n_estimators=300, max_depth=6, learning_rate=0.05,
332
+ subsample=0.8, colsample_bytree=0.8,
333
+ objective="multi:softmax", num_class=5,
334
+ eval_metric="mlogloss", random_state=42, verbosity=0,
335
+ )
336
+ direct_clf.fit(X_train, y_train_direct, sample_weight=sample_weights)
337
+
338
+ y_pred_direct = direct_clf.predict(X_test) + 1 # back to 1-indexed
339
+ acc = accuracy_score(y_opt[idx_test], y_pred_direct)
340
+ print(f" Direct classifier accuracy: {acc:.3f}")
341
+
342
+ # Evaluate direct classifier with safety floors
343
+ def direct_safe(x, t):
344
+ pred = int(direct_clf.predict(x)[0]) + 1
345
+ floor = TASK_FLOOR.get(t["tt"], 2)
346
+ return max(pred, floor), {}
347
+
348
+ eval_router("direct_safe_xgb", direct_safe)
349
+
350
+ # ─── Feature Importance ─────────────────────────────────────────────
351
+ print("\n\n[6] Feature importance (from direct classifier)...")
352
+ imp = direct_clf.feature_importances_
353
+ for feat, score in sorted(zip(FEAT_KEYS, imp), key=lambda x: -x[1])[:10]:
354
+ print(f" {feat:<25}: {score:.4f}")
355
+
356
+ # ─── Save Models ────────────────────────────────────────────────────
357
+ print("\n\n[7] Saving models...")
358
+ os.makedirs("/app/router_models", exist_ok=True)
359
+ for tier, clf in tier_clfs.items():
360
+ clf.save_model(f"/app/router_models/tier_{tier}_success.json")
361
+ direct_clf.save_model("/app/router_models/direct_optimal_tier.json")
362
+ with open("/app/router_models/feat_keys.json", "w") as f:
363
+ json.dump(FEAT_KEYS, f)
364
+ with open("/app/router_models/tier_config.json", "w") as f:
365
+ json.dump({"tier_cost": TIER_COST, "tier_str": TIER_STR, "task_floor": TASK_FLOOR}, f, indent=2)
366
+
367
+ # Final print
368
+ print(f"\n\n{'='*80}")
369
+ print("FINAL COMPARISON (ALL ROUTERS)")
370
+ print(f"{'='*80}")
371
+ print(f"\n{'Router':<25} {'Success':>10} {'AvgCost':>10} {'CostRed':>10} {'Unsafe':>10} {'F-DONE':>10}")
372
+ print("-"*75)
373
+ frontier_cost = results["always_frontier"]["avg_cost"]
374
+ for name, r in sorted(results.items(), key=lambda x: (-x[1]["success"], x[1]["avg_cost"])):
375
+ cr = (1 - r["avg_cost"]/frontier_cost)*100
376
+ 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}")
377
+
378
+ print(f"\n\nDONE! Models saved to /app/router_models/")
379
+
380
+ # ─── RouteLLM-Style Binary Router ────────────────────────────────────
381
+ print("\n\n[8] Training RouteLLM-style binary classifiers...")
382
+ print(" (For each tier pair, train: should we route to cheaper or more expensive tier?)")
383
+
384
+ # For each tier boundary, train a binary classifier
385
+ # tier_boundary[t] = P(should use tier >= t | query)
386
+ # Route to the first tier where the boundary classifier says "yes, this is enough"
387
+
388
+ boundary_clfs = {}
389
+ for boundary in range(2, 6):
390
+ # Label: 1 if optimal_tier < boundary (cheaper tier is sufficient)
391
+ # 0 if optimal_tier >= boundary (need this tier or higher)
392
+ y_boundary = np.array([1 if traces[i]["opt"] < boundary else 0 for i in range(len(traces))])
393
+
394
+ y_tr = y_boundary[idx_train]
395
+ y_te = y_boundary[idx_test]
396
+
397
+ neg = (y_tr == 0).sum()
398
+ pos = (y_tr == 1).sum()
399
+ spw = neg / max(pos, 1)
400
+
401
+ clf = xgb.XGBClassifier(
402
+ n_estimators=150, max_depth=5, learning_rate=0.1,
403
+ subsample=0.8, colsample_bytree=0.8,
404
+ scale_pos_weight=min(spw, 3.0),
405
+ objective="binary:logistic", eval_metric="logloss",
406
+ random_state=42, verbosity=0,
407
+ )
408
+ clf.fit(X_train, y_tr)
409
+
410
+ y_pred = clf.predict(X_test)
411
+ acc = accuracy_score(y_te, y_pred)
412
+ f1 = f1_score(y_te, y_pred, zero_division=0)
413
+
414
+ boundary_clfs[boundary] = clf
415
+ rate = (y_tr == 0).mean() # fraction that needs this tier
416
+ print(f" Boundary {boundary}: acc={acc:.3f}, f1={f1:.3f}, needs_tier={rate:.3f}")
417
+
418
+ def route_cascade_binary(x, t):
419
+ """RouteLLM-style cascade: check each boundary, route to first that passes."""
420
+ if x.ndim == 1:
421
+ x = x.reshape(1, -1)
422
+ floor = TASK_FLOOR.get(t["tt"], 2)
423
+
424
+ # Start at floor, check if we need higher
425
+ current_tier = floor
426
+
427
+ for boundary in range(floor + 1, 6):
428
+ # boundary_clfs[boundary] predicts P(optimal < boundary)
429
+ # If P(optimal < boundary) > threshold, we can stay below boundary
430
+ # i.e., if P(need tier >= boundary) > threshold, escalate
431
+ p_need_higher = boundary_clfs[boundary].predict_proba(x)[0, 0] # P(optimal >= boundary)
432
+ if p_need_higher > 0.4: # confidence threshold
433
+ current_tier = boundary
434
+ else:
435
+ break
436
+
437
+ return current_tier, {}
438
+
439
+ eval_router("cascade_binary_t0.4", route_cascade_binary)
440
+
441
+ def route_cascade_binary_t050(x, t):
442
+ if x.ndim == 1: x = x.reshape(1, -1)
443
+ floor = TASK_FLOOR.get(t["tt"], 2)
444
+ current_tier = floor
445
+ for boundary in range(floor + 1, 6):
446
+ p_need = boundary_clfs[boundary].predict_proba(x)[0, 0]
447
+ if p_need > 0.5:
448
+ current_tier = boundary
449
+ else:
450
+ break
451
+ return current_tier, {}
452
+
453
+ eval_router("cascade_binary_t0.5", route_cascade_binary_t050)
454
+
455
+ def route_cascade_binary_t030(x, t):
456
+ if x.ndim == 1: x = x.reshape(1, -1)
457
+ floor = TASK_FLOOR.get(t["tt"], 2)
458
+ current_tier = floor
459
+ for boundary in range(floor + 1, 6):
460
+ p_need = boundary_clfs[boundary].predict_proba(x)[0, 0]
461
+ if p_need > 0.3:
462
+ current_tier = boundary
463
+ else:
464
+ break
465
+ return current_tier, {}
466
+
467
+ eval_router("cascade_binary_t0.3", route_cascade_binary_t030)
468
+
469
+ # Save boundary classifiers
470
+ for boundary, clf in boundary_clfs.items():
471
+ clf.save_model(f"/app/router_models/boundary_{boundary}.json")
472
+ print(f" Saved boundary_{boundary}.json")
473
+
474
+ # ─── Final Final Comparison ───────────────────────────────────────────
475
+ print(f"\n\n{'='*80}")
476
+ print("FINAL COMPARISON v2 (WITH BINARY CASCADE ROUTER)")
477
+ print(f"{'='*80}")
478
+ print(f"\n{'Router':<25} {'Success':>10} {'AvgCost':>10} {'CostRed':>10} {'Unsafe':>10} {'F-DONE':>10}")
479
+ print("-"*75)
480
+ frontier_cost = results["always_frontier"]["avg_cost"]
481
+ for name, r in sorted(results.items(), key=lambda x: (-x[1]["success"], x[1]["avg_cost"])):
482
+ cr = (1 - r["avg_cost"]/frontier_cost)*100
483
+ # Only show key results
484
+ if name in ("oracle","always_frontier","heuristic_diff+1","safe_CARROT_t0.60",
485
+ "cascade_binary_t0.4","cascade_binary_t0.5","cascade_binary_t0.3",
486
+ "always_cheap"):
487
+ 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}")
488
+
489
+ # Find best Pareto
490
+ print("\n\nPARETO FRONTIER:")
491
+ pareto = []
492
+ for name, r in results.items():
493
+ if name in ("always_cheap",):
494
+ continue # skip dominated
495
+ dominated = False
496
+ for name2, r2 in results.items():
497
+ if name == name2: continue
498
+ if r2["success"] >= r["success"] and r2["avg_cost"] <= r["avg_cost"]:
499
+ if r2["success"] > r["success"] or r2["avg_cost"] < r["avg_cost"]:
500
+ dominated = True; break
501
+ if not dominated:
502
+ pareto.append((name, r))
503
+ cr = (1 - r["avg_cost"]/frontier_cost)*100
504
+ print(f" {name:<25} success={r['success']:.3f} cost={r['avg_cost']:.4f} costRed={cr:.1f}%")
505
+
506
+ # Save all results
507
+ with open("/app/router_models/eval_results.json", "w") as f:
508
+ json.dump(results, f, indent=2, default=str)
509
+ print(f"\n Saved eval_results.json")
510
+ print(f"\nDONE!")