"""CPU-only checks: suite validity, parsers, scorer, and the analysis pipeline on a synthetic fixture.
HF_HUB_OFFLINE=1 python test_offline.py
The synthetic fixture lives in a temp dir and is deleted; it is never written to raw/ or results.json.
"""
import json
import shutil
import sys
import tempfile
from collections import Counter
from pathlib import Path
from parsers import gemma_strict, lenient, mlx_lm_qwen, qwen_strict
from prompts import interleaved, menu
from scoring import match_value, safe_eval, score
from tasks import CATEGORIES, TASKS, WARMUP
from tools import ALL_BY_NAME, REAL_BY_NAME
FAILED = []
def check(cond, msg):
if not cond:
FAILED.append(msg)
print("FAIL:", msg)
def concrete(v):
"""A gold value satisfying a matcher."""
if isinstance(v, dict) and len(v) == 1 and next(iter(v)).startswith("$"):
(op, a), = v.items()
return {"$any": lambda: concrete(a[0]), "$contains": lambda: " ".join(a), "$city": lambda: a.title(),
"$time": lambda: a, "$math": lambda: repr(a) if not float(a).is_integer() else str(int(a))}[op]()
if isinstance(v, dict):
return {k: concrete(x) for k, x in v.items()}
if isinstance(v, list):
return [concrete(x) for x in v][::-1] # reversed: arrays must match order-insensitively
return v
def gold_calls(task):
return [{"name": c["name"], "arguments": {k: concrete(v) for k, v in c["args"].items()}} for c in task["expected"]]
def test_suite():
check(len(TASKS) == 96, "96 tasks")
check(Counter(t["category"] for t in TASKS) == {c: 16 for c in CATEGORIES}, "16 per category")
check(len({t["id"] for t in TASKS + WARMUP}) == 99, "unique ids")
check(len({t["prompt"] for t in TASKS}) == 96, "unique prompts")
for t in TASKS:
for c in t["expected"]:
props = REAL_BY_NAME[c["name"]]["function"]["parameters"]
for r in props["required"]:
check(r in c["args"], f"{t['id']}: required arg {r} missing from ground truth")
for k, v in c["args"].items():
check(k in props["properties"], f"{t['id']}: {k} not in schema")
enum = props["properties"][k].get("enum")
if enum and isinstance(v, str):
check(v in enum, f"{t['id']}: {v} not in enum")
m8 = [x["function"]["name"] for x in menu(t, 8)]
check(len(m8) == 8 and len(set(m8)) == 8, f"{t['id']}: menu size")
for n in [c["name"] for c in t["expected"]] + t["distractors"]:
check(n in m8, f"{t['id']}: {n} missing from 8-tool menu")
check(len(menu(t, 32)) == 32, "32 menu")
check(sorted(t["id"] for t in interleaved()) == sorted(t["id"] for t in TASKS), "interleave keeps all")
check([t["category"] for t in interleaved()[:6]] == CATEGORIES, "interleave round-robin")
def qwen_template_render(tok, calls, content=""):
from tasks import SYSTEM_PROMPT
msgs = [{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": "x"},
{"role": "assistant", "content": content,
"tool_calls": [{"type": "function", "function": c} for c in calls]}]
s = tok.apply_chat_template(msgs, tools=list(REAL_BY_NAME.values()), tokenize=False)
s = s.rsplit("<|im_start|>assistant\n", 1)[1].split("<|im_end|>")[0]
return s.split("", 1)[1].lstrip("\n") if "" in s else s
def test_gold_roundtrip(qtok):
"""Gold answers rendered by Qwen's own chat template must parse and score as correct."""
for t in TASKS:
tools = menu(t, 8)
if t["expected"]:
q = qwen_template_render(qtok, gold_calls(t))
g = "\n".join("```tool_call\n" + json.dumps(c) + "\n```" for c in gold_calls(t))
cases = [("qwen_strict", qwen_strict, q), ("qwen_lenient", lenient, q), ("mlx_lm", mlx_lm_qwen, q),
("gemma_strict", gemma_strict, g), ("gemma_lenient", lenient, g)]
else:
ans = "Canberra is the capital."
cases = [(n, f, ans) for n, f in [("qwen_strict", qwen_strict), ("lenient", lenient),
("mlx_lm", mlx_lm_qwen), ("gemma_strict", gemma_strict)]]
for name, f, text in cases:
calls, bad = f(text, tools)
ok, fail = score(t, calls, bad, text, False, ALL_BY_NAME)
check(ok, f"gold {t['id']} via {name}: {fail} {calls} <- {text!r}")
def test_parsers_and_failures():
tools = menu(TASKS[0], 8)
t = TASKS[0] # get_weather(location=lisbon)
good = "\n\n\nLisbon\n\n\n"
def s(fn, text, task=t, truncated=False):
calls, bad = fn(text, tools)
return score(task, calls, bad, text, truncated, ALL_BY_NAME)
check(s(qwen_strict, good) == (True, None), "strict good")
check(s(qwen_strict, "Let me check.\n" + good) == (True, None), "strict allows prefix text")
broken = good.replace("", "")
check(s(qwen_strict, broken) == (False, "malformed_output"), "missing is malformed for strict")
check(s(lenient, broken) == (True, None), "lenient recovers missing ")
check(s(mlx_lm_qwen, broken) == (True, None), "mlx_lm server tolerates missing ")
no_param_close = good.replace("Lisbon\n", "Lisbon\n")
check(s(qwen_strict, no_param_close)[1] == "malformed_output", "missing strict")
check(s(lenient, no_param_close) == (True, None), "missing lenient")
jtc = '\n{"name": "get_weather", "arguments": {"location": "Lisbon"}}\n'
check(s(qwen_strict, jtc)[1] == "malformed_output", "JSON-in-tool_call is not the template format")
check(s(lenient, jtc) == (True, None), "lenient reads JSON in tool_call")
fence = "```json\n{'name': 'get_weather', 'arguments': {'location': 'Lisbon',}}\n```"
check(s(gemma_strict, fence)[1] in ("skipped_needed_call", "malformed_output"), "gemma strict rejects ```json")
check(s(lenient, fence) == (True, None), "lenient: other fence + single quotes + trailing comma")
gem_trail = '```tool_call\n{"name": "get_weather", "arguments": {"location": "Lisbon"}}\n```\nDone!'
check(s(gemma_strict, gem_trail) == (True, None), "gemma strict allows trailing text")
gem_badjson = "```tool_call\n{'name': 'get_weather', 'arguments': {'location': 'Lisbon'}}\n```"
check(s(gemma_strict, gem_badjson) == (False, "malformed_output"), "gemma strict single quotes malformed")
check(s(lenient, gem_badjson) == (True, None), "lenient single quotes")
check(s(qwen_strict, "It is sunny in Lisbon.")[1] == "skipped_needed_call", "skipped")
check(s(qwen_strict, good.replace("get_weather", "get_forecast"))[1] == "wrong_tool", "wrong tool")
check(s(qwen_strict, good.replace("Lisbon", "Porto"))[1] == "wrong_or_missing_arg", "wrong arg")
check(s(qwen_strict, good.replace("Lisbon", "Lisbon, Portugal")) == (True, None), "city alias")
halluc = good.replace("", "\nPT\n\n")
check(s(qwen_strict, halluc)[1] == "hallucinated_arg", "arg not in schema")
units_default = good.replace("", "\nmetric\n\n")
check(s(qwen_strict, units_default) == (True, None), "optional arg at its default is fine")
units_other = good.replace("", "\nimperial\n\n")
check(s(qwen_strict, units_other)[1] == "hallucinated_arg", "unrequested non-default optional arg")
notool = next(x for x in TASKS if x["category"] == "no_tool")
check(s(qwen_strict, good, notool)[1] == "called_when_not_needed", "called when not needed")
check(s(qwen_strict, "", t, truncated=True)[1] == "truncated_by_cap", "truncated")
par = next(x for x in TASKS if x["id"] == "parallel-01")
one = good.replace("Lisbon", "Paris")
check(s(qwen_strict, one, par)[1] == "skipped_needed_call", "parallel: one of two calls")
two = one + "\n" + good.replace("Lisbon", "Rome")
check(s(qwen_strict, two, par) == (True, None), "parallel both")
check(s(qwen_strict, two + "\n" + one, par)[1] == "wrong_tool", "parallel: extra duplicate call")
# typed values: the template writes non-strings as JSON
timer = next(x for x in TASKS if x["id"] == "single-02")
tt = menu(timer, 8)
for raw, want in [("600", True), ("600.0", True), ("ten minutes", False)]:
txt = f"\n\n\n{raw}\n\n\n"
calls, bad = qwen_strict(txt, tt)
check(score(timer, calls, bad, txt, False, ALL_BY_NAME)[0] == want, f"typed int {raw}")
gem_str_int = '```tool_call\n{"name": "set_timer", "arguments": {"duration_seconds": "600"}}\n```'
calls, bad = gemma_strict(gem_str_int, tt)
check(score(timer, calls, bad, gem_str_int, False, ALL_BY_NAME)[1] == "wrong_or_missing_arg",
"string '600' for an integer is a type error in JSON")
def test_matchers():
check(safe_eval("0.18*2450") == 441 and safe_eval("18% of 2450") is None and safe_eval("2^10") == 1024,
"safe_eval")
check(safe_eval("18% * 2450") == 441, "percent")
check(match_value({"$math": 1 / 3}, "1/3") and match_value({"$math": 1 / 3}, 0.3333), "math tolerance")
check(match_value({"$time": "09:15"}, "9:15") and not match_value({"$time": "09:15"}, "21:15"), "time")
check(match_value(["a@x.com", "b@x.com"], ["B@x.com ", "a@x.com"]), "arrays order/case-insensitive")
check(not match_value(5, "5") and not match_value(True, 1), "type strictness")
def test_analysis_pipeline():
"""Run analyze.py end to end on a SYNTHETIC fixture (gold + perturbed answers), in a temp dir."""
import analyze
from transformers import AutoTokenizer # noqa: F401 (already imported via test_gold_roundtrip)
tmp = Path(tempfile.mkdtemp())
try:
raw = tmp / "raw"
raw.mkdir()
conds = {"qwen_nothink_8": ("qwen", 8, False, [0, 1, 2]), "qwen_nothink_32": ("qwen", 32, False, [0]),
"qwen_think_8": ("qwen", 8, True, [0]), "gemma_8": ("gemma", 8, False, [0, 1, 2])}
meta = {"environment": {"note": "synthetic fixture"}, "conditions": {}}
for name, (fam, size, think, seeds) in conds.items():
with open(raw / f"{name}.jsonl", "w") as f:
for i, t in enumerate(interleaved()[:60]):
for sd in seeds:
calls = gold_calls(t)
if fam == "qwen":
body = "\n".join(f"\n\n" + "".join(
f"\n{v if isinstance(v, str) else json.dumps(v)}\n\n"
for k, v in c["arguments"].items()) + "\n" for c in calls)
if (i + sd) % 7 == 0:
body = body.replace("", "")
else:
body = "\n".join("```tool_call\n" + json.dumps(c) + "\n```" for c in calls)
if (i + sd) % 5 == 0:
body = body.replace("```tool_call", "```json")
body = body or "A direct answer."
text = ("reasoning...\n\n" + body) if think else body
cap = think and i % 9 == 0
if cap:
text = "long reasoning that never ends"
f.write(json.dumps({"condition": name, "task_id": t["id"], "category": t["category"],
"seed": sd, "menu": [x["function"]["name"] for x in menu(t, size)],
"text": text, "gen_tokens": 40, "finish": "length" if cap else "stop",
"cap_hit": cap, "latency_s": 1.0 + i / 100, "ttft_s": 0.1,
"prompt_tokens": 1200, "prefix_tokens": 1100, "prefix_cached": True,
"prefix_prefill_s": 0.8}) + "\n")
meta["conditions"][name] = {"family": fam, "menu": size, "thinking": think, "seeds": seeds,
"max_tokens": 1536 if think else 512, "sampling": {}, "model": fam,
"model_load_s": 1.0, "tasks_completed": 60, "tasks_planned": 96,
"stopped_early_by_time_budget": True, "wall_s": 1.0, "peak_memory_gb": 1.0}
(raw / "meta.json").write_text(json.dumps(meta))
out = tmp / "results.json"
analyze.analyze(raw, out)
res = json.loads(out.read_text())
for k in ["question", "environment", "runs", "metrics", "observations", "caveats"]:
check(k in res, f"results.json has {k}")
M = res["metrics"]
check(M["qwen_nothink_8.accuracy_lenient"]["value"] == 100.0, "fixture: lenient recovers all")
check(M["qwen_nothink_8.accuracy_strict"]["value"] < 100.0, "fixture: strict misses broken tags")
check(M["qwen_nothink_8.parser_recoverable_share_of_failures"]["value"] == 100.0, "fixture share")
check(M["qwen_think_8.failure_strict.truncated_by_cap"]["value"] > 0, "fixture truncation counted")
check("drop_8_to_32_tools_strict" in M and "thinking_gain_strict" in M, "paired comparisons")
for k, v in M.items():
check(set(v) == {"value", "unit", "samples", "note"}, f"metric shape {k}")
print(f"fixture analysis OK: {len(M)} metrics")
finally:
shutil.rmtree(tmp)
if __name__ == "__main__":
from transformers import AutoTokenizer
from run_bench import MODELS, model_path
test_suite()
test_matchers()
test_parsers_and_failures()
test_gold_roundtrip(AutoTokenizer.from_pretrained(model_path(MODELS["qwen"])))
test_analysis_pipeline()
print("ALL OK" if not FAILED else f"{len(FAILED)} FAILURES")
sys.exit(1 if FAILED else 0)