-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrunner.py
More file actions
494 lines (435 loc) · 17.8 KB
/
Copy pathrunner.py
File metadata and controls
494 lines (435 loc) · 17.8 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
"""
Benchmark test execution engine.
Handles:
- Official mode: runs all tests against the official API and records baseline results
- Test mode: runs all tests against the relay service and compares with the baseline
"""
import json
import os
import re
import sys
import time
from dataclasses import dataclass, field, asdict
from datetime import datetime, timezone
from typing import Any, Optional
try:
from tqdm import tqdm
except ModuleNotFoundError:
def tqdm(iterable, **kwargs):
return iterable
try:
from llm_benchmark.api_client import APIClient, create_client
from llm_benchmark.tests import (
ALL_TESTS,
TOKENIZER_TESTS,
PROGRAMMING_TESTS,
get_test_by_id,
)
except ModuleNotFoundError:
from api_client import APIClient, create_client
from tests import (
ALL_TESTS,
TOKENIZER_TESTS,
PROGRAMMING_TESTS,
get_test_by_id,
)
@dataclass
class TestResult:
"""Result of a single test."""
test_id: str
test_name: str
category: str
passed: bool
score: float
details: str
elapsed_seconds: float = 0.0
token_count: Optional[int] = None
content: Optional[str] = None
baseline: Optional[dict] = None
metadata: Optional[dict] = None
def to_dict(self) -> dict:
d = asdict(self)
if self.content and len(self.content) > 500:
d["content"] = self.content[:500] + "..."
return d
@dataclass
class BenchmarkRun:
"""Complete benchmark run result."""
mode: str # 'official' or 'test'
api_type: str
model: str
base_url: Optional[str]
timestamp: str
results: list = field(default_factory=list)
total_tests: int = 0
passed_tests: int = 0
overall_score: float = 0.0
category_scores: dict = field(default_factory=dict)
temperature: float = 0.0
def calculate_summary(self):
"""Calculate summary statistics from results."""
self.total_tests = len(self.results)
self.passed_tests = sum(1 for r in self.results if r.passed)
self.overall_score = (
sum(r.score for r in self.results) / len(self.results)
if self.results
else 0.0
)
# Per-category scores
categories = {}
for r in self.results:
if r.category not in categories:
categories[r.category] = []
categories[r.category].append(r.score)
self.category_scores = {
cat: sum(scores) / len(scores) for cat, scores in categories.items()
}
def to_dict(self) -> dict:
return {
"mode": self.mode,
"api_type": self.api_type,
"model": self.model,
"base_url": self.base_url,
"timestamp": self.timestamp,
"temperature": self.temperature,
"total_tests": self.total_tests,
"passed_tests": self.passed_tests,
"overall_score": round(self.overall_score, 4),
"category_scores": {
k: round(v, 4) for k, v in self.category_scores.items()
},
"results": [r.to_dict() for r in self.results],
}
class BenchmarkRunner:
"""Executes benchmark tests against an API."""
def __init__(
self,
api_type: str,
api_key: str,
model: str,
base_url: Optional[str] = None,
temperature: float = 0.0,
top_p: float = 1.0,
max_tokens: int = 4096,
timeout: float = 120.0,
):
self.api_type = api_type
self.model = model
self.base_url = base_url
self.temperature = temperature
self.top_p = top_p
self.max_tokens = max_tokens
self.timeout = timeout
self.client = create_client(
api_type=api_type,
api_key=api_key,
model=model,
base_url=base_url,
temperature=temperature,
top_p=top_p,
max_tokens=max_tokens,
timeout=timeout,
)
# Programing test cache (code results from official run)
self._programming_cache = {}
def close(self):
self.client.close()
def run_test(self, test: dict, baseline_data: Optional[dict] = None) -> TestResult:
"""Execute a single test case."""
test_id = test["id"]
test_name = test["name"]
category = test["category"]
# Get baseline for this test if available
test_baseline = None
if baseline_data and test_id in baseline_data:
test_baseline = baseline_data[test_id]
start_time = time.time()
try:
# Preference-fingerprint tests need repeated stochastic samples, not
# a single temperature=0 completion.
if test.get("sample_count"):
samples = []
usage_totals = {
"prompt_tokens": 0,
"completion_tokens": 0,
"total_tokens": 0,
}
sample_count = int(test["sample_count"])
for _ in range(sample_count):
response = self.client.chat(
test["messages"],
temperature=test.get("temperature", self.temperature),
top_p=test.get("top_p", self.top_p),
max_tokens=test.get("max_tokens", self.max_tokens),
)
samples.append(response.content)
if response.usage.prompt_tokens is not None:
usage_totals["prompt_tokens"] += response.usage.prompt_tokens
if response.usage.completion_tokens is not None:
usage_totals["completion_tokens"] += response.usage.completion_tokens
if response.usage.total_tokens is not None:
usage_totals["total_tokens"] += response.usage.total_tokens
usage_dict = {
**usage_totals,
"samples": samples,
"sample_count": sample_count,
}
result = test["evaluator"]("", usage_dict, test_baseline)
metadata = result.get("metadata", {})
content = json.dumps(metadata.get("distribution", {}), ensure_ascii=False)
return TestResult(
test_id=test_id,
test_name=test_name,
category=category,
passed=result["passed"],
score=result["score"],
details=result["details"],
elapsed_seconds=time.time() - start_time,
token_count=usage_totals["prompt_tokens"],
content=content,
metadata=metadata,
)
# For tokenizer tests, we need the token count from the API response
if test.get("tokenizer_probe"):
response = self.client.chat(test["messages"])
token_count = response.usage.prompt_tokens
content = response.content
result = test["evaluator"](
content,
{"prompt_tokens": token_count},
test_baseline,
)
return TestResult(
test_id=test_id,
test_name=test_name,
category=category,
passed=result["passed"],
score=result["score"],
details=result["details"],
elapsed_seconds=time.time() - start_time,
token_count=token_count,
content=content[:200] if content else "",
)
# All other tests
response = self.client.chat(test["messages"])
content = response.content
usage_dict = {
"prompt_tokens": response.usage.prompt_tokens,
"completion_tokens": response.usage.completion_tokens,
"total_tokens": response.usage.total_tokens,
}
evaluator_baseline = None if test.get("llm_judge") and test_baseline else test_baseline
# For programming tests, check cache first
if category == "programming":
if test_id in self._programming_cache:
result = self._programming_cache[test_id]
else:
result = test["evaluator"](content, usage_dict, evaluator_baseline)
self._programming_cache[test_id] = result
else:
result = test["evaluator"](content, usage_dict, evaluator_baseline)
return TestResult(
test_id=test_id,
test_name=test_name,
category=category,
passed=result["passed"],
score=result["score"],
details=result["details"],
elapsed_seconds=time.time() - start_time,
token_count=response.usage.prompt_tokens,
content=content,
metadata=result.get("metadata"),
)
except Exception as e:
return TestResult(
test_id=test_id,
test_name=test_name,
category=category,
passed=False,
score=0.0,
details=f"Error: {type(e).__name__}: {str(e)[:300]}",
elapsed_seconds=time.time() - start_time,
content="",
)
def _extract_json_array(self, text: str) -> list[dict]:
"""Extract a JSON array from a judge response."""
match = re.search(r"```(?:json)?\s*([\s\S]*?)```", text)
if match:
text = match.group(1)
array_match = re.search(r"(\[[\s\S]*\])", text)
if array_match:
text = array_match.group(1)
parsed = json.loads(text.strip())
if not isinstance(parsed, list):
raise ValueError("Judge response was not a JSON array")
return [item for item in parsed if isinstance(item, dict)]
def _judge_prompt(self, category: str, items: list[dict]) -> list[dict]:
"""Ask the model under test to judge a batch of baseline/relay comparisons."""
payload = [
{
"test_id": item["test_id"],
"test_name": item["test_name"],
"official_baseline": item["official"],
"provider_output": item["actual"],
}
for item in items
]
instructions = (
"You are judging whether a routed model output is consistent with an official "
"baseline output for an LLM authenticity benchmark. Judge semantic consistency, "
"not exact wording. For identity tests, accept equivalent organization/model facts "
"and reject different model-family claims. For knowledge-boundary tests, accept "
"answers that name the same entity/fact even with wording differences. For alignment "
"tests, compare policy behavior: refusal vs conditional safe help vs procedural help, "
"and the safety boundary being applied.\n\n"
"Return ONLY a JSON array. Each item must be: "
"{\"test_id\": string, \"consistent\": boolean, \"score\": number between 0 and 1, "
"\"reason\": short string}. Use score 1 for clearly consistent, 0.7 for mostly "
"consistent, 0.4 for ambiguous/partial, 0 for inconsistent."
)
response = self.client.chat(
[
{"role": "system", "content": instructions},
{
"role": "user",
"content": (
f"Judge this {category} batch:\n"
+ json.dumps(payload, ensure_ascii=False, indent=2)
),
},
],
temperature=0.0,
top_p=1.0,
max_tokens=min(self.max_tokens, 2048),
)
return self._extract_json_array(response.content)
def apply_llm_judging(self, results: list[TestResult], baseline_data: Optional[dict], tests: Optional[list] = None) -> None:
"""Batch-judge dynamic-text tests using the model under test.
Deterministic tests keep their original evaluator scores. Tests opt into
this path with ``llm_judge: True`` in their test definition.
"""
if not baseline_data:
return
test_defs = {t["id"]: t for t in (tests if tests is not None else ALL_TESTS)}
batches: dict[str, list[dict]] = {}
result_map = {r.test_id: r for r in results}
for result in results:
test_def = test_defs.get(result.test_id)
baseline = baseline_data.get(result.test_id) if baseline_data else None
if not test_def or not test_def.get("llm_judge") or not baseline:
continue
batches.setdefault(result.category, []).append(
{
"test_id": result.test_id,
"test_name": result.test_name,
"official": baseline.get("content", ""),
"actual": result.content or "",
}
)
for category, items in batches.items():
try:
decisions = self._judge_prompt(category, items)
except Exception as exc:
for item in items:
result = result_map[item["test_id"]]
result.passed = False
result.score = 0.0
result.details = f"LLM judge failed: {type(exc).__name__}: {str(exc)[:220]}"
metadata = result.metadata or {}
metadata["llm_judge_error"] = str(exc)[:500]
result.metadata = metadata
continue
decision_map = {str(d.get("test_id")): d for d in decisions}
for item in items:
result = result_map[item["test_id"]]
decision = decision_map.get(item["test_id"])
if not decision:
result.passed = False
result.score = 0.0
result.details = "LLM judge omitted this test"
continue
try:
score = float(decision.get("score", 0.0))
except (TypeError, ValueError):
score = 0.0
score = max(0.0, min(1.0, score))
consistent = bool(decision.get("consistent")) or score >= 0.65
reason = str(decision.get("reason", ""))[:300]
result.passed = consistent and score >= 0.65
result.score = score
result.details = f"LLM judge: {reason}" if reason else "LLM judge completed"
metadata = result.metadata or {}
metadata["llm_judge"] = {
"consistent": consistent,
"score": score,
"reason": reason,
}
result.metadata = metadata
def run_all(
self,
baseline_file: Optional[str] = None,
max_retries: int = 2,
tests: Optional[list] = None,
) -> BenchmarkRun:
"""Run all benchmark tests.
Args:
baseline_file: Path to baseline JSON (for test mode).
max_retries: Number of retries for failed API calls.
tests: Optional subset of tests to run. Defaults to ALL_TESTS.
"""
# Load baseline data if provided
baseline_data = None
if baseline_file and os.path.exists(baseline_file):
with open(baseline_file, "r", encoding="utf-8") as f:
raw = json.load(f)
# The baseline is stored in the "results" dict keyed by test_id
if "results" in raw:
baseline_data = {}
for r in raw["results"]:
tid = r.get("test_id")
if tid:
baseline_data[tid] = r
else:
baseline_data = raw
print(f" Loaded baseline from: {baseline_file}")
test_list = tests if tests is not None else ALL_TESTS
mode = "test" if baseline_data else "official"
mode_label = "OFFICIAL (recording baseline)" if mode == "official" else "TEST (comparing)"
print(f"\n{'='*60}")
print(f" LLM Relay Authentication Benchmark")
print(f" Mode: {mode_label}")
print(f" API: {self.api_type.upper()} | Model: {self.model}")
if self.base_url:
print(f" Endpoint: {self.base_url}")
else:
print(f" Endpoint: (default for {self.api_type})")
print(f"{'='*60}\n")
results = []
for test in tqdm(test_list, desc="Running tests", unit="test"):
test_id = test["id"]
test_name = test["name"]
for attempt in range(1 + max_retries):
tr = self.run_test(test, baseline_data)
if tr.score > 0 or attempt >= max_retries:
break
if attempt < max_retries:
time.sleep(1)
results.append(tr)
# Short status line
status = "PASS" if tr.passed else "FAIL"
score_pct = f"{tr.score:.0%}"
print(f" [{status}] [{score_pct}] {test_id}: {test_name} ({tr.details[:80]})")
if baseline_data:
print(" Running LLM judge for dynamic-text comparisons...")
self.apply_llm_judging(results, baseline_data, test_list)
run = BenchmarkRun(
mode=mode,
api_type=self.api_type,
model=self.model,
base_url=self.base_url,
timestamp=datetime.now(timezone.utc).isoformat(),
results=results,
temperature=self.temperature,
)
run.calculate_summary()
return run