Repository navigation
Expand file tree
/
Copy pathrun_benchmark.py
More file actions
1607 lines (1376 loc) · 79.4 KB
/
Copy pathrun_benchmark.py
File metadata and controls
1607 lines (1376 loc) · 79.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import json
import time
import csv
import argparse
import inspect
from datetime import datetime
# Import core routing framework
from src.client import LLMClient
from src.router import HybridRouter
from src.evaluator import ResponseEvaluator, detect_programming_language
from src.style import S
# Reconfigure stdout to use UTF-8 to prevent encoding crashes on Windows consoles
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8")
# Global Telemetry Tracker for Non-Invasive Instrumentation
class TelemetryTracker:
def __init__(self):
self.active = False
self.reset()
def reset(self):
# Latencies
self.classifier_latency = 0.0
self.local_model_latency = 0.0
self.evaluator_latency = 0.0
self.repair_latency = 0.0
self.remote_model_latency = 0.0
# Stage-level prompt/completion token accounting
self.classifier_prompt_tokens = 0
self.classifier_completion_tokens = 0
self.local_prompt_tokens = 0
self.local_completion_tokens = 0
self.evaluator_prompt_tokens = 0
self.evaluator_completion_tokens = 0
self.repair_prompt_tokens = 0
self.repair_completion_tokens = 0
self.remote_prompt_tokens = 0
self.remote_completion_tokens = 0
# Helper states
self.repair_used = False
self.remote_fallback_occurred = False
self.local_attempts = 0
self.remote_attempts = 0
# Cache of last evaluation to avoid double evaluation
self.last_evaluated_query = None
self.last_evaluated_response = None
self.last_evaluation_result = None
tracker = TelemetryTracker()
# Frame inspection helpers to identify caller state without fragile string matching
def is_caller_repair():
try:
frame = inspect.currentframe()
while frame:
if frame.f_code.co_name == "_run_local_with_retry":
if "attempt" in frame.f_locals:
return True
frame = frame.f_back
except Exception:
pass
return False
def is_caller_self_critique():
try:
frame = inspect.currentframe()
while frame:
if frame.f_code.co_name == "_self_critique":
return True
frame = frame.f_back
except Exception:
pass
return False
# Monkeypatch LLMClient.call_local to intercept usage data directly
original_call_local = LLMClient.call_local
def wrapped_call_local(self, prompt, *args, **kwargs):
if not tracker.active:
return original_call_local(self, prompt, *args, **kwargs)
messages = []
system_prompt = kwargs.get("system_prompt")
if system_prompt:
messages.append({"role": "system", "content": system_prompt})
messages.append({"role": "user", "content": prompt})
temperature = kwargs.get("temperature", 0.2)
max_tokens = kwargs.get("max_tokens", 1000)
json_mode = kwargs.get("json_mode", False)
create_kwargs = {}
if json_mode:
create_kwargs["response_format"] = {"type": "json"}
start = time.perf_counter()
res_text = ""
pt_used = 0
ct_used = 0
try:
response = self.local_client.chat.completions.create(
model=self.local_model,
messages=messages,
temperature=temperature,
max_tokens=max_tokens,
**create_kwargs
)
res_text = response.choices[0].message.content
if hasattr(response, "usage") and response.usage:
pt_used = response.usage.prompt_tokens
ct_used = response.usage.completion_tokens
except Exception as e:
res_text = f"Error executing local query: {str(e)}"
elapsed = time.perf_counter() - start
# Fallback to tiktoken estimation consistently if client doesn't return usage
if pt_used == 0:
pt_used = self.estimate_tokens(prompt)
if system_prompt:
pt_used += self.estimate_tokens(system_prompt)
if ct_used == 0:
ct_used = self.estimate_tokens(res_text)
# Attribute tokens and latency to the correct stage
if is_caller_self_critique():
tracker.evaluator_prompt_tokens += pt_used
tracker.evaluator_completion_tokens += ct_used
elif is_caller_repair():
tracker.repair_prompt_tokens += pt_used
tracker.repair_completion_tokens += ct_used
tracker.repair_latency += elapsed
tracker.repair_used = True
else:
tracker.local_prompt_tokens += pt_used
tracker.local_completion_tokens += ct_used
tracker.local_model_latency += elapsed
tracker.local_attempts += 1
return res_text
# Monkeypatch LLMClient.call_remote to record remote tokens
original_call_remote = LLMClient.call_remote
def wrapped_call_remote(self, prompt, *args, **kwargs):
if not tracker.active:
return original_call_remote(self, prompt, *args, **kwargs)
start = time.perf_counter()
res, pt, ct = original_call_remote(self, prompt, *args, **kwargs)
elapsed = time.perf_counter() - start
tracker.remote_model_latency += elapsed
tracker.remote_prompt_tokens += pt
tracker.remote_completion_tokens += ct
tracker.remote_attempts += 1
return res, pt, ct
# Monkeypatch ResponseEvaluator.evaluate with cache to avoid double evaluation
original_evaluate = ResponseEvaluator.evaluate
def wrapped_evaluate(self, query, response, *args, **kwargs):
if not tracker.active:
return original_evaluate(self, query, response, *args, **kwargs)
# Check evaluation cache
if tracker.last_evaluated_query == query and tracker.last_evaluated_response == response:
return tracker.last_evaluation_result
start = time.perf_counter()
eval_res = original_evaluate(self, query, response, *args, **kwargs)
elapsed = time.perf_counter() - start
tracker.evaluator_latency += elapsed
tracker.last_evaluated_query = query
tracker.last_evaluated_response = response
tracker.last_evaluation_result = eval_res
return eval_res
# Apply monkeypatches
LLMClient.call_local = wrapped_call_local
LLMClient.call_remote = wrapped_call_remote
ResponseEvaluator.evaluate = wrapped_evaluate
def get_response_format(category, prompt):
cat_lower = category.lower()
prompt_lower = prompt.lower()
# 1. Check for json explicitly first
if "json" in prompt_lower or cat_lower == "json/xml":
if "xml" not in prompt_lower or "json" in prompt_lower:
return "json"
# 2. Detect programming language dynamically
lang = detect_programming_language(prompt)
if lang not in ("text", "code"):
return lang
# 3. Use category mappings if language is generic or not found
if cat_lower == "coding":
return lang if lang != "text" else "code"
if cat_lower == "sql":
return "sql"
if cat_lower == "regex":
return "text"
if lang == "code":
return "code"
return "text"
def get_selected_evaluator(query: str, response_format: str) -> str:
fmt = response_format.lower()
evaluators = []
from src.evaluator import (
ComparisonEvaluator, SummarizationEvaluator, ArchitectureEvaluator,
DebuggingEvaluator, JSONEvaluator, PythonEvaluator, CodeGenerationEvaluator
)
if ComparisonEvaluator.is_applicable(query):
evaluators.append("ComparisonEvaluator")
if SummarizationEvaluator.is_applicable(query):
evaluators.append("SummarizationEvaluator")
if ArchitectureEvaluator.is_applicable(query):
evaluators.append("ArchitectureEvaluator")
if DebuggingEvaluator.is_applicable(query):
evaluators.append("DebuggingEvaluator")
if JSONEvaluator.is_applicable(fmt):
evaluators.append("JSONEvaluator")
if PythonEvaluator.is_applicable(fmt):
evaluators.append("PythonEvaluator")
if CodeGenerationEvaluator.is_applicable(query, fmt):
evaluators.append("CodeGenerationEvaluator")
if not evaluators:
evaluators.append("GenericTextEvaluator")
return "+".join(evaluators)
def normalize_route(route):
"""Normalize routing decisions for comparison."""
if not route:
return "none"
r = route.lower()
if "local" in r:
return "local"
if "remote" in r:
return "remote"
return r
def generate_accuracy_svg(accuracies, output_path):
"""Generate a clean side-by-side vertical bar chart SVG for strategy accuracy."""
width = 500
height = 300
margin = 50
strategies = list(accuracies.keys())
# SVG construction
svg = [
f'<svg width="{width}" height="{height}" xmlns="http://www.w3.org/2000/svg" style="background:#1e1e2e; border-radius:8px; font-family:system-ui, sans-serif;">',
'<!-- Title -->',
'<text x="250" y="30" fill="#cdd6f4" font-size="16" font-weight="bold" text-anchor="middle">Accuracy (Pass Rate) by Strategy</text>',
'<!-- Grid lines -->'
]
for i in range(5):
y = margin + i * (height - 2 * margin) / 4
val = 100 - i * 25
svg.append(f'<line x1="{margin}" y1="{y}" x2="{width - margin}" y2="{y}" stroke="#45475a" stroke-dasharray="4"/>')
svg.append(f'<text x="{margin - 10}" y="{y + 4}" fill="#a6adc8" font-size="11" text-anchor="end">{val}%</text>')
bar_width = 60
gap = 40
colors = ["#f38ba8", "#89b4fa", "#f9e2af", "#a6e3a1"]
for i, (strat, val) in enumerate(accuracies.items()):
x = margin + gap + i * (bar_width + gap)
bar_height = (val / 100.0) * (height - 2 * margin)
y = height - margin - bar_height
color = colors[i % len(colors)]
# Draw bar
svg.append(f'<rect x="{x}" y="{y}" width="{bar_width}" height="{bar_height}" rx="4" fill="{color}"/>')
# Draw value label
svg.append(f'<text x="{x + bar_width/2}" y="{y - 8}" fill="#cdd6f4" font-size="12" font-weight="bold" text-anchor="middle">{val:.1f}%</text>')
# Draw X-axis label
label = strat.replace("always_", "").capitalize()
svg.append(f'<text x="{x + bar_width/2}" y="{height - margin + 20}" fill="#a6adc8" font-size="11" text-anchor="middle">{label}</text>')
svg.append('</svg>')
with open(output_path, "w", encoding="utf-8") as f:
f.write("\n".join(svg))
def generate_cost_svg(costs, output_path):
"""Generate a clean vertical bar chart SVG for total strategy costs."""
width = 500
height = 300
margin = 50
strategies = list(costs.keys())
values = list(costs.values())
max_val = max(values) if max(values) > 0 else 1.0
# SVG construction
svg = [
f'<svg width="{width}" height="{height}" xmlns="http://www.w3.org/2000/svg" style="background:#1e1e2e; border-radius:8px; font-family:system-ui, sans-serif;">',
'<!-- Title -->',
'<text x="250" y="30" fill="#cdd6f4" font-size="16" font-weight="bold" text-anchor="middle">Total API Cost ($)</text>',
'<!-- Grid lines -->'
]
for i in range(5):
y = margin + i * (height - 2 * margin) / 4
val = max_val - i * (max_val / 4)
svg.append(f'<line x1="{margin}" y1="{y}" x2="{width - margin}" y2="{y}" stroke="#45475a" stroke-dasharray="4"/>')
svg.append(f'<text x="{margin - 10}" y="{y + 4}" fill="#a6adc8" font-size="11" text-anchor="end">${val:.4f}</text>')
bar_width = 60
gap = 40
colors = ["#f38ba8", "#89b4fa", "#f9e2af", "#a6e3a1"]
for i, (strat, val) in enumerate(costs.items()):
x = margin + gap + i * (bar_width + gap)
bar_height = (val / max_val) * (height - 2 * margin) if max_val > 0 else 0
y = height - margin - bar_height
color = colors[i % len(colors)]
# Draw bar
svg.append(f'<rect x="{x}" y="{y}" width="{bar_width}" height="{bar_height}" rx="4" fill="{color}"/>')
# Draw value label
svg.append(f'<text x="{x + bar_width/2}" y="{y - 8}" fill="#cdd6f4" font-size="12" font-weight="bold" text-anchor="middle">${val:.4f}</text>')
# Draw X-axis label
label = strat.replace("always_", "").capitalize()
svg.append(f'<text x="{x + bar_width/2}" y="{height - margin + 20}" fill="#a6adc8" font-size="11" text-anchor="middle">{label}</text>')
svg.append('</svg>')
with open(output_path, "w", encoding="utf-8") as f:
f.write("\n".join(svg))
def run_benchmark():
parser = argparse.ArgumentParser(description="Hybrid LLM Router Benchmark Runner")
parser.add_argument("--limit", type=int, help="Limit execution to the first N prompts for faster debugging")
parser.add_argument("--strategies", type=str, help="Comma-separated list of strategies to evaluate (always_local, always_remote, fallback, predictive)")
parser.add_argument("--dry-run-calibration", action="store_true", help="Perform threshold calibration dry-run without writing to calibrated_thresholds.json")
parser.add_argument("--min-calibration-prompts", type=int, default=50, help="Minimum number of prompts required to persist calibrated thresholds")
parser.add_argument("--min-improvement", type=float, default=0.02, help="Minimum improvement in oracle routing accuracy to persist calibration")
parser.add_argument("--latency-tolerance", type=float, default=0.10, help="Allowable latency increase factor (e.g. 0.10 for 10 percent)")
parser.add_argument("--calibration-step", type=float, default=0.02, help="Grid search step size for threshold calibration")
parser.add_argument("--benchmark-version", type=str, default="1.1", help="Version identifier for the benchmark dataset")
args = parser.parse_args()
if args.limit is not None and args.limit < 1:
print(S.error("Error: --limit must be an integer greater than or equal to 1."))
sys.exit(1)
all_supported_strategies = ["always_local", "always_remote", "fallback", "predictive"]
if args.strategies:
strategies = [s.strip().lower() for s in args.strategies.split(",") if s.strip()]
for s in strategies:
if s not in all_supported_strategies:
print(S.error(f"Error: Strategy '{s}' is not supported. Choose from {all_supported_strategies}"))
sys.exit(1)
else:
strategies = all_supported_strategies
dataset_path = "input/benchmark_dataset.json"
if not os.path.exists(dataset_path):
print(S.error(f"Error: Dataset {dataset_path} not found. Run scripts/generate_dataset.py first."))
sys.exit(1)
print(S.header("\n Initializing LLM Client & Hybrid Router..."))
client = LLMClient()
router = HybridRouter(client=client)
evaluator = router.evaluator
with open(dataset_path, "r", encoding="utf-8") as f:
full_dataset = json.load(f)
total_dataset_size = len(full_dataset)
executed_size = total_dataset_size
skipped_size = 0
if args.limit is not None:
executed_size = min(args.limit, total_dataset_size)
skipped_size = total_dataset_size - executed_size
dataset = full_dataset[:executed_size]
print(S.warn(f"⚠️ Fast Development Mode: Limiting benchmark execution to first {executed_size} prompts."))
else:
dataset = full_dataset
results_by_strategy = {strat: [] for strat in strategies}
print(S.header(f"\n Starting Benchmark Run ({executed_size} prompts across {len(strategies)} strategies)..."))
total_runs = len(strategies) * executed_size
run_idx = 0
start_time_all = time.perf_counter()
# Execute loop
for prompt_idx, item in enumerate(dataset, 1):
query = item["prompt"]
category = item["category"]
difficulty = item["difficulty"]
id_str = item["id"]
fmt = get_response_format(category, query)
# Pre-calculate complexity report (Routing Overhead)
class_start = time.perf_counter()
report = router.analyze_complexity(query, response_format=fmt)
class_elapsed = time.perf_counter() - class_start
for strategy in strategies:
run_idx += 1
elapsed_all = time.perf_counter() - start_time_all
avg_time_per_run = elapsed_all / run_idx if run_idx > 1 else 0
remaining_runs = total_runs - run_idx
eta = remaining_runs * avg_time_per_run
# Print live progress
sys.stdout.write(f"\r\033[K[{run_idx}/{total_runs}] {strategy.upper()} | {category} | {difficulty.capitalize()} | Elapsed: {elapsed_all:.1f}s | ETA: {eta:.1f}s")
sys.stdout.flush()
# Reset tracker for non-invasive metrics
tracker.reset()
tracker.active = True
# Run routing system
try:
res = router.route_and_execute(
query,
strategy=strategy,
response_format=fmt,
no_cache=False
)
final_response = res.get("response", "")
except Exception as e:
res = {
"query": query,
"strategy": strategy,
"route_chosen": "error",
"response": f"Error: {e}",
"cost_dollars": 0.0,
"latency_sec": 0.0
}
final_response = f"Error: {e}"
tracker.active = False
# Evaluate final response (wrapped_evaluate uses cache internally to prevent double validation)
try:
eval_res = evaluator.evaluate(query, final_response, response_format=fmt)
eval_score = eval_res.quality_score
eval_passed = eval_res.passed
eval_criticals = eval_res.critical_failures
eval_status = getattr(eval_res, "status", "success")
eval_err_msg = getattr(eval_res, "evaluator_error", None)
except Exception as e:
eval_score = None
eval_passed = None
eval_criticals = [f"Runner caught evaluator crash: {e}"]
eval_status = "evaluation_error"
eval_err_msg = str(e)
# Language Diagnostics printing
detected_lang = detect_programming_language(query)
selected_eval = get_selected_evaluator(query, fmt)
is_coding = (category.lower() == "coding" or fmt in ("python", "javascript", "java", "cpp", "go", "rust", "typescript", "code", "sql", "bash", "c"))
if is_coding:
sys.stdout.write("\n")
print(f" [Language Diagnostics - {id_str} | {strategy.upper()}]")
print(f" - Detected programming language: {detected_lang}")
print(f" - Response format: {fmt}")
print(f" - Selected evaluator: {selected_eval}")
print(f" - Route chosen: {normalize_route(res.get('route_chosen'))}")
print(f" - Complexity score: {report.normalized_score:.2f}")
print(f" - Risk score: {report.risk_score:.2f}")
print()
# If the response was served from cache, recover token telemetry from the cache object
if res.get("cached", False):
route_norm = normalize_route(res.get("route_chosen"))
if route_norm == "local":
tracker.local_prompt_tokens = res.get("prompt_tokens_local", 0)
tracker.local_completion_tokens = res.get("completion_tokens_local", 0)
elif route_norm == "remote":
tracker.remote_prompt_tokens = res.get("prompt_tokens_remote", 0)
tracker.remote_completion_tokens = res.get("completion_tokens_remote", 0)
# Stage-level token sums
total_prompt_tokens = (
tracker.classifier_prompt_tokens +
tracker.local_prompt_tokens +
tracker.evaluator_prompt_tokens +
tracker.repair_prompt_tokens +
tracker.remote_prompt_tokens
)
total_completion_tokens = (
tracker.classifier_completion_tokens +
tracker.local_completion_tokens +
tracker.evaluator_completion_tokens +
tracker.repair_completion_tokens +
tracker.remote_completion_tokens
)
total_tokens = total_prompt_tokens + total_completion_tokens
# Latency breakdown (ensure routing_overhead maps to classifier_latency)
routing_overhead_sec = class_elapsed if strategy in ("predictive",) else 0.0
local_model_latency_sec = tracker.local_model_latency
remote_model_latency_sec = tracker.remote_model_latency
repair_latency_sec = tracker.repair_latency
evaluation_latency_sec = tracker.evaluator_latency
# Model latency is prompt inference + generation
model_latency_sec = local_model_latency_sec + remote_model_latency_sec + repair_latency_sec
# Total latency calculation (cached retrieves directly)
if res.get("cached", False):
total_latency_sec = res.get("latency_sec", 0.0)
else:
total_latency_sec = routing_overhead_sec + model_latency_sec + evaluation_latency_sec
record = {
"id": id_str,
"prompt": query,
"category": category,
"detected_programming_language": detected_lang,
"selected_evaluator": selected_eval,
"difficulty": difficulty,
"reasoning_level": item["reasoning_level"],
"estimated_complexity": item["estimated_complexity"],
"strategy": strategy,
"route_chosen": res.get("route_chosen"),
"route_chosen_normalized": normalize_route(res.get("route_chosen")),
"chosen_model": client.local_model if "local" in normalize_route(res.get("route_chosen")) else client.remote_model,
"routing_confidence": report.confidence,
"complexity_score": report.normalized_score,
"risk_score": report.risk_score,
# Detailed Stage-level Latencies
"routing_overhead_sec": routing_overhead_sec,
"local_model_latency_sec": local_model_latency_sec,
"remote_model_latency_sec": remote_model_latency_sec,
"repair_latency_sec": repair_latency_sec,
"evaluation_latency_sec": evaluation_latency_sec,
"model_latency_sec": model_latency_sec,
"total_latency_sec": total_latency_sec,
# Detailed Stage-level Tokens
"classifier_prompt_tokens": tracker.classifier_prompt_tokens,
"classifier_completion_tokens": tracker.classifier_completion_tokens,
"local_prompt_tokens": tracker.local_prompt_tokens,
"local_completion_tokens": tracker.local_completion_tokens,
"evaluator_prompt_tokens": tracker.evaluator_prompt_tokens,
"evaluator_completion_tokens": tracker.evaluator_completion_tokens,
"repair_prompt_tokens": tracker.repair_prompt_tokens,
"repair_completion_tokens": tracker.repair_completion_tokens,
"remote_prompt_tokens": tracker.remote_prompt_tokens,
"remote_completion_tokens": tracker.remote_completion_tokens,
"total_prompt_tokens": total_prompt_tokens,
"total_completion_tokens": total_completion_tokens,
"total_tokens": total_tokens,
# Response and evaluation
"response": final_response,
"evaluator_score": eval_score,
"evaluator_passed": eval_passed,
"evaluator_status": eval_status,
"evaluator_error": eval_err_msg,
"repair_used": tracker.repair_used,
"remote_fallback_occurred": res.get("fallback_triggered", False),
"cost_dollars": res.get("cost_dollars", 0.0),
"errors": ", ".join(eval_criticals) if eval_criticals else "",
"diagnostics_explanation": report.diagnostics.explanation if (report and report.diagnostics) else "",
"diagnostics_feature_scores": report.diagnostics.feature_scores if (report and report.diagnostics) else {},
"feature_contributions_version": report.diagnostics.feature_contributions_version if (report and report.diagnostics) else 1,
"feature_contributions": report.diagnostics.feature_contributions if (report and report.diagnostics) else {},
# Backward Compatibility Mappings
"total_latency": total_latency_sec,
"classifier_latency": routing_overhead_sec,
"evaluator_latency": evaluation_latency_sec,
"repair_latency": repair_latency_sec,
"input_tokens": total_prompt_tokens,
"output_tokens": total_completion_tokens
}
results_by_strategy[strategy].append(record)
time.sleep(0.01) # cooling sleep
print()
print(S.good("\n Execution complete. Establishing Cost-Optimal Routes & Normalizing routing labels..."))
# Establish Cost-Optimal Routes (ignoring unsolvable prompts)
cost_optimal_routes = {}
local_opts = 0
remote_opts = 0
no_opts = 0
for i in range(executed_size):
prompt_id = dataset[i]["id"]
query = dataset[i]["prompt"]
cat = dataset[i]["category"]
fmt = get_response_format(cat, query)
# Determine local_pass
local_pass = False
if "always_local" in results_by_strategy:
local_pass = results_by_strategy["always_local"][i]["evaluator_passed"]
else:
cached = router.cache.get(query, "always_local", fmt)
if cached:
try:
eval_res = evaluator.evaluate(query, cached["response"], response_format=fmt)
local_pass = eval_res.passed
except Exception:
local_pass = False
else:
try:
res = router.route_and_execute(query, strategy="always_local", response_format=fmt, no_cache=True)
eval_res = evaluator.evaluate(query, res.get("response", ""), response_format=fmt)
local_pass = eval_res.passed
router.cache.set(query, "always_local", fmt, None, res)
except Exception:
local_pass = False
# Determine remote_pass
remote_pass = False
if "always_remote" in results_by_strategy:
remote_pass = results_by_strategy["always_remote"][i]["evaluator_passed"]
else:
cached = router.cache.get(query, "always_remote", fmt)
if cached:
try:
eval_res = evaluator.evaluate(query, cached["response"], response_format=fmt)
remote_pass = eval_res.passed
except Exception:
remote_pass = False
else:
try:
res = router.route_and_execute(query, strategy="always_remote", response_format=fmt, no_cache=True)
eval_res = evaluator.evaluate(query, res.get("response", ""), response_format=fmt)
remote_pass = eval_res.passed
router.cache.set(query, "always_remote", fmt, None, res)
except Exception:
remote_pass = False
# Oracle route evaluation (Cost-Optimal Route)
if local_pass and remote_pass:
gt_route = "local"
local_opts += 1
elif not local_pass and remote_pass:
gt_route = "remote"
remote_opts += 1
elif local_pass and not remote_pass:
gt_route = "local"
local_opts += 1
else:
gt_route = "none" # Unsolvable
no_opts += 1
cost_optimal_routes[prompt_id] = gt_route
# Annotate records with Cost-Optimal Route comparison
for strategy in strategies:
for rec in results_by_strategy[strategy]:
rec["cost_optimal_route"] = cost_optimal_routes[rec["id"]]
rec["ground_truth_route"] = cost_optimal_routes[rec["id"]] # backward compatibility
norm_route = rec["route_chosen_normalized"]
rec["routing_match"] = (norm_route == rec["cost_optimal_route"])
# Calculate aggregates for side-by-side comparison
aggregates = {}
for strategy in strategies:
recs = results_by_strategy[strategy]
total_p = len(recs)
eval_errors = sum(1 for r in recs if r.get("evaluator_status") == "evaluation_error")
model_errors = sum(1 for r in recs if r.get("evaluator_status") == "model_error")
valid_evaluations = total_p - eval_errors - model_errors
passed_p = sum(1 for r in recs if r.get("evaluator_passed") is True)
accuracy = (passed_p / valid_evaluations * 100) if valid_evaluations > 0 else 0.0
avg_score = sum(r["evaluator_score"] for r in recs if r.get("evaluator_score") is not None) / valid_evaluations if valid_evaluations > 0 else 0.0
avg_overhead = sum(r["routing_overhead_sec"] for r in recs) / total_p if total_p > 0 else 0.0
avg_model_lat = sum(r["model_latency_sec"] for r in recs) / total_p if total_p > 0 else 0.0
avg_eval_lat = sum(r["evaluation_latency_sec"] for r in recs) / total_p if total_p > 0 else 0.0
avg_total_lat = sum(r["total_latency_sec"] for r in recs) / total_p if total_p > 0 else 0.0
avg_tokens = sum(r["total_tokens"] for r in recs) / total_p if total_p > 0 else 0.0
total_cost = sum(r["cost_dollars"] for r in recs)
avg_cost = total_cost / total_p
local_routed = sum(1 for r in recs if r["route_chosen_normalized"] == "local")
remote_routed = sum(1 for r in recs if r["route_chosen_normalized"] == "remote")
cost_per_success = total_cost / passed_p if passed_p > 0 else 0.0
aggregates[strategy] = {
"accuracy": accuracy,
"avg_score": avg_score,
"avg_overhead": avg_overhead,
"avg_model_latency": avg_model_lat,
"avg_eval_latency": avg_eval_lat,
"avg_latency": avg_total_lat, # maps to total avg latency
"avg_tokens": avg_tokens,
"total_cost": total_cost,
"avg_cost": avg_cost,
"cost_per_success": cost_per_success,
"local_percent": (local_routed / total_p * 100) if total_p > 0 else 0,
"remote_percent": (remote_routed / total_p * 100) if total_p > 0 else 0,
"repair_percent": (sum(1 for r in recs if r["repair_used"]) / total_p * 100) if total_p > 0 else 0,
"fallback_percent": (sum(1 for r in recs if r["remote_fallback_occurred"]) / total_p * 100) if total_p > 0 else 0,
"passed_count": passed_p,
"failed_count": sum(1 for r in recs if r.get("evaluator_status") == "failed"),
"eval_error_count": eval_errors,
"model_error_count": model_errors,
}
# Calculate Oracle Routing Baseline metrics (excluding unsolvable prompts where gt is "none")
oracle_tokens = 0
oracle_cost = 0.0
solvable_count = 0
for i in range(executed_size):
id_str = dataset[i]["id"]
gt = cost_optimal_routes[id_str]
# Exclude unsolvable prompts from routing accuracy and routing efficiency sums
if gt == "none":
continue
solvable_count += 1
query = dataset[i]["prompt"]
cat = dataset[i]["category"]
fmt = get_response_format(cat, query)
# Get always_local stats
local_tot = 0
local_cst = 0.0
if "always_local" in results_by_strategy:
local_tot = results_by_strategy["always_local"][i]["total_tokens"]
local_cst = results_by_strategy["always_local"][i]["cost_dollars"]
else:
cached = router.cache.get(query, "always_local", fmt)
if cached:
local_tot = client.estimate_tokens(query) + client.estimate_tokens(cached["response"])
local_cst = 0.0
# Get always_remote stats
remote_tot = 0
remote_cst = 0.0
if "always_remote" in results_by_strategy:
remote_tot = results_by_strategy["always_remote"][i]["total_tokens"]
remote_cst = results_by_strategy["always_remote"][i]["cost_dollars"]
else:
cached = router.cache.get(query, "always_remote", fmt)
if cached:
remote_tot = cached.get("prompt_tokens_remote", 0) + cached.get("completion_tokens_remote", 0)
remote_cst = cached.get("cost_dollars", 0.0)
if remote_tot == 0:
remote_tot = client.estimate_tokens(query) + client.estimate_tokens(cached["response"])
remote_cst = (remote_tot / 1_000_000.0) * client.remote_price_per_1m_tokens
if gt == "local":
oracle_tokens += local_tot
oracle_cost += local_cst
elif gt == "remote":
oracle_tokens += remote_tot
oracle_cost += remote_cst
# Calculate efficiencies only over comparable (solvable) prompts
pred_total_tokens = 0
pred_total_cost = 0.0
if "predictive" in results_by_strategy:
for i in range(executed_size):
if cost_optimal_routes[dataset[i]["id"]] != "none":
pred_total_tokens += results_by_strategy["predictive"][i]["total_tokens"]
pred_total_cost += results_by_strategy["predictive"][i]["cost_dollars"]
routing_efficiency = (oracle_tokens / pred_total_tokens) if pred_total_tokens > 0 else 0.0
token_efficiency_pct = routing_efficiency * 100
cost_ratio = (pred_total_cost / oracle_cost) if oracle_cost > 0 else 1.0
cost_efficiency_pct = (1.0 / cost_ratio * 100) if cost_ratio > 0 else 100.0
# Calculate Predictive Routing Accuracy (only on comparable/solvable prompts)
if "predictive" in results_by_strategy:
comparable_prompts = [r for r in results_by_strategy["predictive"] if r["cost_optimal_route"] in ("local", "remote")]
if comparable_prompts:
routing_matches = sum(1 for r in comparable_prompts if r["routing_match"])
pred_routing_accuracy = (routing_matches / len(comparable_prompts)) * 100
else:
pred_routing_accuracy = 0.0
else:
pred_routing_accuracy = 0.0
# Calculate Over-Routing and Under-Routing Ratios
over_routed_count = 0
under_routed_count = 0
if "predictive" in results_by_strategy:
for r in results_by_strategy["predictive"]:
norm_chosen = r["route_chosen_normalized"]
gt = r["cost_optimal_route"]
if norm_chosen == "remote" and gt in ("local", "none"):
over_routed_count += 1
elif norm_chosen == "local" and gt == "remote":
under_routed_count += 1
over_routing_ratio = (over_routed_count / executed_size) * 100
under_routing_ratio = (under_routed_count / executed_size) * 100
# Estimated savings compared to always-remote
remote_agg = aggregates.get("always_remote")
for strategy in strategies:
agg = aggregates[strategy]
if remote_agg:
token_savings_pct = 100 * (remote_agg["avg_tokens"] - agg["avg_tokens"]) / remote_agg["avg_tokens"] if remote_agg["avg_tokens"] > 0 else 0.0
cost_savings_pct = 100 * (remote_agg["total_cost"] - agg["total_cost"]) / remote_agg["total_cost"] if remote_agg["total_cost"] > 0 else 0.0
cost_savings_dlr = remote_agg["total_cost"] - agg["total_cost"]
else:
token_savings_pct = 0.0
cost_savings_pct = 0.0
cost_savings_dlr = 0.0
agg["token_savings_pct"] = max(token_savings_pct, 0.0)
agg["cost_savings_pct"] = max(cost_savings_pct, 0.0)
agg["cost_savings_dlr"] = max(cost_savings_dlr, 0.0)
# Per-Category Routing Distribution
category_metrics = {}
if "predictive" in results_by_strategy:
for r in results_by_strategy["predictive"]:
cat = r["category"]
if cat not in category_metrics:
category_metrics[cat] = {
"count": 0, "passed": 0, "latency": 0.0, "tokens": 0, "cost": 0.0,
"local_count": 0, "remote_count": 0, "repair_count": 0, "fallback_count": 0
}
cat_agg = category_metrics[cat]
cat_agg["count"] += 1
if r["evaluator_passed"]:
cat_agg["passed"] += 1
cat_agg["latency"] += r["total_latency_sec"]
cat_agg["tokens"] += r["total_tokens"]
cat_agg["cost"] += r["cost_dollars"]
if r["route_chosen_normalized"] == "local":
cat_agg["local_count"] += 1
elif r["route_chosen_normalized"] == "remote":
cat_agg["remote_count"] += 1
if r["repair_used"]:
cat_agg["repair_count"] += 1
if r["remote_fallback_occurred"]:
cat_agg["fallback_count"] += 1
for cat in category_metrics:
m = category_metrics[cat]
c = m["count"]
m["accuracy"] = (m["passed"] / c * 100) if c > 0 else 0.0
m["avg_latency"] = m["latency"] / c
m["avg_tokens"] = m["tokens"] / c
m["local_pct"] = (m["local_count"] / c * 100) if c > 0 else 0.0
m["remote_pct"] = (m["remote_count"] / c * 100) if c > 0 else 0.0
m["repair_pct"] = (m["repair_count"] / c * 100) if c > 0 else 0.0
m["fallback_pct"] = (m["fallback_count"] / c * 100) if c > 0 else 0.0
# Difficulty Breakdown
difficulty_metrics = {}
if "predictive" in results_by_strategy:
for r in results_by_strategy["predictive"]:
diff = r["difficulty"]
if diff not in difficulty_metrics:
difficulty_metrics[diff] = {"count": 0, "passed": 0, "tokens": 0, "cost": 0.0}
difficulty_metrics[diff]["count"] += 1
if r["evaluator_passed"]:
difficulty_metrics[diff]["passed"] += 1
difficulty_metrics[diff]["tokens"] += r["total_tokens"]
difficulty_metrics[diff]["cost"] += r["cost_dollars"]
for diff in difficulty_metrics:
m = difficulty_metrics[diff]
m["accuracy"] = (m["passed"] / m["count"] * 100) if m["count"] > 0 else 0.0
m["avg_tokens"] = m["tokens"] / m["count"]
# Sorting Top 20 lists according to correctness rules
pred_recs = results_by_strategy.get("predictive", [])
# 1. Routing Mistakes sorted by evaluator score ascending (worst first), then cost wasted descending
routing_mistakes = [r for r in pred_recs if not r["routing_match"] and r["cost_optimal_route"] != "none"]
routing_mistakes = sorted(routing_mistakes, key=lambda x: (x["evaluator_score"], -x["cost_dollars"]))[:20]
highest_token_prompts = sorted(pred_recs, key=lambda x: x["total_tokens"], reverse=True)[:20]
unnecessary_remote = [r for r in pred_recs if r["route_chosen_normalized"] == "remote" and r["cost_optimal_route"] == "local"]
unnecessary_remote = sorted(unnecessary_remote, key=lambda x: x["total_tokens"], reverse=True)[:20]
local_failures = [r for r in pred_recs if r["route_chosen_normalized"] == "local" and not r["evaluator_passed"]]
local_failures = sorted(local_failures, key=lambda x: x["complexity_score"], reverse=True)[:20]
# 2. Evaluator Mistakes: check for true error indicators in passed responses and self-critique conflicts
eval_discrepancies = []
for r in pred_recs:
resp_str = r.get("response") or ""
has_error_msg = "error executing" in resp_str.lower() or "traceback (most recent call" in resp_str.lower()
is_suspicious_pass = r["evaluator_passed"] and has_error_msg
is_critique_conflict = (not r["evaluator_passed"]) and (r["evaluator_score"] > 0.8) and (r["evaluator_tokens"] > 0)
if is_suspicious_pass or is_critique_conflict:
r["suspicion_reason"] = "Suspicious Pass (Error Msg)" if is_suspicious_pass else "Critique Conflict (High Score, Fail)"
eval_discrepancies.append(r)
evaluator_mistakes = sorted(eval_discrepancies, key=lambda x: x["evaluator_score"], reverse=True)[:20]
# Generate SVGs
generate_accuracy_svg({s: aggregates[s]["accuracy"] for s in strategies}, "output/accuracy_chart.svg")
generate_cost_svg({s: aggregates[s]["total_cost"] for s in strategies}, "output/cost_chart.svg")
# Write output/benchmark_results.csv (including granular token splits and backward compatibility columns)
csv_path = "output/benchmark_results.csv"
with open(csv_path, "w", encoding="utf-8", newline="") as f:
f.write(f"# Benchmark Dataset: {total_dataset_size} prompts\n")
f.write(f"# Executed: {executed_size}\n")
f.write(f"# Skipped: {skipped_size}\n")
f.write(f"# Status: {'Partial Run' if args.limit else 'Full Run'}\n")
writer = csv.writer(f)
headers = [
"id", "prompt", "category", "difficulty", "reasoning_level", "estimated_complexity",
"strategy", "route_chosen", "route_chosen_normalized", "chosen_model", "cost_optimal_route", "routing_match",
"routing_confidence", "complexity_score", "risk_score",
# Latencies
"routing_overhead_sec", "local_model_latency_sec", "remote_model_latency_sec", "repair_latency_sec", "evaluation_latency_sec", "model_latency_sec", "total_latency_sec",
# Tokens
"classifier_prompt_tokens", "classifier_completion_tokens",
"local_prompt_tokens", "local_completion_tokens",
"evaluator_prompt_tokens", "evaluator_completion_tokens",
"repair_prompt_tokens", "repair_completion_tokens",
"remote_prompt_tokens", "remote_completion_tokens",
"total_prompt_tokens", "total_completion_tokens", "total_tokens",
# Score / Metadata
"evaluator_score", "evaluator_passed", "repair_used", "remote_fallback_occurred", "cost_dollars", "errors",
# Backward Compatibility Headers
"ground_truth_route", "total_latency", "classifier_latency", "evaluator_latency", "repair_latency", "input_tokens", "output_tokens"
]
writer.writerow(headers)
for strategy in strategies:
for r in results_by_strategy[strategy]:
writer.writerow([
r["id"], r["prompt"], r["category"], r["difficulty"], r["reasoning_level"], r["estimated_complexity"],
r["strategy"], r["route_chosen"], r["route_chosen_normalized"], r["chosen_model"], r["cost_optimal_route"], r["routing_match"],
r["routing_confidence"], r["complexity_score"], r["risk_score"],
r["routing_overhead_sec"], r["local_model_latency_sec"], r["remote_model_latency_sec"], r["repair_latency_sec"], r["evaluation_latency_sec"], r["model_latency_sec"], r["total_latency_sec"],
r["classifier_prompt_tokens"], r["classifier_completion_tokens"],
r["local_prompt_tokens"], r["local_completion_tokens"],
r["evaluator_prompt_tokens"], r["evaluator_completion_tokens"],
r["repair_prompt_tokens"], r["repair_completion_tokens"],
r["remote_prompt_tokens"], r["remote_completion_tokens"],
r["total_prompt_tokens"], r["total_completion_tokens"], r["total_tokens"],
r["evaluator_score"], r["evaluator_passed"], r["repair_used"], r["remote_fallback_occurred"], r["cost_dollars"], r["errors"],
# Backward Compatibility Values
r["cost_optimal_route"], r["total_latency_sec"], r["routing_overhead_sec"], r["evaluation_latency_sec"], r["repair_latency_sec"], r["total_prompt_tokens"], r["total_completion_tokens"]
])
# Write output/benchmark_responses.json
responses_path = "output/benchmark_responses.json"
with open(responses_path, "w", encoding="utf-8") as f:
json.dump(results_by_strategy, f, indent=2, ensure_ascii=False)
# Write routing_analysis.csv