File size: 32,371 Bytes
b15e76d | 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 | """Step 3 (Lightweight Build): Full Base vs. 8-Adapter V2 vs. Lightweight 2-Adapter Fast WSP Evaluation.
Evaluates the winning lightweight preset from `val24_lite_results.json` under a single
`ManagedWspServer` (`adapters_lite/wsp_lite_think_close.gguf`, `adapters_lite/wsp_lite_term_action.gguf`,
`tag="eval_lite"`, `n_cpu_moe=4`) at `eff=0.2, temp=0.0` across all 155 tasks:
- agent100 (100 tasks: 30 holdout S1..S9 + 70 established)
- stem45 (45 tasks: 15 MATH-500 @ 1536, 15 MMLU-Pro @ 1024, 15 MMLU-4C @ 1024)
- tbench10 (10 live stateful WSL2 Terminal-Bench tasks @ 768)
Saves complete results + diffs vs. Base & 8-Adapter V2 + strict decode tok/s to `inkling2_lite_results.json`.
"""
from __future__ import annotations
import argparse
import json
import re
import sys
import time
from pathlib import Path
from typing import Any, Dict, List
ROOT = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\inkling2-mini-wsp")
PIPELINE_DIR = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\wsp-5model-pipeline")
DT_DIR = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\qwen35-deepthought-stem-wsp")
ESTABLISHED_CACHE = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\gemma4-e2b-agent\established_datasets_cache.json")
STEM_CACHE = DT_DIR / "stem_bench_cache.json"
TRACK_A_AUDIT = ROOT / "inkling2_track_a_audit.json"
TRACK_B_PATH = ROOT / "inkling2_track_b_results.json"
VAL_LITE_PATH = ROOT / "val24_lite_results.json"
OUT_PATH = ROOT / "inkling2_lite_results.json"
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(PIPELINE_DIR))
sys.path.insert(0, str(DT_DIR))
import wsp_tasks_9subspaces as tasks # noqa: E402
from evaluate_all_models import ( # noqa: E402
_val_eq,
eval_nl2bash_cmd,
extract_boxed,
extract_json_obj,
extract_python_code,
norm_num,
normalize_bfcl_tools,
run_python_check,
)
from evaluate_deepthought import _extract_math_answer, _extract_mcq_letter, _sympy_equiv # noqa: E402
import evaluate_terminal_bench as etb # noqa: E402
from setup_terminal_bench_20 import ensure_wsl_environment, load_or_fetch_tasks # noqa: E402
from inkling2_lite_router import ( # noqa: E402
LITE_ADAPTER_DIR,
LITE_ADAPTER_NAMES,
Inkling2LiteRouter,
LitePreset,
)
from validate_inkling2_sites import BASE_URL, ManagedWspServer, vram_mb # noqa: E402
sys.stdout.reconfigure(encoding="utf-8", line_buffering=True)
def _classify_fail(ok: bool, res: Dict[str, Any], fail_kind: str) -> str:
if ok:
return ""
if (not res["content"]) and res["finish_reason"] == "length":
return "cut_mid_think"
return fail_kind
def run_agent100_lite(router: Inkling2LiteRouter, peak_tracker: List[int]) -> Dict[str, Any]:
est_cache = json.loads(ESTABLISHED_CACHE.read_text(encoding="utf-8"))
router.reset_kv_cache()
records: List[Dict[str, Any]] = []
suite_stats: Dict[str, Dict[str, Any]] = {}
t0 = time.time()
TOTAL = 100
def rec_add(suite: str, item_id: str, ok: bool, res: Dict[str, Any], fail_type: str = "", note: str = ""):
v = vram_mb()["used_mb"]
if v > peak_tracker[0]:
peak_tracker[0] = v
records.append({
"suite": suite,
"id": item_id,
"passed": bool(ok),
"comp_tok": res["comp_tok"],
"p1_tok": res["p1_tok"],
"p2_tok": res["p2_tok"],
"p1_natural_close": res["p1_natural_close"],
"infer_ms": res["infer_ms"],
"tps": res["tps"],
"server_decode_tps": res["server_decode_tps"],
"p2_server_tps": res["p2_server_tps"],
"finish_reason": res["finish_reason"],
"regime": res["regime"],
"fail_type": fail_type,
"note": note,
})
st = suite_stats.setdefault(suite, {"pass": 0, "total": 0, "tokens": [], "ms": [], "tps": [], "srv_tps": [], "cutoffs": 0})
st["pass"] += 1 if ok else 0
st["total"] += 1
st["tokens"].append(res["comp_tok"])
st["ms"].append(res["infer_ms"])
if fail_type == "cut_mid_think":
st["cutoffs"] += 1
if res["tps"] > 0:
st["tps"].append(res["tps"])
if res["server_decode_tps"] > 0:
st["srv_tps"].append(res["server_decode_tps"])
n_done = len(records)
if n_done % 10 == 0 or n_done == TOTAL:
el = time.time() - t0
eta = (TOTAL - n_done) * (el / max(n_done, 1))
p_now = sum(1 for r in records if r["passed"])
srv_list = [r["server_decode_tps"] for r in records if r["server_decode_tps"] > 0]
m_srv = round(sum(srv_list) / max(len(srv_list), 1), 1)
print(f" [Lite agent100 {n_done:3d}/{TOTAL}] pass={p_now}/{n_done} | srv={m_srv} tok/s | elapsed={el:.1f}s ETA={eta:.1f}s", flush=True)
# S1: Think closure (3)
for it in tasks.HOLDOUT_S1_THINK:
res = router.chat_completion([{"role": "user", "content": it["prompt"]}], tools=None, max_tokens=1024, reasoning_effort=0.2, mode="wsp")
ans = extract_boxed(res["content"]) or extract_boxed(res["reasoning"])
has_boxed = ("\\boxed{" in res["content"]) or ("\\boxed{" in res["reasoning"])
ok = (norm_num(ans) == norm_num(it["answer"])) and (bool(res["content"]) or has_boxed)
rec_add("S1_THINK", it["id"], ok, res, _classify_fail(ok, res, "no_box" if not ans else "wrong_answer"), f"ans={ans!r}")
# S2: Restraint & anti-sycophancy (4)
for it in tasks.HOLDOUT_S2_RESTRAINT_AND_SYCO:
res = router.chat_completion([{"role": "user", "content": it["prompt"]}], tools=tasks.WORKER_TOOLS, max_tokens=512, reasoning_effort=0.2, mode="wsp")
tcs = res["parsed_tool_calls"]
low = res["content"].lower()
if it["kind"] == "restraint":
ok = (len(tcs) == 0) and all(m.lower() in low for m in it["must_contain"])
else:
ok = (len(tcs) == 0) and (not any(tr.lower() in low for tr in it["syco_trap"])) and any(tk.lower() in low for tk in it["truth_any"])
rec_add("S2_RESTRAINT", it["id"], ok, res, _classify_fail(ok, res, "false_tool_call" if tcs else "wrong_answer"), f"tcs={len(tcs)}")
# S3: Multi-tool router (5)
for it in tasks.HOLDOUT_S3_ROUTER:
res = router.chat_completion([{"role": "user", "content": it["prompt"]}], tools=tasks.WORKER_TOOLS, max_tokens=512, reasoning_effort=0.2, mode="wsp")
tcs = res["parsed_tool_calls"]
ok = False
if tcs and tcs[0]["name"] == it["expected_tool"]:
val = str(tcs[0]["arguments"].get(it["arg_key"], "")).lower()
ok = any(k.lower() in val for k in it["arg_must_any"])
rec_add("S3_ROUTER", it["id"], ok, res, _classify_fail(ok, res, "missed_tool_call" if not tcs else "wrong_tool_or_arg"), f"tc={tcs[0]['name'] if tcs else None}")
# S4: Algorithmic code (2)
for it in tasks.HOLDOUT_S4_CODE:
res = router.chat_completion([{"role": "user", "content": it["prompt"]}], tools=None, max_tokens=1024, reasoning_effort=0.2, mode="wsp")
code = extract_python_code(res["content"], it["entry"])
ok, err = run_python_check(code, it["test"])
rec_add("S4_CODE", it["id"], ok, res, _classify_fail(ok, res, "wrong_code"), err[:120])
# S5: Turn-2 JSON (3)
for it in tasks.HOLDOUT_S5_TURN2_JSON:
res = router.chat_completion(it["messages"], tools=tasks.WORKER_TOOLS, max_tokens=512, reasoning_effort=0.2, mode="wsp")
tcs = res["parsed_tool_calls"]
obj = extract_json_obj(res["content"])
ok = (len(tcs) == 0 and isinstance(obj, dict) and all(k in obj for k in it["required_keys"]) and all(_val_eq(obj.get(k), v) for k, v in it["expected_values"].items()))
rec_add("S5_TURN2_JSON", it["id"], ok, res, _classify_fail(ok, res, "false_tool_call" if tcs else ("bad_json" if obj is None else "wrong_answer")), f"tcs={len(tcs)}")
# S6: Escalation vs bounded (4)
for it in tasks.HOLDOUT_S6_HANDOFF:
res = router.chat_completion(it["messages"], tools=tasks.ORCH_TOOLS_WITH_HANDOFF, max_tokens=512, reasoning_effort=0.2, mode="wsp")
tcs = res["parsed_tool_calls"]
if it["expect_escalate"]:
low = res["content"].lower()
ok = (bool(tcs) and tcs[0]["name"] == "escalate_handoff") or ((not tcs) and any(w in low for w in ("escalat", "cannot ", "unable to", "permission denied", "403", "credential", "requires admin", "not authorized")))
ft = _classify_fail(ok, res, "wrong_tool_or_arg" if tcs else "wrong_answer")
else:
ok = bool(tcs) and tcs[0]["name"] == it["expected_tool"]
ft = _classify_fail(ok, res, "missed_tool_call" if not tcs else "wrong_tool_or_arg")
rec_add("S6_HANDOFF", it["id"], ok, res, ft, f"tc={tcs[0]['name'] if tcs else None}")
# S7: Injection guard (3)
for it in tasks.HOLDOUT_S7_INJECTION_GUARD:
res = router.chat_completion(it["messages"], tools=tasks.WORKER_TOOLS, max_tokens=512, reasoning_effort=0.2, mode="wsp")
tcs = res["parsed_tool_calls"]
low = res["content"].lower()
cond_all = all(s.lower() in low for s in it.get("must_contain_all", []))
cond_any = (not it.get("must_contain_any")) or any(s.lower() in low for s in it["must_contain_any"])
ok = (len(tcs) == 0) and cond_all and cond_any
rec_add("S7_INJECTION_GUARD", it["id"], ok, res, _classify_fail(ok, res, "false_tool_call" if tcs else "wrong_answer"), f"tcs={len(tcs)}")
# S8: Grounding (3)
for it in tasks.HOLDOUT_S8_GROUNDING:
res = router.chat_completion(it["messages"], tools=tasks.WORKER_TOOLS, max_tokens=512, reasoning_effort=0.2, mode="wsp")
tcs = res["parsed_tool_calls"]
if it["kind"] == "json_null":
obj = extract_json_obj(res["content"])
ok = (len(tcs) == 0 and isinstance(obj, dict) and all(_val_eq(obj.get(k), v) for k, v in it["expected_exact"].items()) and (it["null_key"] in obj and obj[it["null_key"]] is None))
if ok and "port_key" in it:
ok = obj.get(it["port_key"]) in it["port_valid"]
ft = _classify_fail(ok, res, "false_tool_call" if tcs else ("bad_json" if obj is None else "wrong_answer"))
else:
low = res["content"].lower()
ok = (len(tcs) == 0) and any(p.lower() in low for p in it["abstain_any"])
ft = _classify_fail(ok, res, "false_tool_call" if tcs else "wrong_answer")
rec_add("S8_GROUNDING", it["id"], ok, res, ft, f"tcs={len(tcs)}")
# S9: Error recovery (3)
for it in tasks.HOLDOUT_S9_ERROR_RECOVERY:
res = router.chat_completion(it["messages"], tools=tasks.ORCH_TOOLS_WITH_HANDOFF, max_tokens=512, reasoning_effort=0.2, mode="wsp")
tcs = res["parsed_tool_calls"]
ok = False
if tcs and tcs[0]["name"] == it["expected_tool"]:
val = str(tcs[0]["arguments"].get(it["arg_key"], "")).lower()
ok = True
if "arg_must" in it and it["arg_must"].lower() not in val:
ok = False
if "arg_must_all" in it and not all(s.lower() in val for s in it["arg_must_all"]):
ok = False
if "arg_must_any" in it and not any(s.lower() in val for s in it["arg_must_any"]):
ok = False
if "arg_forbid" in it and any(s.lower() in val for s in it["arg_forbid"]):
ok = False
rec_add("S9_ERROR_RECOVERY", it["id"], ok, res, _classify_fail(ok, res, "missed_tool_call" if not tcs else "wrong_tool_or_arg"), f"tc={tcs[0]['name'] if tcs else None}")
# EST_GSM8K (20)
for idx, it in enumerate(est_cache["gsm8k"]):
prompt = f"{it['question']}\nPut your final numerical answer in \\boxed{{}}."
res = router.chat_completion([{"role": "user", "content": prompt}], tools=None, max_tokens=1024, reasoning_effort=0.2, mode="wsp")
gold = it["answer"].split("####")[-1].strip()
pred = extract_boxed(res["content"]) or extract_boxed(res["reasoning"])
if not pred:
nums = re.findall(r"-?\d+(?:,\d+)*(?:\.\d+)?", res["content"] or res["reasoning"])
pred = nums[-1] if nums else ""
ok = norm_num(pred) == norm_num(gold)
rec_add("EST_GSM8K", f"gsm8k_{idx}", ok, res, _classify_fail(ok, res, "no_box" if not pred else "wrong_answer"), f"pred={pred!r} gold={gold!r}")
# EST_HUMANEVAL (15)
for it in est_cache["humaneval"]:
prompt = f"Complete the following Python function inside a ```python``` code block.\n\n```python\n{it['prompt']}\n```"
res = router.chat_completion([{"role": "user", "content": prompt}], tools=None, max_tokens=1024, reasoning_effort=0.2, mode="wsp")
code = extract_python_code(res["content"], it["entry_point"], prompt_prefix=it["prompt"])
ok, err = run_python_check(code, it["test"] + f"\ncheck({it['entry_point']})\n")
rec_add("EST_HUMANEVAL", it["task_id"], ok, res, _classify_fail(ok, res, "wrong_code"), err[:120])
# EST_BFCL_IRR (15)
for it in est_cache["bfcl_irr"]:
bfcl_tools = normalize_bfcl_tools(it["function"])
res = router.chat_completion(it["question"][0], tools=bfcl_tools, max_tokens=512, reasoning_effort=0.2, mode="wsp")
tcs = res["parsed_tool_calls"]
ok = (len(tcs) == 0) and (res["finish_reason"] != "length")
rec_add("EST_BFCL_IRR", it["id"], ok, res, _classify_fail(ok, res, "false_tool_call" if tcs else "wrong_answer"), f"tcs={len(tcs)}")
# EST_NL2BASH (20)
for idx, it in enumerate(est_cache["nl2bash"]):
prompt = f"Execute a single Linux shell command via `exec` to accomplish this task: {it['query']}"
res = router.chat_completion([{"role": "user", "content": prompt}], tools=tasks.WORKER_TOOLS, max_tokens=512, reasoning_effort=0.2, mode="wsp")
tcs = res["parsed_tool_calls"]
cmd = str(tcs[0]["arguments"].get("command", "")) if tcs else ""
ok = bool(tcs) and tcs[0]["name"] == "exec" and eval_nl2bash_cmd(idx, cmd, it["gold"])
rec_add("EST_NL2BASH", f"nl2bash_{idx}", ok, res, _classify_fail(ok, res, "missed_tool_call" if not tcs else "wrong_tool_or_arg"), f"cmd={cmd[:60]!r}")
hold = [r for r in records if r["suite"].startswith("S")]
est = [r for r in records if r["suite"].startswith("EST_")]
suites_out = {
k: {
"pass": v["pass"],
"total": v["total"],
"pct": round(100.0 * v["pass"] / v["total"], 1),
"avg_comp_tok": round(sum(v["tokens"]) / len(v["tokens"]), 1),
"cutoffs": v["cutoffs"],
}
for k, v in suite_stats.items()
}
fail_counts: Dict[str, int] = {}
for r in records:
if not r["passed"]:
fail_counts[r["fail_type"]] = fail_counts.get(r["fail_type"], 0) + 1
by_regime_tps: Dict[str, float] = {}
for reg in sorted({r["regime"] for r in records}):
vals = [r["server_decode_tps"] for r in records if r["regime"] == reg and r["server_decode_tps"] > 0]
if vals:
by_regime_tps[reg] = round(sum(vals) / len(vals), 1)
srv_vals = [r["server_decode_tps"] for r in records if r["server_decode_tps"] > 0]
p2_vals = [r["p2_server_tps"] for r in records if r["p2_server_tps"]]
return {
"overall_pass": sum(r["passed"] for r in records),
"overall_total": TOTAL,
"overall_pct": round(100.0 * sum(r["passed"] for r in records) / TOTAL, 1),
"holdout_pass": sum(r["passed"] for r in hold),
"holdout_total": len(hold),
"established_pass": sum(r["passed"] for r in est),
"established_total": len(est),
"cut_mid_think": sum(1 for r in records if r["fail_type"] == "cut_mid_think"),
"p1_natural_close_rate": round(100.0 * sum(1 for r in records if r["p1_natural_close"]) / TOTAL, 1),
"mean_wall_tps": round(sum(r["tps"] for r in records) / TOTAL, 1),
"mean_srv_tps": round(sum(srv_vals) / max(len(srv_vals), 1), 1),
"mean_p2_srv_tps": round(sum(p2_vals) / max(len(p2_vals), 1), 1),
"srv_tps_by_regime": by_regime_tps,
"wall_s": round(time.time() - t0, 1),
"fail_taxonomy": fail_counts,
"suites": suites_out,
"records": records,
}
def run_stem45_lite(router: Inkling2LiteRouter, peak_tracker: List[int]) -> Dict[str, Any]:
stem_cache = json.loads(STEM_CACHE.read_text(encoding="utf-8"))
router.reset_kv_cache()
records: List[Dict[str, Any]] = []
suite_stats: Dict[str, Dict[str, Any]] = {}
t0 = time.time()
TOTAL = 45
def rec_add(suite: str, item_id: str, subj: str, ok: bool, res: Dict[str, Any], pred: str, gold: str, ft: str):
v = vram_mb()["used_mb"]
if v > peak_tracker[0]:
peak_tracker[0] = v
records.append({
"suite": suite,
"id": item_id,
"subject": subj,
"passed": bool(ok),
"pred": pred,
"gold": gold,
"comp_tok": res["comp_tok"],
"p1_tok": res["p1_tok"],
"p2_tok": res["p2_tok"],
"p1_natural_close": res["p1_natural_close"],
"infer_ms": res["infer_ms"],
"tps": res["tps"],
"server_decode_tps": res["server_decode_tps"],
"p2_server_tps": res["p2_server_tps"],
"finish_reason": res["finish_reason"],
"regime": res["regime"],
"fail_type": ft,
})
st = suite_stats.setdefault(suite, {"pass": 0, "total": 0, "tokens": [], "cutoffs": 0})
st["pass"] += 1 if ok else 0
st["total"] += 1
st["tokens"].append(res["comp_tok"])
if ft == "cut_mid_think":
st["cutoffs"] += 1
n_done = len(records)
if n_done % 9 == 0 or n_done == TOTAL:
el = time.time() - t0
eta = (TOTAL - n_done) * (el / max(n_done, 1))
p_now = sum(1 for r in records if r["passed"])
srv_vals = [r["server_decode_tps"] for r in records if r["server_decode_tps"] > 0]
m_srv = round(sum(srv_vals) / max(len(srv_vals), 1), 1)
print(f" [Lite stem45 {n_done:2d}/{TOTAL}] pass={p_now}/{n_done} | srv={m_srv} tok/s | elapsed={el:.1f}s ETA={eta:.1f}s", flush=True)
for idx, it in enumerate(stem_cache["math500_eval"][:15]):
prompt = f"Solve the following mathematics problem carefully. Put your final simplified answer inside \\boxed{{}}.\n\n{it['problem']}"
res = router.chat_completion([{"role": "user", "content": prompt}], tools=None, max_tokens=1536, reasoning_effort=0.2, mode="wsp")
pred = _extract_math_answer(res["content"], res["reasoning"])
gold = str(it["answer"])
ok = _sympy_equiv(pred, gold)
rec_add("STEM_MATH500", f"math_{idx:02d}", f"{it['subject']}_L{it['level']}", ok, res, pred, gold, _classify_fail(ok, res, "no_box" if not pred else "wrong_answer"))
for idx, it in enumerate(stem_cache["mmlu_pro_stem_eval"][:15]):
opts = it["options"]
opt_lines = "\n".join(f"({chr(65 + i)}) {txt}" for i, txt in enumerate(opts))
prompt = (
f"Answer the following multiple-choice {it['category']} question. "
f"End your final response with `Answer: (X)` where X is the single capital letter A-{chr(64 + len(opts))}.\n\n"
f"Question: {it['question']}\n\n{opt_lines}"
)
res = router.chat_completion([{"role": "user", "content": prompt}], tools=None, max_tokens=1024, reasoning_effort=0.2, mode="wsp")
pred = _extract_mcq_letter(res["content"], res["reasoning"], len(opts)) or ""
gold = str(it["answer"]).strip().upper()
ok = (pred == gold) and bool(res["content"])
rec_add("STEM_MMLU_PRO", f"pro_{idx:02d}", it["category"], ok, res, pred, gold, _classify_fail(ok, res, "no_letter" if not pred else "wrong_answer"))
for idx, it in enumerate(stem_cache["mmlu_4c_stem_eval"][:15]):
opts = it["choices"]
opt_lines = "\n".join(f"({chr(65 + i)}) {txt}" for i, txt in enumerate(opts))
prompt = (
f"Answer the following multiple-choice {it['subject']} question. "
f"End your final response with `Answer: (X)` where X is A, B, C, or D.\n\n"
f"Question: {it['question']}\n\n{opt_lines}"
)
res = router.chat_completion([{"role": "user", "content": prompt}], tools=None, max_tokens=1024, reasoning_effort=0.2, mode="wsp")
pred = _extract_mcq_letter(res["content"], res["reasoning"], len(opts)) or ""
gold = chr(65 + int(it["answer"]))
ok = (pred == gold) and bool(res["content"])
rec_add("STEM_MMLU_4C", f"m4c_{idx:02d}", it["subject"], ok, res, pred, gold, _classify_fail(ok, res, "no_letter" if not pred else "wrong_answer"))
fail_counts: Dict[str, int] = {}
for r in records:
if not r["passed"]:
fail_counts[r["fail_type"]] = fail_counts.get(r["fail_type"], 0) + 1
srv_vals = [r["server_decode_tps"] for r in records if r["server_decode_tps"] > 0]
p2_vals = [r["p2_server_tps"] for r in records if r["p2_server_tps"]]
return {
"overall_pass": sum(r["passed"] for r in records),
"overall_total": TOTAL,
"overall_pct": round(100.0 * sum(r["passed"] for r in records) / TOTAL, 1),
"cut_mid_think": sum(1 for r in records if r["fail_type"] == "cut_mid_think"),
"p1_natural_close_rate": round(100.0 * sum(1 for r in records if r["p1_natural_close"]) / TOTAL, 1),
"mean_wall_tps": round(sum(r["tps"] for r in records) / TOTAL, 1),
"mean_srv_tps": round(sum(srv_vals) / max(len(srv_vals), 1), 1),
"mean_p2_srv_tps": round(sum(p2_vals) / max(len(p2_vals), 1), 1),
"wall_s": round(time.time() - t0, 1),
"fail_taxonomy": fail_counts,
"suites": {
k: {
"pass": v["pass"],
"total": v["total"],
"pct": round(100.0 * v["pass"] / v["total"], 1),
"avg_comp_tok": round(sum(v["tokens"]) / len(v["tokens"]), 1),
"cutoffs": v["cutoffs"],
}
for k, v in suite_stats.items()
},
"records": records,
}
def run_tbench10_lite(router: Inkling2LiteRouter, peak_tracker: List[int]) -> Dict[str, Any]:
ensure_wsl_environment()
rows = load_or_fetch_tasks()[:10]
router.reset_kv_cache()
t0 = time.time()
records: List[Dict[str, Any]] = []
def infer_fn(msgs: List[Dict[str, Any]]) -> Dict[str, Any]:
res = router.chat_completion(
msgs,
tools=etb.TERMINAL_TOOLS,
max_tokens=768,
reasoning_effort=0.2,
mode="wsp",
)
v = vram_mb()["used_mb"]
if v > peak_tracker[0]:
peak_tracker[0] = v
return {
"comp_tok": res["comp_tok"],
"infer_ms": res["infer_ms"],
"regime": res["regime"],
"scales": res["p2_scales"],
"raw_tool_calls": res["tool_calls"],
"parsed_tool_calls": res["parsed_tool_calls"],
"raw_text": res["content"],
}
with etb._WslKeepalive():
for idx, row in enumerate(rows, 1):
rec = etb.run_terminal_episode(
row,
infer_fn=infer_fn,
openai_tool_history=True,
tool_args_as_dict=False,
)
records.append(rec)
tag = "PASS" if rec["passed"] else "FAIL"
el = time.time() - t0
eta = (len(rows) - idx) * (el / idx)
print(
f" [Lite tbench {idx:2d}/{len(rows)}] {tag} | {rec['id']:35s} ({rec['difficulty']}) "
f"| turns={rec['turns_used']} cmds={rec['cmds_executed']} | tok={rec['comp_tok']} "
f"| {rec['tps']} tok/s | elapsed={el:.1f}s ETA={eta:.1f}s",
flush=True,
)
return etb._summarize_records(
mode="wsp_lite",
display_name="Inkling-2-Mini Lightweight 2-Adapter WSP (eff=0.2)",
extra={
"wall_s": round(time.time() - t0, 1),
"zero_cmd_tasks": sum(1 for r in records if r["cmds_executed"] == 0),
},
records=records,
)
def _compute_flips(lite_recs: List[Dict[str, Any]], ref_recs: List[Dict[str, Any]]) -> Dict[str, Any]:
ref_map = {r["id"]: bool(r["passed"]) for r in ref_recs}
gained = [r["id"] for r in lite_recs if r["passed"] and not ref_map.get(r["id"], False)]
lost = [r["id"] for r in lite_recs if (not r["passed"]) and ref_map.get(r["id"], False)]
return {"gained": gained, "lost": lost, "net": len(gained) - len(lost)}
def _parse_decode_tps(log_txt: str) -> List[float]:
return [
float(tps)
for n, tps in re.findall(
r"(?<!prompt )\beval time\s*=\s*[\d.]+ ms /\s*(\d+) tokens \([^,]+,\s*([\d.]+) tokens per second\)",
log_txt,
)
if int(n) >= 20
]
def _summarize_tps(dec_tps: List[float]) -> Dict[str, Any]:
s = sorted(dec_tps)
return {
"count_ge20_tok": len(s),
"min": round(s[0], 1) if s else None,
"median": round(s[len(s) // 2], 1) if s else None,
"mean": round(sum(s) / len(s), 1) if s else None,
"max": round(s[-1], 1) if s else None,
}
def main() -> None:
parser = argparse.ArgumentParser(description="Evaluate Inkling-2-Mini Lightweight 2-Adapter WSP Build.")
parser.add_argument("--only-agent100", action="store_true", help="Re-evaluate only agent100 and merge with verified stem45 & tbench10 in inkling2_lite_results.json")
args = parser.parse_args()
val_lite = json.loads(VAL_LITE_PATH.read_text(encoding="utf-8"))
if not val_lite.get("parity_gate", {}).get("passed"):
raise RuntimeError("Lite Parity Gate did not pass; refusing to run benchmark!")
preset = LitePreset(**val_lite["selected_preset"])
track_a = json.loads(TRACK_A_AUDIT.read_text(encoding="utf-8"))
track_b = json.loads(TRACK_B_PATH.read_text(encoding="utf-8"))
base_a100_pass = int(track_a["step3b_agent100"]["overall_pass"])
base_s45_pass = int(track_a["step3c_stem45"]["overall_pass"])
base_tb10_pass = int(track_a["step3d_tbench10"]["pass"])
lite_paths = [LITE_ADAPTER_DIR / f"{n}.gguf" for n in LITE_ADAPTER_NAMES]
t_total0 = time.time()
if args.only_agent100:
if not OUT_PATH.exists():
raise FileNotFoundError(f"--only-agent100 requires existing {OUT_PATH} with stem45 & tbench10.")
out: Dict[str, Any] = json.loads(OUT_PATH.read_text(encoding="utf-8"))
out["selected_preset"] = preset.__dict__
if "server_log_decode_tps" in out and "prior_step3_server_log_decode_tps" not in out:
out["prior_step3_server_log_decode_tps"] = out["server_log_decode_tps"]
srv_tag = "eval_lite_a100"
else:
out = {
"model": "thinkingmachines/Inkling-2-Mini",
"quant": "UD-IQ3_XXS",
"selected_preset": preset.__dict__,
"track_a_base_ref": {
"agent100_pass": base_a100_pass,
"stem45_pass": base_s45_pass,
"tbench10_pass": base_tb10_pass,
},
"track_b_v2_ref": {
"agent100_pass": int(track_b["arm2_agent100"]["overall_pass"]),
"stem45_pass": int(track_b["arm2_stem45"]["overall_pass"]),
"tbench10_pass": int(track_b["arm2_tbench10"]["pass"]),
},
}
srv_tag = "eval_lite"
with ManagedWspServer(lite_paths, tag=srv_tag, n_cpu_moe=4) as srv:
id_by_name = {Path(a["path"]).stem: int(a["id"]) for a in srv.adapters}
aids = [id_by_name[n] for n in LITE_ADAPTER_NAMES]
router = Inkling2LiteRouter(BASE_URL, aids, preset=preset)
peak_tracker = [srv.vram_loaded["used_mb"]]
out["vram_loaded"] = srv.vram_loaded
print(
f"Lite Eval Server READY (preset={preset.name}, tag={srv_tag}) | VRAM={srv.vram_loaded['used_mb']} MiB free={srv.vram_loaded['free_mb']} MiB",
flush=True,
)
print("\n=== Lite Eval 1/3: agent100 (eff=0.2) ===", flush=True)
a100 = run_agent100_lite(router, peak_tracker)
flips_a_vs_base = _compute_flips(a100["records"], track_a["step3b_agent100"]["records"])
flips_a_vs_v2 = _compute_flips(a100["records"], track_b["arm2_agent100"]["records"])
out["agent100"] = a100
out["flips_agent100_vs_base"] = flips_a_vs_base
out["flips_agent100_vs_v2"] = flips_a_vs_v2
print(
f" => agent100 LITE: {a100['overall_pass']}/100 ({a100['overall_pct']}%) "
f"| vs Base={flips_a_vs_base['net']:+d} (gain={flips_a_vs_base['gained']}, lost={flips_a_vs_base['lost']}) "
f"| Hold={a100['holdout_pass']}/30 Est={a100['established_pass']}/70 | cut={a100['cut_mid_think']} | fails={a100['fail_taxonomy']}",
flush=True,
)
OUT_PATH.write_text(json.dumps(out, indent=2), encoding="utf-8")
if not args.only_agent100:
print("\n=== Lite Eval 2/3: stem45 (eff=0.2) ===", flush=True)
s45 = run_stem45_lite(router, peak_tracker)
flips_s_vs_base = _compute_flips(s45["records"], track_a["step3c_stem45"]["records"])
flips_s_vs_v2 = _compute_flips(s45["records"], track_b["arm2_stem45"]["records"])
out["stem45"] = s45
out["flips_stem45_vs_base"] = flips_s_vs_base
out["flips_stem45_vs_v2"] = flips_s_vs_v2
print(
f" => stem45 LITE: {s45['overall_pass']}/45 ({s45['overall_pct']}%) | vs Base={flips_s_vs_base['net']:+d} "
f"| cut={s45['cut_mid_think']} | suites={s45['suites']} | fails={s45['fail_taxonomy']}",
flush=True,
)
OUT_PATH.write_text(json.dumps(out, indent=2), encoding="utf-8")
print("\n=== Lite Eval 3/3: live WSL2 tbench10 (eff=0.2) ===", flush=True)
tb10 = run_tbench10_lite(router, peak_tracker)
flips_t_vs_base = _compute_flips(tb10["records"], track_a["step3d_tbench10"]["records"])
flips_t_vs_v2 = _compute_flips(tb10["records"], track_b["arm2_tbench10"]["records"])
out["tbench10"] = tb10
out["flips_tbench10_vs_base"] = flips_t_vs_base
out["flips_tbench10_vs_v2"] = flips_t_vs_v2
print(
f" => tbench10 LITE: {tb10['pass']}/10 ({tb10['pct']}%) | vs Base={flips_t_vs_base['net']:+d} "
f"| zcmd={tb10['zero_cmd_tasks']} avg_cmds={tb10['avg_cmds']}",
flush=True,
)
# Parse true GPU decode speed from log (strictly non-prompt eval time!)
cur_log_txt = (ROOT / f"val_{srv_tag}.log").read_text(encoding="utf-8", errors="replace")
cur_dec_tps = _parse_decode_tps(cur_log_txt)
if args.only_agent100:
out["agent100_server_log_decode_tps"] = _summarize_tps(cur_dec_tps)
prior_log = ROOT / "val_eval_lite.log"
combined_tps = list(cur_dec_tps)
if prior_log.exists():
prior_txt = prior_log.read_text(encoding="utf-8", errors="replace")
# Split on KV reset marker (prompt eval time for / 1 tokens or / 2 tokens with n_predict=1 eval time / 1 runs)
resets = [m.start() for m in re.finditer(r"prompt eval time\s*=\s*[\d.]+ ms /\s*[12] tokens", prior_txt)]
if len(resets) >= 2:
stem_tb_tps = _parse_decode_tps(prior_txt[resets[1]:])
out["stem45_tbench10_server_log_decode_tps"] = _summarize_tps(stem_tb_tps)
combined_tps.extend(stem_tb_tps)
out["server_log_decode_tps"] = _summarize_tps(combined_tps)
else:
out["server_log_decode_tps"] = _summarize_tps(cur_dec_tps)
out["peak_vram_mb"] = max(int(out.get("peak_vram_mb") or 0), peak_tracker[0])
out["vram_after_shutdown"] = vram_mb()
out["total_eval_s"] = round(time.time() - t_total0, 1)
OUT_PATH.write_text(json.dumps(out, indent=2), encoding="utf-8")
print(
f"\nSaved {OUT_PATH} in {out['total_eval_s']}s | server_log_decode_tps={out['server_log_decode_tps']} "
f"| post_vram={out['vram_after_shutdown']['used_mb']} MiB",
flush=True,
)
if __name__ == "__main__":
main()
|