"""Score raw/.jsonl with every parser and write results.json. python analyze.py [--raw raw] [--out results.json] """ import argparse import json from collections import Counter, defaultdict from pathlib import Path import numpy as np from parsers import PARSERS, looks_like_tool_call from scoring import FAILURES, score from tasks import CATEGORIES, TASKS from tools import ALL_BY_NAME HERE = Path(__file__).parent TASK = {t["id"]: t for t in TASKS} B = 10_000 QUESTION = ("On 96 self-written tool-calling tasks, how accurate are Qwen3.6-35B-A3B (thinking off and on) and " "Gemma 3 12B in MLX; what share of failures are malformed/unparseable output rather than wrong " "decisions; how much does accuracy drop with 32 tools instead of 8; and what does each setting cost " "in seconds per call?") def visible_answer(text, thinking): """Thinking runs: the answer is what follows ; none means the cap cut the reasoning.""" if "" in text: return text.split("", 1)[1] if thinking else text.split("")[-1] return "" if thinking else text def score_rows(raw_dir, meta): rows = [] for cond, cm in meta["conditions"].items(): path = raw_dir / f"{cond}.jsonl" if not path.exists(): continue for line in path.read_text().splitlines(): r = json.loads(line) task = TASK[r["task_id"]] tools = [ALL_BY_NAME[n] for n in r["menu"]] vis = visible_answer(r["text"], cm["thinking"]) row = {k: r[k] for k in ["condition", "task_id", "category", "seed", "latency_s", "ttft_s", "gen_tokens", "cap_hit", "prefix_cached", "prefix_prefill_s", "prompt_tokens"]} row["answer_text"] = vis for pname, parser in PARSERS[cm["family"]].items(): calls, malformed = parser(vis, tools) ok, fail = score(task, calls, malformed, vis, r["cap_hit"], ALL_BY_NAME) row[pname] = {"correct": ok, "failure": fail, "calls": calls} row["tool_call_markup_seen"] = looks_like_tool_call(vis) rows.append(row) return rows def pct(x): return round(100.0 * x, 2) def task_matrix(rows, parser): """task_id -> mean correctness over seeds.""" acc = defaultdict(list) for r in rows: acc[r["task_id"]].append(float(r[parser]["correct"])) return {t: float(np.mean(v)) for t, v in acc.items()} def boot(values, rng): v = np.asarray(values, dtype=float) if len(v) == 0: return [None, None] means = v[rng.integers(0, len(v), (B, len(v)))].mean(axis=1) return [pct(np.percentile(means, 2.5)), pct(np.percentile(means, 97.5))] def metric(value, unit, samples=None, note=""): return {"value": value, "unit": unit, "samples": samples if samples is not None else [], "note": note} def analyze(raw_dir, out_path): meta = json.loads((raw_dir / "meta.json").read_text()) rows = score_rows(raw_dir, meta) rng = np.random.default_rng(0) by_cond = defaultdict(list) for r in rows: by_cond[r["condition"]].append(r) M, tables, obs = {}, {"accuracy_by_category": {}, "failure_breakdown_pct_of_task_runs": {}, "strict_failure_to_lenient_outcome": {}, "per_task": {}}, [] for cond, rs in by_cond.items(): cm = meta["conditions"][cond] parsers = list(PARSERS[cm["family"]]) seeds = sorted({r["seed"] for r in rs}) n_tasks = len({r["task_id"] for r in rs}) M[f"{cond}.tasks_completed"] = metric(n_tasks, "tasks", note=f"of {cm['tasks_planned']} planned; " f"stopped early by time budget: {cm['stopped_early_by_time_budget']}") for p in parsers: tm = task_matrix(rs, p) per_seed = [pct(np.mean([r[p]["correct"] for r in rs if r["seed"] == s])) for s in seeds] label = {"strict": "strict parser", "lenient": "lenient parser", "mlx_lm": "mlx_lm's built-in qwen3_coder parser (as mlx_lm.server uses it)"}[p] M[f"{cond}.accuracy_{p}"] = metric( pct(np.mean([r[p]["correct"] for r in rs])), "%", per_seed, f"exact-match accuracy, {label}; samples = per-seed accuracy (seeds {seeds}); " f"95% bootstrap CI over tasks {boot(list(tm.values()), rng)}") M[f"{cond}.accuracy_{p}_ci95"] = metric(boot(list(tm.values()), rng), "%", note="bootstrap over tasks (10k resamples), task score = mean over seeds") if len(seeds) > 1: M[f"{cond}.seed_spread_{p}"] = metric(round(max(per_seed) - min(per_seed), 2), "percentage points", per_seed, "max - min of per-seed accuracy") fails = Counter(r[p]["failure"] for r in rs if not r[p]["correct"]) tables["failure_breakdown_pct_of_task_runs"][f"{cond}.{p}"] = { f: pct(fails.get(f, 0) / len(rs)) for f in FAILURES} for f in FAILURES: M[f"{cond}.failure_{p}.{f}"] = metric(pct(fails.get(f, 0) / len(rs)), "% of task runs", [fails.get(f, 0)], f"count in samples; n={len(rs)} task runs") tables["accuracy_by_category"][f"{cond}.{p}"] = {} for c in CATEGORIES: cr = [r[p]["correct"] for r in rs if r["category"] == c] if cr: tables["accuracy_by_category"][f"{cond}.{p}"][c] = pct(np.mean(cr)) M[f"{cond}.accuracy_{p}.{c}"] = metric(pct(np.mean(cr)), "%", [len(cr)], "samples = number of task runs in this category") strict_fail = [r for r in rs if not r["strict"]["correct"]] recovered = [r for r in strict_fail if r["lenient"]["correct"]] M[f"{cond}.parser_recoverable_share_of_failures"] = metric( pct(len(recovered) / len(strict_fail)) if strict_fail else None, "%", [len(recovered), len(strict_fail)], "task runs wrong under the strict parser but right under the lenient one, as a share of all strict " "failures; samples = [recovered, strict failures]") regress = [r for r in rs if r["strict"]["correct"] and not r["lenient"]["correct"]] M[f"{cond}.lenient_regressions"] = metric(len(regress), "task runs", [r["task_id"] for r in regress], "right under strict, wrong under lenient (lenient over-extraction)") trans = defaultdict(Counter) for r in strict_fail: trans[r["strict"]["failure"]]["correct" if r["lenient"]["correct"] else r["lenient"]["failure"]] += 1 tables["strict_failure_to_lenient_outcome"][cond] = {k: dict(v) for k, v in trans.items()} if "mlx_lm" in parsers: gap = [r for r in rs if r["mlx_lm"]["correct"] != r["strict"]["correct"]] M[f"{cond}.mlx_lm_vs_strict_disagreements"] = metric(len(gap), "task runs", [r["task_id"] for r in gap], "task runs where mlx_lm's parser and ours disagree") lat = [r["latency_s"] for r in rs] M[f"{cond}.latency_median_s"] = metric(round(float(np.median(lat)), 3), "s", None, "end-to-end per task run incl. suffix prefill, with the tool-definition " "prefix already cached") M[f"{cond}.latency_p90_s"] = metric(round(float(np.percentile(lat, 90)), 3), "s") M[f"{cond}.ttft_median_s"] = metric(round(float(np.median([r["ttft_s"] for r in rs])), 3), "s", note="time to first generated token") M[f"{cond}.generated_tokens_median"] = metric(float(np.median([r["gen_tokens"] for r in rs])), "tokens") M[f"{cond}.cap_hit_rate"] = metric(pct(np.mean([r["cap_hit"] for r in rs])), "%", [int(sum(r["cap_hit"] for r in rs))], f"share of runs that hit max_tokens={cm['max_tokens']}") M[f"{cond}.prefix_prefill_median_s"] = metric( round(float(np.median([r["prefix_prefill_s"] for r in rs])), 3), "s", None, "one-off cost of prefilling the shared tool-definition prefix (not included in latency)") M[f"{cond}.prompt_tokens_median"] = metric(float(np.median([r["prompt_tokens"] for r in rs])), "tokens") M[f"{cond}.prefix_cache_hit_rate"] = metric(pct(np.mean([r["prefix_cached"] for r in rs])), "%") M[f"{cond}.peak_memory_gb"] = metric(round(cm["peak_memory_gb"], 2), "GB", note="mx.get_peak_memory() during the condition, weights included") M[f"{cond}.model_load_s"] = metric(round(cm["model_load_s"], 1), "s") tables["per_task"][cond] = {t: round(v, 3) for t, v in task_matrix(rs, "strict").items()} def paired(a, b, p, name, note): if a not in by_cond or b not in by_cond: return ta, tb = task_matrix(by_cond[a], p), task_matrix(by_cond[b], p) common = sorted(set(ta) & set(tb)) if not common: return d = [ta[t] - tb[t] for t in common] M[name] = metric(pct(np.mean(d)), "percentage points", [len(common)], f"{note}; paired over {len(common)} common tasks; 95% bootstrap CI {boot(d, rng)}; " "samples = [common tasks]") for p in ["strict", "lenient"]: paired("qwen_nothink_8", "qwen_nothink_32", p, f"drop_8_to_32_tools_{p}", "Qwen thinking off: accuracy with 8 tools (mean of 3 seeds) minus with 32 tools (1 seed)") paired("qwen_think_8", "qwen_nothink_8", p, f"thinking_gain_{p}", "Qwen 8 tools: thinking on (1 seed) minus thinking off (mean of 3 seeds)") paired("gemma_8", "qwen_nothink_8", p, f"gemma_minus_qwen_nothink_{p}", "Gemma 3 12B (prompted format) minus Qwen thinking off, 8 tools, both mean of 3 seeds") if "qwen_think_8" in by_cond and "qwen_nothink_8" in by_cond: a = M["qwen_think_8.latency_median_s"]["value"] b = M["qwen_nothink_8.latency_median_s"]["value"] M["thinking_latency_ratio_median"] = metric(round(a / b, 2), "x", [a, b], "median latency thinking on / thinking off") # misses for hand review (wrong-arg category), plus optional published adjudications review = Path(out_path).parent / "review" review.mkdir(exist_ok=True) with open(review / "wrong_arg_misses.jsonl", "w") as f: for r in rows: for p in ["strict", "lenient"]: if r[p]["failure"] == "wrong_or_missing_arg": f.write(json.dumps({"key": f"{r['condition']}|{r['task_id']}|{r['seed']}", "parser": p, "expected": TASK[r["task_id"]]["expected"], "got": r[p]["calls"]}) + "\n") adj_path = HERE / "adjudications.json" adj = json.loads(adj_path.read_text()) if adj_path.exists() else {} M["adjudications_applied"] = metric(len(adj), "task runs", note="hand-review overrides of wrong-arg misses " "(adjudications.json); headline accuracies above are NOT adjusted") if adj: for cond, rs in by_cond.items(): fixed = [r["strict"]["correct"] or adj.get(f"{cond}|{r['task_id']}|{r['seed']}", {}).get("correct", False) for r in rs] M[f"{cond}.accuracy_strict_adjudicated"] = metric(pct(np.mean(fixed)), "%") (Path(out_path).parent / "scored_rows.jsonl").write_text("\n".join(json.dumps(r) for r in rows) + "\n") # factual observations, generated from the numbers above for cond in by_cond: s, l = M[f"{cond}.accuracy_strict"], M[f"{cond}.accuracy_lenient"] share = M[f"{cond}.parser_recoverable_share_of_failures"] obs.append(f"{cond}: strict accuracy {s['value']}% (95% CI {M[f'{cond}.accuracy_strict_ci95']['value']}), " f"lenient {l['value']}%; {share['samples'][0]} of {share['samples'][1]} strict failures were " f"recoverable by the lenient parser ({share['value']}%).") obs.append(f"{cond}: median {M[f'{cond}.latency_median_s']['value']} s per task " f"(p90 {M[f'{cond}.latency_p90_s']['value']} s), median " f"{M[f'{cond}.generated_tokens_median']['value']} generated tokens, " f"cap hit in {M[f'{cond}.cap_hit_rate']['value']}% of runs, " f"{M[f'{cond}.tasks_completed']['value']} tasks completed.") if f"{cond}.accuracy_mlx_lm" in M: obs.append(f"{cond}: mlx_lm's own qwen3_coder parser scored {M[f'{cond}.accuracy_mlx_lm']['value']}% " f"(disagrees with our strict parser on " f"{M[f'{cond}.mlx_lm_vs_strict_disagreements']['value']} task runs).") for k in ["drop_8_to_32_tools_strict", "thinking_gain_strict", "gemma_minus_qwen_nothink_strict"]: if k in M: obs.append(f"{k}: {M[k]['value']} pp ({M[k]['note']}).") caveats = [ "96 self-written synthetic tasks: differences under roughly 8 points may be noise; see bootstrap CIs.", "Qwen3.6's chat template defines an XML-style call format (), " "not JSON; the strict parser follows the template as shipped in the mlx-community snapshot.", "Gemma 3 has no native tool role: its numbers are for a prompted ```tool_call``` JSON format and are not " "like-for-like with Qwen's native template.", "Thinking-on and 32-tool conditions use 1 seed; thinking-off 8-tool and Gemma use 3 seeds.", "Latency is per task with the shared tool-definition prefix already in the prompt cache; the one-off " "prefix prefill is reported separately.", "Sampling follows the model cards (Qwen presence_penalty 1.5 applied to generated tokens only, as in " "vLLM/OpenAI semantics); results apply to these 4-bit MLX builds, these templates and mlx/mlx_lm versions.", "Wrong-arg misses are written to review/wrong_arg_misses.jsonl for hand review; headline numbers do not " "include any adjudication.", "The lenient parser only extracts calls and never edits values, but it can also over-extract (see " "lenient_regressions).", ] for cond, cm in meta["conditions"].items(): if cm["stopped_early_by_time_budget"]: caveats.append(f"{cond} stopped early at {cm['tasks_completed']}/{cm['tasks_planned']} tasks because of " "the run's time budget; tasks were interleaved by category, and comparisons are paired " "on common tasks.") env = meta["environment"] result = { "question": QUESTION, "environment": env, "runs": 3, "runs_note": "3 seeds for qwen_nothink_8 and gemma_8; 1 seed for qwen_nothink_32 and qwen_think_8", "conditions": meta["conditions"], "metrics": M, "tables": tables, "observations": obs, "caveats": caveats, } Path(out_path).write_text(json.dumps(result, indent=2)) print(f"wrote {out_path}: {len(M)} metrics, {len(rows)} scored task runs") if __name__ == "__main__": ap = argparse.ArgumentParser() ap.add_argument("--raw", default=str(HERE / "raw")) ap.add_argument("--out", default=str(HERE / "results.json")) a = ap.parse_args() analyze(Path(a.raw), a.out)