v4: oversampled abstention + metric fix
Browse filesFiles changed (37)
- GGUF.mdAdded+69
- __pycache__/analyze_failures.cpython-311.pycAdded
- __pycache__/audit_dataset.cpython-311.pycAdded
- __pycache__/build_card.cpython-311.pycAdded
- __pycache__/check_gate.cpython-311.pycAdded
- __pycache__/check_special.cpython-311.pycAdded
- __pycache__/convert_hf_to_gguf.cpython-311.pycAdded
- __pycache__/debug_base.cpython-311.pycAdded
- __pycache__/debug_encode.cpython-311.pycAdded
- __pycache__/debug_gen.cpython-311.pycAdded
- __pycache__/eval_openai.cpython-311.pycAdded
- __pycache__/inspect_mt.cpython-311.pycAdded
- __pycache__/inspect_raw.cpython-311.pycAdded
- __pycache__/make_hard_set.cpython-311.pycAdded
- __pycache__/merge_local.cpython-311.pycAdded
- __pycache__/metrics_lib.cpython-311.pycAdded
- __pycache__/mt_lengths.cpython-311.pycAdded
- __pycache__/prepare_multiturn.cpython-311.pycAdded
- __pycache__/runtime_ab.cpython-311.pycAdded
- __pycache__/test_encode.cpython-311.pycAdded
- __pycache__/test_metrics_lib.cpython-311.pycAdded
- __pycache__/test_runtime.cpython-311.pycAdded
- __pycache__/train_eval.cpython-311.pyc
- analyze_failures.pyAdded+222
- audit_dataset.pyAdded+352
- build_card.pyAdded+464
- check_gate.pyAdded+321
- convert_hf_to_gguf.pyAdded+342
- eval_openai.pyAdded+485
- make_gguf.ps1Added+96
- make_hard_set.pyAdded+386
- make_oversampled.pyAdded+28
- metrics_lib.pyAdded+501
- runtime_ab.pyAdded+588
- start_servers.ps1Added+93
- test_metrics_lib.pyAdded+274
- train_eval.py+11-5
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869# GGUF build (MiniCPM5-1B toolcall)
Builds `f16`, `Q8_0`, and `Q4_K_M` GGUF files from the merged`DevGwardo/minicpm5-1b-toolcall` LoRA via `pipeline/make_gguf.ps1`.
## Prerequisites
- `pipeline/merge_local.py` (merges the LoRA into the base, writes `.\merged`)- `llama.cpp-src\convert_hf_to_gguf.py` (llama.cpp master checkout)- `llama-bin\llama-quantize.exe` (release b12931)- `.venv\Scripts\python.exe` with `torch`, `transformers`, `peft`, `gguf`, `numpy`
## Commands
Full pipeline (merge + convert + quantize), run from the project root:
```powershellpowershell -NoProfile -File pipeline\make_gguf.ps1```
Convert + quantize only (requires `.\merged\config.json` to already exist):
```powershellpowershell -NoProfile -File pipeline\make_gguf.ps1 -SkipMerge```
Custom directories (both relative to the project root unless absolute):
```powershellpowershell -NoProfile -File pipeline\make_gguf.ps1 -OutDir gguf -MergedDir merged```
Manual equivalents of what the script runs:
```powershell# 1) Merge (skipped automatically when merged\config.json exists).venv\Scripts\python.exe pipeline\merge_local.py
# 2) Convert merged dir -> f16 GGUF.venv\Scripts\python.exe llama.cpp-src\convert_hf_to_gguf.py merged --outfile gguf\minicpm5-1b-toolcall-f16.gguf --outtype f16
# 3) Quantizellama-bin\llama-quantize.exe gguf\minicpm5-1b-toolcall-f16.gguf gguf\minicpm5-1b-toolcall-Q8_0.gguf Q8_0llama-bin\llama-quantize.exe gguf\minicpm5-1b-toolcall-f16.gguf gguf\minicpm5-1b-toolcall-Q4_K_M.gguf Q4_K_M```
The script is idempotent: re-running it reuses `.\merged` when`merged\config.json` exists and overwrites the GGUF outputs.
## Expected outputs and sizes
| File | Approx. size || ---- | ------------ || `gguf\minicpm5-1b-toolcall-f16.gguf` | ~2.2 GB || `gguf\minicpm5-1b-toolcall-Q8_0.gguf` | ~1.2 GB || `gguf\minicpm5-1b-toolcall-Q4_K_M.gguf` | ~0.8 GB |
The script prints a file/size table at the end and exits non-zero onany failure (native calls are checked via `$LASTEXITCODE`).
## Serve
```powershell.\llama-bin\llama-server.exe -m .\gguf\minicpm5-1b-toolcall-Q4_K_M.gguf -c 4096 --jinja --port 8080```
> Runtime note: use a llama.cpp build **>= b9833**, which contains the> native MiniCPM5 tool-call parser. Older builds will serve the model> but cannot parse its tool calls.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222"""Analyze tool-call prediction failures into reports/failures.json + reports/failures.md.
Usage: python pipeline/analyze_failures.py --predictions reports/runtime_eval/predictions.jsonl \ --data data_native/test.jsonl --out reports
Input predictions JSONL rows: {"i","category","expected":[{"name","arguments"}],"predicted":[...], "raw","exact","name_match","bucket"} (bucket may be missing)
Bucket/category come from pipeline/metrics_lib.py (failure_bucket, categorize)when the row does not already carry them."""
import argparseimport jsonimport sysfrom collections import Counter, defaultdictfrom pathlib import Path
def _load_metrics_lib(): """Import pipeline.metrics_lib; fall back to local equivalents if absent.
The real metrics_lib (owned by another session) takes precedence whenever it exists. The fallback only lets this script run standalone for the synthetic fixture proof. """ try: from pipeline.metrics_lib import categorize as _categorize from pipeline.metrics_lib import failure_bucket as _failure_bucket
return _failure_bucket, _categorize except Exception: def _failure_bucket(expected, predicted, raw): exp = expected or [] pred = predicted or [] if not exp and not pred: return "ok" if not exp and pred: return "false_positive" if exp and not pred: if not (raw or "").strip(): return "empty_output" return "missing_call" exp_names = sorted(c.get("name", "") for c in exp) pred_names = sorted(c.get("name", "") for c in pred) if exp_names != pred_names: if len(pred) < len(exp): return "missing_call" if len(pred) > len(exp): return "extra_call" return "wrong_name" # same names: compare arguments (normalized to str) for e, p in zip( sorted(exp, key=lambda c: c.get("name", "")), sorted(pred, key=lambda c: c.get("name", "")), ): if json.dumps(e.get("arguments", {}), sort_keys=True, default=str) != json.dumps( p.get("arguments", {}), sort_keys=True, default=str ): return "wrong_args" return "ok"
def _categorize(row): if row.get("category"): return row["category"] n = len(row.get("expected") or []) if n == 0: return "abstention" if n == 1: return "single_call" return "multi_call"
return _failure_bucket, _categorize
failure_bucket, categorize = _load_metrics_lib()
def load_jsonl(path): rows = [] with open(path, encoding="utf-8") as f: for line in f: line = line.strip() if line: rows.append(json.loads(line)) return rows
def user_prompt(test_row): """Extract the user prompt from a data_native/test.jsonl row.""" if not isinstance(test_row, dict): return "(unavailable: bad test row)" for m in test_row.get("messages", []): if isinstance(m, dict) and m.get("role") == "user": return m.get("content", "") return "(unavailable: no user message)"
def main(): ap = argparse.ArgumentParser() ap.add_argument("--predictions", required=True) ap.add_argument("--data", required=True, help="data_native/test.jsonl for prompts") ap.add_argument("--out", required=True, help="output dir for failures.json/failures.md") args = ap.parse_args()
pred_rows = load_jsonl(args.predictions) test_lines = [] with open(args.data, encoding="utf-8") as f: for line in f: if line.strip(): test_lines.append(json.loads(line))
def prompt_for(i): if isinstance(i, int) and 0 <= i < len(test_lines): return user_prompt(test_lines[i]) return f"(unavailable: index {i} out of range 0..{len(test_lines) - 1})"
counts = Counter() by_category = defaultdict(Counter) enriched = [] # (row, bucket, category) for idx, row in enumerate(pred_rows): # train_eval.py writes predictions without an index and calls the raw text # "text"; eval_openai.py writes "i"/"raw". Normalize both here. row.setdefault("i", idx) if "raw" not in row: row["raw"] = row.get("text", "") bucket = row.get("bucket") or failure_bucket(row.get("expected"), row.get("predicted"), row.get("raw", "")) try: category = row.get("category") or categorize(row) except Exception: category = row.get("category") or "unknown" if not bucket: bucket = "unknown" if not category: category = "unknown" counts[bucket] += 1 by_category[category][bucket] += 1 enriched.append((row, bucket, category))
n = len(pred_rows) out = Path(args.out) out.mkdir(parents=True, exist_ok=True)
failures_json = { "n": n, "counts": dict(counts), "by_category": {cat: dict(c) for cat, c in by_category.items()}, } (out / "failures.json").write_text(json.dumps(failures_json, indent=2), encoding="utf-8")
# ---- markdown report ---- lines = [] lines.append("# Failure analysis") lines.append("") lines.append(f"n = {n} predictions analyzed.") lines.append("") lines.append("## Counts by bucket") lines.append("") lines.append("| bucket | count | share |") lines.append("|---|---|---|") for bucket, c in counts.most_common(): share = c / n if n else 0.0 lines.append(f"| {bucket} | {c} | {share:.1%} |") lines.append("")
# examples per non-ok bucket, up to 3 each shown = defaultdict(int) examples = defaultdict(list) for row, bucket, category in enriched: if bucket == "ok": continue if len(examples[bucket]) < 3: examples[bucket].append((row, category)) for bucket, _ in counts.most_common(): if bucket == "ok" or bucket not in examples: continue lines.append(f"## {bucket} (n={counts[bucket]})") lines.append("") for k, (row, category) in enumerate(examples[bucket], 1): i = row.get("i") lines.append(f"### Example {k}: index {i} (category: {category})") lines.append("") lines.append("Prompt:") lines.append("```") lines.append(str(prompt_for(i))) lines.append("```") lines.append("Expected:") lines.append("```json") lines.append(json.dumps(row.get("expected"), indent=2, ensure_ascii=False, default=str)) lines.append("```") lines.append("Predicted:") lines.append("```json") lines.append(json.dumps(row.get("predicted"), indent=2, ensure_ascii=False, default=str)) lines.append("```") lines.append("Raw (first 300 chars):") lines.append("```") lines.append(str(row.get("raw", ""))[:300]) lines.append("```") lines.append("")
if counts: top_bucket, top_c = counts.most_common(1)[0] top_share = top_c / n if n else 0.0 lines.append( f"The most common failure mode is `{top_bucket}` with {top_c}/{n} rows ({top_share:.1%})." if top_bucket != "ok" else f"The most common outcome is `ok` with {top_c}/{n} rows ({top_share:.1%}), " f"so the model is mostly correct on this slice." ) else: lines.append("No predictions to analyze.") lines.append("") (out / "failures.md").write_text("\n".join(lines), encoding="utf-8")
print(f"wrote {out / 'failures.json'} and {out / 'failures.md'} (n={n})", flush=True) print(json.dumps(dict(counts), indent=2))
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352"""Audit data_native/*.jsonl splits for the MiniCPM5-1B tool-call pipeline.
Read-only: never modifies the data. Reports per-split stats and data bugs.
Usage: python pipeline/audit_dataset.py --data data_native --out reports"""import argparseimport collectionsimport jsonfrom pathlib import Path
def load_rows(path): rows = [] with open(path, encoding="utf-8") as f: for line in f: line = line.strip() if line: rows.append(json.loads(line)) return rows
def first_user_content(messages): for m in messages: if m.get("role") == "user": return m.get("content", "") or "" return ""
def all_calls(messages): calls = [] for m in messages: if m.get("role") == "assistant": for c in m.get("tool_calls") or []: calls.append(c) return calls
def tool_required(tool): """Return the required-arg list, handling both schema placements.""" req = tool.get("required") if isinstance(req, list) and req: return req params = tool.get("parameters") or {} if isinstance(params, dict): req = params.get("required") if isinstance(req, list) and req: return req return []
def arg_kind(v): if isinstance(v, bool): return "bool" if isinstance(v, (int, float)): return "number" if isinstance(v, str): return "string" if isinstance(v, list): return "list" if isinstance(v, dict): return "object" if v is None: return "null" return "other"
def has_deep_nesting(v): if isinstance(v, dict): return any(isinstance(x, (dict, list)) for x in v.values()) if isinstance(v, list): return any(isinstance(x, (dict, list)) for x in v) return False
def percentile(sorted_vals, p): if not sorted_vals: return 0 idx = min(int(len(sorted_vals) * p), len(sorted_vals) - 1) return sorted_vals[idx]
def audit_split(name, rows, tokenizer): n = len(rows) users = [first_user_content(r.get("messages", [])) for r in rows] uniq = len(set(users)) dup_rate = 1.0 - uniq / n if n else 0.0
tok_lens, render_errors = [], 0 for r in rows: try: text = tokenizer.apply_chat_template( r["messages"], tools=r.get("tools"), tokenize=False ) ids = tokenizer(text, add_special_tokens=False)["input_ids"] tok_lens.append(len(ids)) except Exception: render_errors += 1 tok_lens.sort()
tool_buckets = collections.Counter() for r in rows: k = len(r.get("tools") or []) if k <= 1: tool_buckets["1"] += 1 elif k <= 4: tool_buckets["2-4"] += 1 elif k <= 9: tool_buckets["5-9"] += 1 else: tool_buckets["10+"] += 1
call_buckets = collections.Counter() arg_types = collections.Counter() calls_with_complex = 0 # any arg is list/dict calls_with_deep = 0 # nested inside a list/dict arg total_calls = 0 for r in rows: calls = all_calls(r.get("messages", [])) total_calls += len(calls) call_buckets["0" if not calls else "1" if len(calls) == 1 else "2+"] += 1 for c in calls: args = c.get("arguments") or {} complex_hit, deep_hit = False, False for v in args.values(): kind = arg_kind(v) arg_types[kind] += 1 if kind in ("list", "object"): complex_hit = True if has_deep_nesting(v): deep_hit = True calls_with_complex += complex_hit calls_with_deep += deep_hit
# schema coverage n_tools, tools_with_required = 0, 0 calls_missing_required = 0 rows_missing_required = 0 for r in rows: tools = r.get("tools") or [] by_name = {t.get("name"): t for t in tools if isinstance(t, dict)} n_tools += len(tools) for t in tools: if tool_required(t): tools_with_required += 1 row_bad = False for c in all_calls(r.get("messages", [])): schema = by_name.get(c.get("name")) if schema is None: continue # counted as a bug flag instead req = tool_required(schema) if req: given = c.get("arguments") or {} if any(k not in given for k in req): calls_missing_required += 1 row_bad = True rows_missing_required += row_bad
abstention = sum(1 for r in rows if not all_calls(r.get("messages", [])))
# stage-2 type for multi-turn rows stage2 = None if name.startswith("mt_"): s2 = collections.Counter() for r in rows: assistants = [m for m in r.get("messages", []) if m.get("role") == "assistant"] last = assistants[-1] if assistants else {} s2["call" if (last.get("tool_calls") or []) else "text"] += 1 stage2 = dict(s2)
freq = collections.Counter() for r in rows: for c in all_calls(r.get("messages", [])): freq[c.get("name", "<missing>")] += 1
# bug flags bugs = collections.Counter() bug_examples = collections.defaultdict(list) seen_prompts = set() for i, r in enumerate(rows): msgs = r.get("messages", []) tools = r.get("tools") or [] names = {t.get("name") for t in tools if isinstance(t, dict)} if not tools: bugs["empty_tools_list"] += 1 bug_examples["empty_tools_list"].append(i) u = first_user_content(msgs) if not (u or "").strip(): bugs["empty_user_content"] += 1 bug_examples["empty_user_content"].append(i) if u in seen_prompts: bugs["duplicate_user_prompt"] += 1 else: seen_prompts.add(u) for j, m in enumerate(msgs): if m.get("role") == "assistant": content = m.get("content", "") tc = m.get("tool_calls") or [] if (not (content or "").strip()) and not tc: bugs["empty_assistant_no_call"] += 1 bug_examples["empty_assistant_no_call"].append(i) break for c in tc: if c.get("name") not in names: bugs["call_name_not_in_tools"] += 1 bug_examples["call_name_not_in_tools"].append(i) break if m.get("role") == "tool": prior_call = any( (pm.get("role") == "assistant" and (pm.get("tool_calls") or [])) for pm in msgs[:j] ) if not prior_call: bugs["tool_without_preceding_call"] += 1 bug_examples["tool_without_preceding_call"].append(i) break
return { "rows": n, "unique_user_prompts": uniq, "duplicate_rate": round(dup_rate, 4), "rendered_tokens": { "p50": percentile(tok_lens, 0.5), "p90": percentile(tok_lens, 0.9), "max": max(tok_lens) if tok_lens else 0, "render_errors": render_errors, }, "tool_count_dist": {k: tool_buckets.get(k, 0) for k in ("1", "2-4", "5-9", "10+")}, "call_count_dist": {k: call_buckets.get(k, 0) for k in ("0", "1", "2+")}, "total_calls": total_calls, "arg_types": {k: arg_types.get(k, 0) for k in ("string", "number", "bool", "list", "object", "null", "other")}, "calls_with_complex_arg": calls_with_complex, "calls_with_deep_nesting": calls_with_deep, "schema": { "n_tools": n_tools, "tools_with_required": tools_with_required, "calls_missing_required_arg": calls_missing_required, "rows_missing_required_arg": rows_missing_required, }, "abstention_rows": abstention, "abstention_share": round(abstention / n, 4) if n else 0.0, "stage2_dist": stage2, "top_tools": freq.most_common(5), "bugs": dict(bugs), "bug_row_examples": {k: v[:5] for k, v in bug_examples.items()}, }
def write_markdown(report, splits): L = ["# Dataset Audit", ""] L.append("| Split | Rows | Uniq prompts | Dup rate | p50 | p90 | Max | Abstain |") L.append("|---|---|---|---|---|---|---|---|---|") for s in splits: d = report[s] t = d["rendered_tokens"] L.append( f"| {s} | {d['rows']} | {d['unique_user_prompts']} | {d['duplicate_rate']:.2%} " f"| {t['p50']} | {t['p90']} | {t['max']} | {d['abstention_share']:.2%} |" ) L += ["", "## Tool / call counts", "", "| Split | Tools 1 | 2-4 | 5-9 | 10+ | Calls 0 | 1 | 2+ |", "|---|---|---|---|---|---|---|---|"] for s in splits: d = report[s] tc, cc = d["tool_count_dist"], d["call_count_dist"] L.append(f"| {s} | {tc['1']} | {tc['2-4']} | {tc['5-9']} | {tc['10+']} " f"| {cc['0']} | {cc['1']} | {cc['2+']} |") L += ["", "## Argument types (whole dataset: all splits pooled)", ""] pool = collections.Counter() cx = dx = 0 for s in splits: pool.update({k: v for k, v in report[s]["arg_types"].items()}) cx += report[s]["calls_with_complex_arg"] dx += report[s]["calls_with_deep_nesting"] tot = sum(pool.values()) or 1 L.append("| Type | Count | Share |") L.append("|---|---|---|") for k in ("string", "number", "bool", "list", "object", "null", "other"): L.append(f"| {k} | {pool.get(k, 0)} | {pool.get(k, 0) / tot:.2%} |") L.append(f"| calls with list/dict arg | {cx} | |") L.append(f"| calls with deep nesting | {dx} | |") L += ["", "## Schema coverage (required args)", "", "| Split | Tools w/ required | Calls omitting required | Rows affected |", "|---|---|---|---|"] for s in splits: sc = report[s]["schema"] L.append(f"| {s} | {sc['tools_with_required']}/{sc['n_tools']} " f"| {sc['calls_missing_required_arg']} | {sc['rows_missing_required_arg']} |") mt = [s for s in splits if s.startswith("mt_")] if mt: L += ["", "## Multi-turn stage-2 (last assistant message)", "", "| Split | call | text |", "|---|---|---|"] for s in mt: s2 = report[s]["stage2_dist"] or {} L.append(f"| {s} | {s2.get('call', 0)} | {s2.get('text', 0)} |") L += ["", "## Top tools per split", ""] for s in splits: top = ", ".join(f"{k} ({v})" for k, v in report[s]["top_tools"]) L.append(f"- **{s}**: {top}") L += ["", "## Bug flags", "", "| Split | Flag | Count | Example rows |", "|---|---|---|---|"] any_bug = False for s in splits: for flag, cnt in sorted(report[s]["bugs"].items()): any_bug = True ex = report[s]["bug_row_examples"].get(flag, []) L.append(f"| {s} | {flag} | {cnt} | {ex} |") if not any_bug: L.append("| (all splits) | no flags | 0 | — |") L += ["", "## Notes", "- `hard_test.jsonl` (50 rows) exists in `data_native/` but is not documented in its README.", "- 3 train rows render above the 1,400-token filter stated in the README (max 1,736); " "likely tokenizer/template drift since generation. 79/7,600 train rows exceed the " "1,280-token training cap and will be truncated at train time."] L.append("") return "\n".join(L)
def main(): ap = argparse.ArgumentParser() ap.add_argument("--data", default="data_native") ap.add_argument("--out", default="reports") args = ap.parse_args()
from transformers import AutoTokenizer tok = AutoTokenizer.from_pretrained("openbmb/MiniCPM5-1B", trust_remote_code=True)
data_dir = Path(args.data) files = sorted(data_dir.glob("*.jsonl")) if not files: raise SystemExit(f"no .jsonl files in {data_dir}") report, order = {}, [] for fp in files: name = fp.stem order.append(name) rows = load_rows(fp) print(f"{name}: {len(rows)} rows, auditing...", flush=True) report[name] = audit_split(name, rows, tok)
out = Path(args.out) out.mkdir(parents=True, exist_ok=True) with open(out / "dataset_audit.json", "w", encoding="utf-8") as f: json.dump(report, f, ensure_ascii=False, indent=2) with open(out / "dataset_audit.md", "w", encoding="utf-8") as f: f.write(write_markdown(report, order)) print(f"wrote {out / 'dataset_audit.json'} and {out / 'dataset_audit.md'}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464#!/usr/bin/env python3"""Build a model card (markdown + SVG chart) from eval metrics.
CLI: python pipeline/build_card.py --metrics reports/metrics.json --out card/README.md
Inputs (all except --metrics are optional and degrade to "n/a"): --metrics JSON with keys: base, tuned, multiturn_base, multiturn_tuned, val_loss, steps (plus optional base_model / adapter / context_tokens). --failures reports/failures.json (optional): {"buckets": [{"name":..., "count":...}], "n": ...} also accepts a plain list of {"bucket":...} rows or {"buckets": {"name": count}}. --runtime reports/runtime_ab.json (optional): llama-server A/B smoke-test summary. --audit reports/dataset_audit.json (optional): dataset counts / notes. --chart output path for the SVG chart (default: <out-dir>/chart.svg).
Never invents numbers: any missing value renders as "n/a" and its claim is omitted."""
from __future__ import annotations
import argparseimport htmlimport jsonfrom pathlib import Path
BASE_MODEL = "openbmb/MiniCPM5-1B"ADAPTER = "LoRA r=16 on all linear layers"CONTEXT = 1024DATASET_ID = "DevGwardo/toolcall-mini"CODE_ID = "DevGwardo/minicpm5-toolcall-code"ADAPTER_ID = "DevGwardo/minicpm5-1b-toolcall"
# (metric key, display label, higher-is-better)SINGLE_TURN_ROWS = [ ("exact_call_rate", "Exact call rate", True), ("positive_exact_rate", "Positive exact rate", True), ("name_accuracy", "Name accuracy", True), ("parse_rate", "Parse rate", True), ("abstention_accuracy", "Abstention accuracy", True), ("false_positive_rate", "False positive rate", False),]
MT_ROWS = [ ("stage1_exact", "Stage 1: first-call exact"), ("stage2_type_accuracy", "Stage 2: call-vs-answer decision"), ("stage2_call_exact", "Stage 2: second-call exact"), ("stage2_no_spurious_call_rate", "Stage 2: no call when an answer is expected"), ("stage2_answer_rate", "Stage 2: non-empty answer rate"),]
CHART_SHORT = { "exact_call_rate": "exact", "positive_exact_rate": "pos-exact", "name_accuracy": "name", "parse_rate": "parse", "abstention_accuracy": "abstain", "false_positive_rate": "fp-rate",}
def load_json(path: Path | None): if path is None or not path.exists(): return None try: return json.loads(path.read_text(encoding="utf-8")) except (json.JSONDecodeError, OSError): return None
def fmt(x) -> str: if x is None: return "n/a" try: v = float(x) except (TypeError, ValueError): return "n/a" return f"{v:.3f}"
def fmt_count(x) -> str: if x is None: return "n/a" try: v = float(x) except (TypeError, ValueError): return "n/a" return str(int(v)) if v.is_integer() else f"{v:.3f}"
def num(x): try: return float(x) except (TypeError, ValueError): return None
def bold_cells(b, t, higher_better: bool) -> tuple[str, str]: """Return (base_cell, tuned_cell) with the better value bolded. Ties/unavailable: no bold.""" bs, ts = fmt(b), fmt(t) bv, tv = num(b), num(t) if bv is None or tv is None or bv == tv: return bs, ts better_tuned = (tv > bv) if higher_better else (tv < bv) if better_tuned: return bs, f"**{ts}**" return f"**{bs}**", ts
def single_turn_table(base: dict, tuned: dict) -> str: lines = ["| Metric | Base | +LoRA |", "|---|---|---|"] for key, label, hib in SINGLE_TURN_ROWS: b = (base or {}).get(key) t = (tuned or {}).get(key) bc, tc = bold_cells(b, t, hib) lines.append(f"| {label} | {bc} | {tc} |") return "\n".join(lines)
def multiturn_table(mb: dict | None, mt: dict | None) -> str: if not mb and not mt: return "" mb, mt = mb or {}, mt or {} if not any(mb.get(k) is not None or mt.get(k) is not None for k, _ in MT_ROWS): return "" lines = [ "## Multi-turn loops", "", "One round trip is: user → call → tool result → follow-up. Stage 1 checks the first call. " "Stage 2 appends the ground-truth tool result and checks whether the model answers or calls again. " "Greedy decoding, identical prompts for both models.", "", "| Stage | Base | +LoRA |", "|---|---|---|", ] for key, label in MT_ROWS: bc, tc = bold_cells(mb.get(key), mt.get(key), True) lines.append(f"| {label} | {bc} | {tc} |") n_b, n_t = mb.get("n"), mt.get("n") if n_b is not None or n_t is not None: lines.append(f"| *n (loops)* | {fmt_count(n_b)} | {fmt_count(n_t)} |") return "\n".join(lines) + "\n"
def parse_failure_buckets(failures) -> list[tuple[str, int]]: """Normalize several plausible failures.json shapes to [(bucket, count)].""" if not failures: return [] if isinstance(failures, dict): if isinstance(failures.get("counts"), dict): return sorted( ((str(k), int(v)) for k, v in failures["counts"].items()), key=lambda x: -x[1], ) if isinstance(failures.get("buckets"), list): out = [] for b in failures["buckets"]: if not isinstance(b, dict): continue name = b.get("name") or b.get("bucket") or b.get("label") or "unknown" try: out.append((str(name), int(b.get("count", b.get("n", 0))))) except (TypeError, ValueError): continue return sorted(out, key=lambda x: -x[1]) if isinstance(failures.get("buckets"), dict): return sorted( ((str(k), int(v)) for k, v in failures["buckets"].items()), key=lambda x: -x[1], ) # maybe {"failures": [...]} list of rows with a bucket field rows = failures.get("failures") if isinstance(rows, list): counts: dict[str, int] = {} for r in rows: if isinstance(r, dict): k = str(r.get("bucket", r.get("name", "unknown"))) counts[k] = counts.get(k, 0) + 1 return sorted(counts.items(), key=lambda x: -x[1]) if isinstance(failures, list): counts = {} for r in failures: if isinstance(r, dict): k = str(r.get("bucket", r.get("name", "unknown"))) else: k = str(r) counts[k] = counts.get(k, 0) + 1 return sorted(counts.items(), key=lambda x: -x[1]) return []
def failure_section(failures) -> str: buckets = [(n, c) for n, c in parse_failure_buckets(failures) if n.lower() != "ok"] if not buckets: return "" total = sum(c for _, c in buckets) lines = ["## Failure modes", ""] if total <= 0: return "" for name, count in buckets[:3]: share = count / total lines.append(f"- {name}: {count} ({share:.0%} of logged failures)") lines.append("") return "\n".join(lines)
def runtime_section(runtime) -> str: if not runtime: return "" lines = ["## Runtime smoke test (llama-server)", ""] if isinstance(runtime, dict): for k, v in runtime.items(): lines.append(f"- {k}: {v}") else: lines.append(f"- result: {runtime}") lines.append("") return "\n".join(lines)
def audit_section(audit) -> str: if not audit: return "" lines = ["## Dataset audit", ""] if isinstance(audit, dict): for k, v in audit.items(): lines.append(f"- {k}: {v}") else: lines.append(f"- {audit}") lines.append("") return "\n".join(lines)
def headline_delta(base: dict, tuned: dict) -> str | None: bv, tv = num((base or {}).get("exact_call_rate")), num((tuned or {}).get("exact_call_rate")) if bv is None or tv is None: return None return f"exact-call {bv:.3f} → **{tv:.3f}** ({tv - bv:+.3f})"
RUN_IT = """## Run it
```bash# merged FP16 GGUF + native MiniCPM5 tool-call parser, Jinja chat templatellama-server \\ -m minicpm5-1b-toolcall-q4_k_m.gguf \\ --jinja -c 2048 --temp 0```
```bashcurl http://localhost:8080/v1/chat/completions \\ -H 'Content-Type: application/json' \\ -d '{ "model": "minicpm5-1b-toolcall", "messages": [{"role": "user", "content": "What is the weather in Paris?"}], "tools": [{ "type": "function", "function": { "name": "get_weather", "description": "Get the current weather for a city", "parameters": { "type": "object", "properties": { "location": {"type": "string"}, "units": {"type": "string", "enum": ["celsius", "fahrenheit"]} }, "required": ["location"] } } }] }'```"""
WARNING = """> [!WARNING]> **HF `transformers` users: decode with `skip_special_tokens=False`.**> `<function>`, `<param>`, `</param>`, `</function>` are tokenizer special tokens> (ids 18–21). Decoding with `skip_special_tokens=True` (the default in many> helpers) silently strips the tool-call syntax and scores near zero — this is a> decoding setting, not a model failure."""
LIMITATIONS = """## Limitations
- Numbers are **in-domain only** (held-out ToolACE-derived split): 500 single-turn prompts (400 tool calls + 100 no-tool) plus held-out multi-turn loops.- **One tool round**: user → call → tool result → follow-up. No multi-step chaining evaluated.- **Greedy decoding** throughout; no sampling / temperature sweep.- Arguments are **normalized** before comparison (ordering/whitespace), so exact-call is exact modulo normalization, not byte-exact.- No SOTA or BFCL claims are made; this card reports base-vs-adapter deltas only."""
def build_chart_svg(base: dict, tuned: dict) -> str: W, H = 720, 360 ml, mr, mt, mb = 56, 16, 36, 64 # margins pw, ph = W - ml - mr, H - mt - mb n = len(SINGLE_TURN_ROWS) group_w = pw / n bar_w = min(44, (group_w - 18) / 2)
def y(v: float) -> float: v = max(0.0, min(1.0, v)) return mt + ph * (1.0 - v)
parts = [ f'<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{H}" viewBox="0 0 {W} {H}" role="img">', "<title>Base vs +LoRA on single-turn tool-call metrics</title>", f"<desc>Grouped bar chart comparing base model and LoRA adapter on " f"{', '.join(l for _, l, _ in SINGLE_TURN_ROWS)}. Values 0 to 1; missing values shown as n/a.</desc>", f'<text x="{W / 2}" y="20" text-anchor="middle" font-size="15" font-family="sans-serif">' "Base vs +LoRA (single-turn)</text>", # legend f'<rect x="{ml}" y="26" width="12" height="12" fill="#94a3b8"/>', f'<text x="{ml + 16}" y="36" font-size="12" font-family="sans-serif">Base</text>', f'<rect x="{ml + 80}" y="26" width="12" height="12" fill="#2563eb"/>', f'<text x="{ml + 96}" y="36" font-size="12" font-family="sans-serif">+LoRA</text>', ] # gridlines + y labels for g in (0.0, 0.25, 0.5, 0.75, 1.0): yy = y(g) parts.append( f'<line x1="{ml}" y1="{yy}" x2="{W - mr}" y2="{yy}" stroke="#e2e8f0"/>' f'<text x="{ml - 6}" y="{yy + 4}" text-anchor="end" font-size="11" font-family="sans-serif">{g:.2f}</text>' ) # axes parts.append(f'<line x1="{ml}" y1="{mt}" x2="{ml}" y2="{mt + ph}" stroke="#64748b"/>') parts.append(f'<line x1="{ml}" y1="{mt + ph}" x2="{W - mr}" y2="{mt + ph}" stroke="#64748b"/>') parts.append( f'<text x="14" y="{mt + ph / 2}" text-anchor="middle" font-size="12" font-family="sans-serif" ' f'transform="rotate(-90 14 {mt + ph / 2})">rate</text>' ) parts.append( f'<text x="{ml + pw / 2}" y="{H - 8}" text-anchor="middle" font-size="12" ' f'font-family="sans-serif">metric</text>' )
for i, (key, label, _hib) in enumerate(SINGLE_TURN_ROWS): cx = ml + group_w * i + group_w / 2 for j, (val_raw, color, tag) in enumerate( [((base or {}).get(key), "#94a3b8", "Base"), ((tuned or {}).get(key), "#2563eb", "+LoRA")] ): v = num(val_raw) x = cx - bar_w - 2 + j * (bar_w + 4) if v is None: parts.append( f'<text x="{x + bar_w / 2}" y="{y(0) - 6}" text-anchor="middle" ' f'font-size="11" font-family="sans-serif" fill="#64748b">n/a</text>' ) else: top, bot = y(v), y(0) parts.append( f"<rect x=\"{x:.1f}\" y=\"{top:.1f}\" width=\"{bar_w:.1f}\" " f"height=\"{(bot - top):.1f}\" fill=\"{color}\">" f"<title>{html.escape(label)} {html.escape(tag)}: {v:.3f}</title></rect>" ) parts.append( f'<text x="{x + bar_w / 2:.1f}" y="{top - 5:.1f}" text-anchor="middle" ' f'font-size="11" font-family="sans-serif">{v:.2f}</text>' ) parts.append( f'<text x="{cx:.1f}" y="{mt + ph + 18}" text-anchor="middle" font-size="12" ' f'font-family="sans-serif">{html.escape(CHART_SHORT[key])}</text>' ) parts.append("</svg>") return "\n".join(parts)
def main() -> None: ap = argparse.ArgumentParser(description="Build a model card + chart from eval metrics.") ap.add_argument("--metrics", required=True, help="Path to metrics JSON.") ap.add_argument("--out", required=True, help="Output markdown path (e.g. card/README.md).") ap.add_argument("--failures", default=None) ap.add_argument("--runtime", default=None) ap.add_argument("--audit", default=None) ap.add_argument("--chart", default=None, help="SVG chart path (default: <out-dir>/chart.svg).") args = ap.parse_args()
metrics_path = Path(args.metrics) out_path = Path(args.out) metrics = load_json(metrics_path) or {}
mdir = metrics_path.parent failures = load_json(Path(args.failures) if args.failures else mdir / "failures.json") runtime = load_json(Path(args.runtime) if args.runtime else mdir / "runtime_ab.json") audit = load_json(Path(args.audit) if args.audit else mdir / "dataset_audit.json")
base = metrics.get("base") or {} tuned = metrics.get("tuned") or {} mt_base = metrics.get("multiturn_base") mt_tuned = metrics.get("multiturn_tuned")
base_model = metrics.get("base_model", BASE_MODEL) adapter = metrics.get("adapter", ADAPTER) context = metrics.get("context_tokens", metrics.get("context", CONTEXT)) val_loss = metrics.get("val_loss") steps = metrics.get("steps") n_test = base.get("n", tuned.get("n"))
delta = headline_delta(base, tuned) spec = ( f"{base_model} + {adapter}; {context}-token context; single-turn XML tool calling " f"with abstention" + (f"; headline delta: {delta}." if delta else "; headline delta: n/a.") )
mt_section = multiturn_table(mt_base, mt_tuned) fail_section = failure_section(failures) rt_section = runtime_section(runtime) audit_section_md = audit_section(audit)
eval_line = ( f"Eval: greedy decode on held-out test" + (f" (n={n_test}" if n_test is not None else " (n=n/a") + (f", val_loss={float(val_loss):.3f}" if num(val_loss) is not None else ", val_loss=n/a") + (f", steps={steps}" if steps is not None else ", steps=n/a") + ")." )
present = ["metrics.json"] if failures: present.append("failures.json") if runtime: present.append("runtime_ab.json") if audit: present.append("dataset_audit.json") card = f"""# MiniCPM5-1B ToolCall LoRA
{spec}
{eval_line}
## Results
{single_turn_table(base, tuned)}
{mt_section}{RUN_IT}
{WARNING}
{fail_section}{LIMITATIONS}{rt_section}{audit_section_md}## Links
- Adapter: https://huggingface.co/{ADAPTER_ID}- Base model: https://huggingface.co/{base_model}- Dataset: https://huggingface.co/datasets/{DATASET_ID}- Code: https://huggingface.co/datasets/{CODE_ID}- Raw predictions / logs: `reports/` ({", ".join(present)})""" out_path.parent.mkdir(parents=True, exist_ok=True) out_path.write_text(card, encoding="utf-8")
chart_path = Path(args.chart) if args.chart else out_path.parent / "chart.svg" chart_path.parent.mkdir(parents=True, exist_ok=True) chart_path.write_text(build_chart_svg(base, tuned), encoding="utf-8")
missing = [k for k in ("base", "tuned") if k not in metrics] print(f"wrote {out_path} + {chart_path}") if missing: print(f"missing top-level keys in metrics: {', '.join(missing)} (rendered as n/a)") for opt, name in ((failures, "failures"), (runtime, "runtime_ab"), (audit, "dataset_audit")): if opt is None: print(f"optional input {name}.json not found (section omitted)")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321"""Release gate: block publishing when quality or packaging is insufficient.
Usage: python pipeline/check_gate.py --metrics reports/metrics.json \ --repo DevGwardo/minicpm5-1b-toolcall --dataset DevGwardo/toolcall-mini python pipeline/check_gate.py --metrics reports/metrics.json --strict
Checks: A) Quality thresholds from metrics.json (base vs tuned, plus multiturn if present). B) Packaging files exist in the repo checkout. C) Public access of the model repo and dataset via the HF API (network problems degrade to WARN, never crash the run; --strict makes them fatal).
Exit code 0 only if every required check passes(and, under --strict, no warnings either).Always writes reports/gate.md + reports/gate.json when possible."""
import argparseimport datetimeimport jsonimport sysfrom pathlib import Path
try: import requestsexcept ImportError: # pragma: no cover requests = None
ROOT = Path(__file__).resolve().parent.parent
# Thresholds (per spec).MIN_ABSTENTION = 0.90MIN_POSITIVE_EXACT = 0.65MIN_PARSE = 0.95MIN_MT_STAGE1 = 0.60MIN_MT_STAGE2_TYPE = 0.70
def resolve(p: str) -> Path: """Resolve a path: absolute as-is, else relative to CWD, else to repo root.""" path = Path(p) if path.is_absolute(): return path if path.exists(): return path rooted = ROOT / path return rooted
def check(status, cid, name, detail, required=True): return {"id": cid, "name": name, "status": status, "detail": detail, "required": required}
def fmt(x): if x is None: return "n/a" if isinstance(x, float): return f"{x:.4f}" return str(x)
def hf_get(url): """GET with a short timeout. Returns (ok, status_code, data, error).""" try: r = requests.get(url, timeout=10) except Exception as e: # network never fails the whole run return False, None, None, f"{type(e).__name__}: {e}" try: data = r.json() if r.status_code == 200 else None except Exception: data = None return True, r.status_code, data, ""
def main(): ap = argparse.ArgumentParser(description="Release gate for MiniCPM5 toolcall.") ap.add_argument("--metrics", default="reports/metrics.json") ap.add_argument("--repo", default="DevGwardo/minicpm5-1b-toolcall") ap.add_argument("--dataset", default="DevGwardo/toolcall-mini") ap.add_argument("--strict", action="store_true", help="warnings are fatal") ap.add_argument("--gate-md", default="reports/gate.md") ap.add_argument("--gate-json", default="reports/gate.json") args = ap.parse_args()
metrics_path = resolve(args.metrics) try: metrics_rel = metrics_path.relative_to(ROOT).as_posix() except ValueError: metrics_rel = str(metrics_path) md_path = resolve(args.gate_md) js_path = resolve(args.gate_json)
checks = []
# ---- A) Quality ---- try: metrics = json.loads(metrics_path.read_text(encoding="utf-8")) except FileNotFoundError: metrics = None checks.append(check("FAIL", "quality/metrics-file", "metrics.json loads", f"not found: {metrics_path}", True)) except Exception as e: metrics = None checks.append(check("FAIL", "quality/metrics-file", "metrics.json loads", f"unreadable {metrics_path}: {e}", True))
if metrics is not None: base = metrics.get("base") or {} tuned = metrics.get("tuned") or {} mt = metrics.get("multiturn_tuned")
def num(d, k): v = d.get(k) return v if isinstance(v, (int, float)) else None
abst = num(tuned, "abstention_accuracy") if abst is None: checks.append(check("FAIL", "quality/abstention", "abstention_accuracy >= 0.90", "tuned.abstention_accuracy missing", True)) else: checks.append(check("PASS" if abst >= MIN_ABSTENTION else "FAIL", "quality/abstention", "abstention_accuracy >= 0.90", f"tuned={fmt(abst)} threshold={MIN_ABSTENTION}", True))
pex = num(tuned, "positive_exact_rate") if pex is None: checks.append(check("FAIL", "quality/positive-exact", "positive_exact_rate >= 0.65", "tuned.positive_exact_rate missing", True)) else: checks.append(check("PASS" if pex >= MIN_POSITIVE_EXACT else "FAIL", "quality/positive-exact", "positive_exact_rate >= 0.65", f"tuned={fmt(pex)} threshold={MIN_POSITIVE_EXACT}", True))
prs = num(tuned, "parse_rate") if prs is None: checks.append(check("FAIL", "quality/parse", "parse_rate >= 0.95", "tuned.parse_rate missing", True)) else: checks.append(check("PASS" if prs >= MIN_PARSE else "FAIL", "quality/parse", "parse_rate >= 0.95", f"tuned={fmt(prs)} threshold={MIN_PARSE}", True))
b_exact = num(base, "exact_call_rate") t_exact = num(tuned, "exact_call_rate") if b_exact is None or t_exact is None: checks.append(check("FAIL", "quality/improvement", "tuned.exact_call_rate > base", f"missing (base={fmt(b_exact)} tuned={fmt(t_exact)})", True)) else: checks.append(check("PASS" if t_exact > b_exact else "FAIL", "quality/improvement", "tuned.exact_call_rate > base", f"base={fmt(b_exact)} tuned={fmt(t_exact)} " f"delta={t_exact - b_exact:+.4f} (strict >)", True))
if isinstance(mt, dict) and mt: s1 = num(mt, "stage1_exact") s2 = num(mt, "stage2_type_accuracy") if s1 is None: checks.append(check("FAIL", "quality/mt-stage1", "stage1_exact >= 0.60", "multiturn_tuned.stage1_exact missing", True)) else: checks.append(check("PASS" if s1 >= MIN_MT_STAGE1 else "FAIL", "quality/mt-stage1", "stage1_exact >= 0.60", f"tuned={fmt(s1)} threshold={MIN_MT_STAGE1}", True)) if s2 is None: checks.append(check("FAIL", "quality/mt-stage2", "stage2_type_accuracy >= 0.70", "multiturn_tuned.stage2_type_accuracy missing", True)) else: checks.append(check("PASS" if s2 >= MIN_MT_STAGE2_TYPE else "FAIL", "quality/mt-stage2", "stage2_type_accuracy >= 0.70", f"tuned={fmt(s2)} threshold={MIN_MT_STAGE2_TYPE}", True)) else: checks.append(check("SKIP", "quality/mt-stage1", "stage1_exact >= 0.60", "no multiturn_tuned in metrics; skipped", False)) checks.append(check("SKIP", "quality/mt-stage2", "stage2_type_accuracy >= 0.70", "no multiturn_tuned in metrics; skipped", False))
# ---- B) Packaging ---- def exists(rel): return (ROOT / rel).is_file()
checks.append(check("PASS" if exists("PROJECT.md") else "FAIL", "packaging/project-md", "PROJECT.md exists", "found" if exists("PROJECT.md") else "missing PROJECT.md", True)) checks.append(check("PASS" if exists("pipeline/test_runtime.py") else "FAIL", "packaging/test-runtime", "pipeline/test_runtime.py exists", "found" if exists("pipeline/test_runtime.py") else "missing pipeline/test_runtime.py", True)) checks.append(check("PASS" if exists("repro/README.md") else "FAIL", "packaging/repro-readme", "repro/README.md exists", "found" if exists("repro/README.md") else "missing repro/README.md", True))
card_ok = exists("card/README.md") root_ok = exists("README.md") if card_ok or root_ok: detail = "found " + ", ".join( [p for p, ok in (("card/README.md", card_ok), ("README.md", root_ok)) if ok]) else: detail = "missing both card/README.md and README.md (need at least one)" checks.append(check("PASS" if (card_ok or root_ok) else "FAIL", "packaging/model-card", "card/README.md or README.md exists", detail, True))
pred_candidates = [ROOT / "reports" / "predictions.jsonl", ROOT / "out" / "predictions.jsonl", ROOT / "predictions.jsonl"] found_pred = next((p for p in pred_candidates if p.is_file()), None) if found_pred is None: # fallback: any *predict* file under reports/ reports_dir = ROOT / "reports" if reports_dir.is_dir(): alts = sorted([p for p in reports_dir.glob("*predict*") if p.is_file()]) if alts: found_pred = alts[0] if found_pred is not None: try: rel = found_pred.relative_to(ROOT).as_posix() except ValueError: rel = str(found_pred) checks.append(check("PASS", "packaging/predictions", "predictions file exists", f"found {rel}", True)) else: checks.append(check("FAIL", "packaging/predictions", "predictions file exists", "missing reports/predictions.jsonl (no *predict* fallback found)", True))
# ---- C) Public access ---- if requests is None: checks.append(check("WARN", "access/dataset", f"dataset {args.dataset} public", "requests not installed; cannot verify", False)) checks.append(check("WARN", "access/model", f"model {args.repo} public", "requests not installed; cannot verify", False)) else: durl = f"https://huggingface.co/api/datasets/{args.dataset}" ok, code, data, err = hf_get(durl) if not ok: checks.append(check("WARN", "access/dataset", f"dataset {args.dataset} public", f"network error ({err}); could not verify {durl}", False)) elif code != 200: checks.append(check("FAIL", "access/dataset", f"dataset {args.dataset} public", f"GET {durl} -> HTTP {code}", True)) elif isinstance(data, dict) and data.get("private") is True: checks.append(check("FAIL", "access/dataset", f"dataset {args.dataset} public", "dataset is private (private == true)", True)) else: checks.append(check("PASS", "access/dataset", f"dataset {args.dataset} public", f"GET {durl} -> 200, private == false", True))
murl = f"https://huggingface.co/api/models/{args.repo}" ok, code, data, err = hf_get(murl) if not ok: checks.append(check("WARN", "access/model", f"model {args.repo} public", f"network error ({err}); could not verify {murl}", False)) elif code != 200: checks.append(check("FAIL", "access/model", f"model {args.repo} public", f"GET {murl} -> HTTP {code}", True)) else: checks.append(check("PASS", "access/model", f"model {args.repo} public", f"GET {murl} -> 200", True))
fails = [c for c in checks if c["status"] == "FAIL" and c["required"]] warns = [c for c in checks if c["status"] == "WARN"] verdict = "PASS" if not fails and not (args.strict and warns) else "FAIL"
# ---- console ---- for c in checks: print(f'[{c["status"]}] {c["id"]}: {c["name"]} -- {c["detail"]}') print(f"VERDICT: {verdict} " f"({len(fails)} required failure(s), {len(warns)} warning(s)" f"{', --strict' if args.strict else ''})")
# ---- reports ---- payload = { "verdict": verdict, "strict": args.strict, "repo": args.repo, "dataset": args.dataset, "metrics": metrics_rel, "generated_utc": datetime.datetime.now(datetime.timezone.utc).isoformat(), "thresholds": { "abstention_accuracy": MIN_ABSTENTION, "positive_exact_rate": MIN_POSITIVE_EXACT, "parse_rate": MIN_PARSE, "multiturn_stage1_exact": MIN_MT_STAGE1, "multiturn_stage2_type_accuracy": MIN_MT_STAGE2_TYPE, "exact_improvement": "tuned.exact_call_rate > base.exact_call_rate (strict)", }, "checks": checks, } try: md_path.parent.mkdir(parents=True, exist_ok=True) js_path.parent.mkdir(parents=True, exist_ok=True) js_path.write_text(json.dumps(payload, indent=2), encoding="utf-8") lines = [f"# Release gate: {verdict}", "", f"- repo: `{args.repo}`", f"- dataset: `{args.dataset}`", f"- metrics: `{metrics_rel}` (`{metrics_path}`)", f"- strict: `{args.strict}`", f"- generated (UTC): `{payload['generated_utc']}`", "", "| Check | Status | Detail | Required |", "|---|---|---|---|"] for c in checks: lines.append(f"| `{c['id']}` | {c['status']} | {c['detail']} | {c['required']} |") lines += ["", f"**Verdict: {verdict}**", "" if verdict == "PASS" else "_FAIL: do not publish until every required FAIL is fixed" + (" (warnings fatal under --strict)." if args.strict and warns and not fails else "."), ""] md_path.write_text("\n".join(lines), encoding="utf-8") print(f"wrote {md_path} and {js_path}") except Exception as e: print(f"WARNING: could not write reports: {e}", file=sys.stderr)
return 0 if verdict == "PASS" else 1
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342#!/usr/bin/env python3# -*- coding: utf-8 -*-
from __future__ import annotations
import argparseimport loggingimport osimport sysfrom pathlib import Path
import torch
if 'NO_LOCAL_GGUF' not in os.environ: sys.path.insert(1, str(Path(__file__).parent / 'gguf-py'))import gguf
from conversion import ( ModelBase, ModelType, get_model_architecture, get_model_class, logger, print_registered_models, _mistral_common_installed, _mistral_import_error_msg,)
def split_str_to_n_bytes(split_str: str) -> int: if split_str.endswith("K"): n = int(split_str[:-1]) * 1000 elif split_str.endswith("M"): n = int(split_str[:-1]) * 1000 * 1000 elif split_str.endswith("G"): n = int(split_str[:-1]) * 1000 * 1000 * 1000 elif split_str.isnumeric(): n = int(split_str) else: raise ValueError(f"Invalid split size: {split_str}, must be a number, optionally followed by K, M, or G")
if n < 0: raise ValueError(f"Invalid split size: {split_str}, must be positive")
return n
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser( description="Convert a huggingface model to a GGML compatible file") parser.add_argument( "--vocab-only", action="store_true", help="extract only the vocab", ) parser.add_argument( "--outfile", type=Path, help="path to write to; default: based on input. {ftype} will be replaced by the outtype.", ) parser.add_argument( "--outtype", type=str, choices=["f32", "f16", "bf16", "q8_0", "tq1_0", "tq2_0", "auto"], default="auto", help="output format - use f32 for float32, f16 for float16, bf16 for bfloat16, q8_0 for Q8_0, tq1_0 or tq2_0 for ternary, and auto to preserve supported FP8 weights and otherwise select the highest-fidelity 16-bit float type", ) parser.add_argument( "--bigendian", action="store_true", help="model is executed on big endian machine", ) parser.add_argument( "model", type=str, help="directory containing model file or huggingface repository ID (if --remote)", nargs="?", ) parser.add_argument( "--use-temp-file", action="store_true", help="use the tempfile library while processing (helpful when running out of memory, process killed)", ) parser.add_argument( "--no-lazy", action="store_true", help="use more RAM by computing all outputs before writing (use in case lazy evaluation is broken)", ) parser.add_argument( "--model-name", type=str, default=None, help="name of the model", ) parser.add_argument( "--verbose", action="store_true", help="increase output verbosity", ) parser.add_argument( "--split-max-tensors", type=int, default=0, help="max tensors in each split", ) parser.add_argument( "--split-max-size", type=str, default="0", help="max size per split N(M|G)", ) parser.add_argument( "--dry-run", action="store_true", help="only print out a split plan and exit, without writing any new files", ) parser.add_argument( "--no-tensor-first-split", action="store_true", help="do not add tensors to the first split (disabled by default)" ) parser.add_argument( "--metadata", type=Path, help="Specify the path for an authorship metadata override file" ) parser.add_argument( "--print-supported-models", action="store_true", help="Print the supported models" ) parser.add_argument( "--remote", action="store_true", help="(Experimental) Read safetensors file remotely without downloading to disk. Config and tokenizer files will still be downloaded. To use this feature, you need to specify Hugging Face model repo name instead of a local directory. For example: 'HuggingFaceTB/SmolLM2-1.7B-Instruct'. Note: To access gated repo, set HF_TOKEN environment variable to your Hugging Face token.", ) parser.add_argument( "--mmproj", action="store_true", help="Export multimodal projector (mmproj) for vision models. This will only work on some vision models. An 'mmproj-' prefix will be added to the output file name.", ) parser.add_argument( "--mtp", action="store_true", help="Export only the multi-token prediction (MTP) head as a separate GGUF, suitable for use as a speculative draft. An 'mtp-' prefix will be added to the output file name.", ) parser.add_argument( "--no-nextn", "--no-mtp", dest="no_mtp", action="store_true", help="Exclude NextN speculative draft tensors from the converted GGUF. Pair with --mtp or --dspark on a second run to publish target and draft as two files.", ) ple_group = parser.add_mutually_exclusive_group() ple_group.add_argument( "--ple-only", action="store_true", help="Export only the per-layer embedding table as a separate GGUF for use with --shard (alias: --ple).", ) ple_group.add_argument( "--no-ple", action="store_true", help="Exclude the per-layer embedding table while retaining its metadata. Load the table separately with --shard (alias: --ple).", ) parser.add_argument( "--dspark", action="store_true", help="Export only the DeepSeek-V4, Mistral Large 4 or Inkling 2 DSpark draft tensors as a separate GGUF.", ) parser.add_argument( "--mistral-format", action="store_true", help="Whether the model is stored following the Mistral format.", ) parser.add_argument( "--disable-mistral-community-chat-template", action="store_true", help=( "Whether to disable usage of Mistral community chat templates. If set, use the Mistral official `mistral-common` library for tokenization and detokenization of Mistral models. " "Using `mistral-common` ensure correctness and zero-day support of tokenization for models converted from the Mistral format but requires to manually setup the tokenization server." ) )
parser.add_argument( "--sentence-transformers-dense-modules", action="store_true", help=("Whether to include sentence-transformers dense modules. " "It can be used for sentence-transformers models, like google/embeddinggemma-300m. " "Default these modules are not included.") )
parser.add_argument( "--fuse-gate-up-exps", action="store_true", help="Fuse gate_exps and up_exps tensors into a single gate_up_exps tensor for MoE models.", ) parser.add_argument( "--fp8-as-q8", action="store_true", help="Store tensors dequantized from FP8 as Q8_0 instead of BF16/F16.", )
parser.add_argument( "--fuse-qkv", action="store_true", help="Fuse separate Q, K, V weight tensors into a single QKV tensor.", ) parser.add_argument( "--target-model-dir", type=str, default=None, help=( "path to the target model directory; required when converting a standalone draft model " "(e.g. EAGLE3 / DFlash) that needs target-model metadata such as tokenizer, hidden size, and " "layer count to populate its GGUF." ), )
args = parser.parse_args() if not args.print_supported_models and args.model is None: parser.error("the following arguments are required: model") if (args.ple_only or args.no_ple) and (args.vocab_only or args.mmproj or args.mtp or args.dspark): parser.error("--ple-only / --no-ple cannot be combined with --vocab-only, --mmproj, --mtp, or --dspark") if args.ple_only and args.no_tensor_first_split: parser.error("--ple-only cannot be combined with --no-tensor-first-split") return args
def main() -> None: args = parse_args()
if args.print_supported_models: logger.error("Supported models:") print_registered_models() sys.exit(0)
if args.verbose: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO)
if args.remote: hf_repo_id = args.model from huggingface_hub import snapshot_download allowed_patterns = ["LICENSE", "*.json", "*.md", "*.txt", "tokenizer.model"] if args.sentence_transformers_dense_modules: # include sentence-transformers dense modules safetensors files allowed_patterns.append("*.safetensors") local_dir = snapshot_download( repo_id=hf_repo_id, allow_patterns=allowed_patterns) dir_model = Path(local_dir) logger.info(f"Downloaded config and tokenizer to {local_dir}") else: hf_repo_id = None dir_model = Path(args.model)
if not dir_model.is_dir(): logger.error(f'Error: {dir_model} is not a directory') sys.exit(1)
ftype_map: dict[str, gguf.LlamaFileType] = { "f32": gguf.LlamaFileType.ALL_F32, "f16": gguf.LlamaFileType.MOSTLY_F16, "bf16": gguf.LlamaFileType.MOSTLY_BF16, "q8_0": gguf.LlamaFileType.MOSTLY_Q8_0, "tq1_0": gguf.LlamaFileType.MOSTLY_TQ1_0, "tq2_0": gguf.LlamaFileType.MOSTLY_TQ2_0, "auto": gguf.LlamaFileType.GUESSED, }
is_split = args.split_max_tensors > 0 or args.split_max_size != "0" if args.use_temp_file and is_split: logger.error("Error: Cannot use temp file when splitting") sys.exit(1)
if args.outfile is not None: fname_out = args.outfile elif hf_repo_id: # if remote, use the model ID as the output file name fname_out = Path("./" + hf_repo_id.replace("/", "-") + "-{ftype}.gguf") else: fname_out = dir_model
logger.info(f"Loading model: {dir_model.name}")
is_mistral_format = args.mistral_format if is_mistral_format and not _mistral_common_installed: raise ImportError(_mistral_import_error_msg) disable_mistral_community_chat_template = args.disable_mistral_community_chat_template
with torch.inference_mode(): output_type = ftype_map[args.outtype] model_type = ModelType.MMPROJ if args.mmproj else ModelType.TEXT hparams = ModelBase.load_hparams(dir_model, is_mistral_format) if not is_mistral_format: model_architecture = get_model_architecture(hparams, model_type) logger.info(f"Model architecture: {model_architecture}") try: model_class = get_model_class(model_architecture, mmproj=(model_type == ModelType.MMPROJ)) except NotImplementedError: logger.error(f"Model {model_architecture} is not supported") sys.exit(1) elif args.mmproj: assert hparams.get("vision_encoder") is not None, "This model does not support multimodal" from conversion.pixtral import PixtralModel model_class = PixtralModel elif hparams.get("moe") is not None and hparams.get("dsa") is not None: from conversion.mistral4 import MistralLarge4Model model_class = MistralLarge4Model elif hparams.get("moe") is not None: from conversion.mistral import MistralMoeModel model_class = MistralMoeModel else: from conversion.mistral import MistralModel model_class = MistralModel
if sum((args.mtp, args.no_mtp, args.dspark)) > 1: logger.error("--mtp, --no-nextn, and --dspark are mutually exclusive") sys.exit(1)
if args.dspark: if is_mistral_format or model_architecture == "MistralLarge4ForConditionalGeneration": if model_class.__name__ != "MistralLarge4Model": logger.error("--dspark is only supported for Mistral Large 4 among Mistral-format models") sys.exit(1) from conversion.mistral4 import MistralLarge4DSparkModel model_class = MistralLarge4DSparkModel elif model_architecture in ("Inkling2ForConditionalGeneration", "Inkling2ForCausalLM", "Inkling2LoopForConditionalGeneration", "Inkling2LoopForCausalLM"): from conversion.inkling2 import Inkling2DSparkModel model_class = Inkling2DSparkModel elif model_architecture not in ("DeepseekV4ForCausalLM", "DeepseekV41ForCausalLM"): logger.error("--dspark is only supported for DeepseekV4ForCausalLM, DeepseekV41ForCausalLM, Mistral Large 4 and Inkling 2") sys.exit(1) elif model_architecture == "DeepseekV41ForCausalLM": from conversion.deepseek41 import DeepseekV41DSparkModel model_class = DeepseekV41DSparkModel else: from conversion.deepseek import DeepseekV4DSparkModel model_class = DeepseekV4DSparkModel
if args.mtp or args.no_mtp: if not model_class.supports_mtp_export: logger.error("--mtp / --no-nextn are not supported for %s", model_architecture) sys.exit(1) if args.no_mtp: model_class.no_mtp = True if args.mtp: model_class.mtp_only = True
model_instance = model_class(dir_model, output_type, fname_out, is_big_endian=args.bigendian, use_temp_file=args.use_temp_file, eager=args.no_lazy, metadata_override=args.metadata, model_name=args.model_name, split_max_tensors=args.split_max_tensors, split_max_size=split_str_to_n_bytes(args.split_max_size), dry_run=args.dry_run, small_first_shard=args.no_tensor_first_split, remote_hf_model_id=hf_repo_id, disable_mistral_community_chat_template=disable_mistral_community_chat_template, sentence_transformers_dense_modules=args.sentence_transformers_dense_modules, target_model_dir=Path(args.target_model_dir) if args.target_model_dir else None, fuse_gate_up_exps=args.fuse_gate_up_exps, fp8_as_q8=args.fp8_as_q8, fuse_qkv=args.fuse_qkv, ple_only=args.ple_only, no_ple=args.no_ple, )
if args.vocab_only: logger.info("Exporting model vocab...") model_instance.write_vocab() logger.info(f"Model vocab successfully exported to {model_instance.fname_out}") else: logger.info("Exporting model...") model_instance.write() out_path = f"{model_instance.fname_out.parent}{os.sep}" if is_split else model_instance.fname_out logger.info(f"Model successfully exported to {out_path}")
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485"""Standalone evaluator for any OpenAI-compatible tool-calling server.
Scores a running server (llama-server --jinja, vLLM, SGLang, ...) against``data_native/test.jsonl`` without any local model weights.
Data schema per line::
{"tools": [{"name", "description", "parameters"}], "messages": [{"role": "user", ...}, {"role": "assistant", "content": "", "tool_calls": [...]} ...]}
Abstention rows have a final assistant message with plain ``content`` and no``tool_calls``.
Example::
python pipeline/eval_openai.py --base-url http://127.0.0.1:8080/v1 \\ --model local --data data_native/test.jsonl \\ --out reports/runtime_eval --limit 100 python pipeline/eval_openai.py --base-url http://127.0.0.1:8080/v1 \\ --model local --data data_native/mt_test.jsonl \\ --out reports/runtime_eval_mt --staged
Requires ``pipeline/metrics_lib.py`` (imported, not created here) and thethird-party package ``requests``. Everything else is stdlib."""
from __future__ import annotations
import argparseimport jsonimport sysimport timefrom pathlib import Pathfrom typing import Any, Dict, List, Tuple
import requests
sys.path.insert(0, str(Path(__file__).resolve().parent))
_METRICS: Dict[str, Any] | None = None
def _metrics() -> Dict[str, Any]: """Lazily import pipeline/metrics_lib.py (assumed to exist at eval time).
The import is deferred so ``--help`` and CLI parsing work even when no server (or metrics module) is present. This function does not create or stub the module; it only imports the documented names. """ global _METRICS if _METRICS is None: from metrics_lib import ( # type: ignore # noqa: E402 parse_calls, canon_call, categorize, failure_bucket, ) _METRICS = { "parse_calls": parse_calls, "canon_call": canon_call, "categorize": categorize, "failure_bucket": failure_bucket, } return _METRICS
# --------------------------------------------------------------------------- ## Conversion helpers# --------------------------------------------------------------------------- #
def load_jsonl(path: str | Path) -> List[Dict[str, Any]]: """Load a JSONL file, skipping blank lines.""" rows: List[Dict[str, Any]] = [] with open(path, encoding="utf-8") as f: for line in f: line = line.strip() if line: rows.append(json.loads(line)) return rows
def to_openai_tools(tools: List[Dict[str, Any]]) -> List[Dict[str, Any]]: """Convert native tool defs to OpenAI ``{"type": "function", ...}`` form.""" out: List[Dict[str, Any]] = [] for t in tools or []: fn: Dict[str, Any] = { "name": t.get("name", ""), "description": t.get("description", ""), } params = t.get("parameters") if params is not None: if isinstance(params, dict): params = dict(params) # Native data uses "dict"; OpenAI expects "object". if params.get("type") == "dict": params["type"] = "object" fn["parameters"] = params out.append({"type": "function", "function": fn}) return out
def to_openai_messages(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]: """Convert a native message prefix to OpenAI chat format.
Native assistant turns carry ``tool_calls: [{name, arguments(dict)}]`` without wire ids; we synthesize ``id`` values. Native ``tool`` turns lack ``tool_call_id``; we bind them to the most recent assistant call id. """ out: List[Dict[str, Any]] = [] last_ids: List[str] = [] for k, m in enumerate(messages): role = m.get("role", "user") if role == "tool": content = m.get("content", "") if not isinstance(content, str): content = json.dumps(content, ensure_ascii=False) tool_msg: Dict[str, Any] = { "role": "tool", "content": content, "tool_call_id": m.get("tool_call_id") or (last_ids[0] if last_ids else "call_0"), } out.append(tool_msg) continue if role == "assistant": tc = m.get("tool_calls") or [] content = m.get("content", "") if content is None: content = "" if not isinstance(content, str): content = json.dumps(content, ensure_ascii=False) if tc: last_ids = [f"call_{k}_{j}" for j in range(len(tc))] oai_tc: List[Dict[str, Any]] = [] for j, c in enumerate(tc): args = c.get("arguments", {}) oai_tc.append({ "id": last_ids[j], "type": "function", "function": { "name": c.get("name", ""), "arguments": json.dumps(args, ensure_ascii=False) if not isinstance(args, str) else args, }, }) out.append({"role": "assistant", "content": content, "tool_calls": oai_tc}) else: out.append({"role": "assistant", "content": content}) continue # user / system / anything else: pass content through as string. content = m.get("content", "") if not isinstance(content, str): content = json.dumps(content, ensure_ascii=False) out.append({"role": role, "content": content}) return out
def expected_calls(message: Dict[str, Any]) -> List[Dict[str, Any]]: """Ground-truth calls from a native assistant message (``[]`` if abstain).""" tc = message.get("tool_calls") or [] return [{"name": c.get("name", ""), "arguments": c.get("arguments", {})} for c in tc]
def parse_response(msg: Dict[str, Any]) -> Tuple[List[Dict[str, Any]], str]: """Parse an OpenAI response message into native-style calls.
Prefer ``message.tool_calls[].function`` (``arguments`` may be a JSON string); fall back to XML parsing of ``message.content`` via ``metrics_lib.parse_calls``. """ content = msg.get("content") or "" if not isinstance(content, str): content = json.dumps(content, ensure_ascii=False) raw: str = content tc = msg.get("tool_calls") or [] if tc: calls: List[Dict[str, Any]] = [] for c in tc: fn = c.get("function", c) if isinstance(c, dict) else {} name = fn.get("name", "") if isinstance(fn, dict) else "" args = fn.get("arguments", {}) if isinstance(fn, dict) else {} if isinstance(args, str): s = args.strip() if not s: args = {} else: try: args = json.loads(s) except (json.JSONDecodeError, ValueError): args = {} if not isinstance(args, dict): args = {} calls.append({"name": name, "arguments": args}) if not raw: raw = json.dumps( [{"name": c["name"], "arguments": c["arguments"]} for c in calls], ensure_ascii=False, ) return calls, raw try: calls = _metrics()["parse_calls"](content) except Exception: calls = [] if not isinstance(calls, list): calls = [] return calls, raw
def canon_sorted(calls: List[Dict[str, Any]]) -> List[Any]: """Canonical sort key for a call list (order-insensitive compare).""" canon_call = _metrics()["canon_call"] return sorted(canon_call(c) for c in calls)
# --------------------------------------------------------------------------- ## HTTP# --------------------------------------------------------------------------- #
def chat_once( session: requests.Session, url: str, payload: Dict[str, Any], timeout: float,) -> Tuple[Dict[str, Any] | None, str]: """POST one /chat/completions request; never raises.
Returns ``(message, "")`` on success or ``(None, "ERROR: ...")`` on any transport / HTTP-status / schema failure. """ try: resp = session.post(url, json=payload, timeout=timeout) except requests.RequestException as exc: return None, f"ERROR: request failed: {exc}" if resp.status_code >= 400: return None, f"ERROR: HTTP {resp.status_code}: {resp.text[:300]}" try: data = resp.json() msg = data["choices"][0]["message"] except (ValueError, KeyError, IndexError, TypeError) as exc: return None, f"ERROR: bad response schema: {exc}" if not isinstance(msg, dict): return None, "ERROR: bad response schema: message is not an object" return msg, ""
# --------------------------------------------------------------------------- ## Eval# --------------------------------------------------------------------------- #
def evaluate_row( session: requests.Session, url: str, model: str, tools: List[Dict[str, Any]], prefix: List[Dict[str, Any]], expected: List[Dict[str, Any]], max_tokens: int, timeout: float,) -> Tuple[List[Dict[str, Any]], str, bool]: """Query the server once; returns (predicted, raw, transport_ok).""" payload = { "model": model, "messages": to_openai_messages(prefix), "tools": to_openai_tools(tools), "tool_choice": "auto", "temperature": 0, "max_tokens": max_tokens, } msg, err = chat_once(session, url, payload, timeout) if msg is None: return [], err, False predicted, raw = parse_response(msg) return predicted, raw, True
def safe_bucket(expected: List[Dict[str, Any]], predicted: List[Dict[str, Any]], raw: str) -> str: """Call metrics_lib.failure_bucket without ever aborting the run.""" try: return str(_metrics()["failure_bucket"](expected, predicted, raw)) except Exception as exc: return f"eval_error: {exc}"
def safe_category(row: Dict[str, Any]) -> str: """Call metrics_lib.categorize without ever aborting the run.""" try: return str(_metrics()["categorize"](row)) except Exception: return "unknown"
def print_table(metrics: Dict[str, Any]) -> None: """Print a compact ASCII summary table.""" rows = [ ("n", str(metrics.get("n", 0))), ("exact_call_rate", f"{metrics.get('exact_call_rate', 0.0):.3f}"), ("name_accuracy", f"{metrics.get('name_accuracy', 0.0):.3f}"), ("parse_rate", f"{metrics.get('parse_rate', 0.0):.3f}"), ("abstention_accuracy", f"{metrics.get('abstention_accuracy', 0.0):.3f}"), ("false_positive_rate", f"{metrics.get('false_positive_rate', 0.0):.3f}"), ] if "stage1_exact" in metrics: rows.append(("stage1_exact", f"{metrics['stage1_exact']:.3f}")) if "stage2_type_accuracy" in metrics: rows.append(("stage2_type_accuracy", f"{metrics['stage2_type_accuracy']:.3f}")) width = max(len(k) for k, _ in rows) print("=" * (width + 12)) print(f"{'metric':<{width}} | value") print("-" * (width + 12)) for k, v in rows: print(f"{k:<{width}} | {v}") print("-" * (width + 12)) by_cat = metrics.get("by_category", {}) if by_cat: print("by_category:") for cat in sorted(by_cat): c = by_cat[cat] print( f" {cat}: n={c.get('n', 0)} " f"exact={c.get('exact_call_rate', 0.0):.3f} " f"name={c.get('name_accuracy', 0.0):.3f}" ) print("=" * (width + 12))
def build_parser() -> argparse.ArgumentParser: """Build the CLI parser.""" ap = argparse.ArgumentParser( description="Score an OpenAI-compatible tool-calling server " "against data_native/test.jsonl (or any native JSONL).", epilog="Example: python pipeline/eval_openai.py " "--base-url http://127.0.0.1:8080/v1 --model local " "--data data_native/test.jsonl --out reports/runtime_eval --limit 100", ) ap.add_argument("--base-url", default="http://127.0.0.1:8080/v1", help="Server base URL (appended with /chat/completions).") ap.add_argument("--model", default="local", help="Model name sent in the request.") ap.add_argument("--data", default="data_native/test.jsonl", help="Input native JSONL.") ap.add_argument("--out", default="reports/runtime_eval", help="Output directory.") ap.add_argument("--limit", type=int, default=0, help="Max rows to evaluate (0 = all).") ap.add_argument("--staged", action="store_true", help="For 4-message rows also query stage 1 (messages[:1]) and " "report stage1_exact / stage2_type_accuracy.") ap.add_argument("--timeout", type=float, default=120.0, help="Per-request timeout in seconds.") ap.add_argument("--max-tokens", type=int, default=256, help="max_tokens sent per request.") return ap
def main() -> None: """Run the evaluation and write predictions.jsonl + metrics.json.""" ap = build_parser() args = ap.parse_args()
try: _metrics() except ImportError as exc: print(f"error: pipeline/metrics_lib.py is required but could not be imported: {exc}", file=sys.stderr) sys.exit(2)
rows = load_jsonl(args.data) if args.limit and args.limit > 0: rows = rows[: args.limit]
url = args.base_url.rstrip("/") + "/chat/completions" out = Path(args.out) out.mkdir(parents=True, exist_ok=True)
session = requests.Session() details: List[Dict[str, Any]] = [] n_exact = n_name = n_parse = 0 neg_total = neg_ok = neg_fp = 0 by_cat: Dict[str, Dict[str, int]] = {} # Staged accumulators (4-message rows only). s1_total = s1_exact = 0 s2_total = s2_type_ok = 0
t0 = time.time() for i, row in enumerate(rows): messages = row.get("messages", []) tools = row.get("tools", []) category = safe_category(row) expected = expected_calls(messages[-1]) if messages else [] prefix = messages[:-1] if len(messages) > 1 else messages
predicted, raw, ok = evaluate_row( session, url, args.model, tools, prefix, expected, args.max_tokens, args.timeout, ) if ok: exact = canon_sorted(predicted) == canon_sorted(expected) name_match = sorted(c.get("name", "") for c in predicted) == sorted( c.get("name", "") for c in expected ) parse_ok = bool(predicted) or not expected else: # Transport / HTTP / schema failure: never award points. exact = False name_match = False parse_ok = False bucket = safe_bucket(expected, predicted, raw)
n_exact += exact n_name += name_match n_parse += parse_ok if not expected: neg_total += 1 neg_ok += not predicted neg_fp += bool(predicted) cell = by_cat.setdefault(category, {"n": 0, "exact": 0, "name": 0}) cell["n"] += 1 cell["exact"] += exact cell["name"] += name_match
details.append({ "i": i, "category": category, "expected": expected, "predicted": predicted, "raw": raw[:2000] if isinstance(raw, str) else raw, "exact": exact, "name_match": name_match, "bucket": bucket, })
# Staged multi-turn scoring for 4-message loops. if args.staged and len(messages) == 4: exp1 = expected_calls(messages[1]) pred1, _, ok1 = evaluate_row( session, url, args.model, tools, messages[:1], exp1, args.max_tokens, args.timeout, ) s1_total += 1 # Stage 2 reuses the main request above (prefix == messages[:3]). s2_total += 1 if ok1 and canon_sorted(pred1) == canon_sorted(exp1): s1_exact += 1 exp2 = expected # messages[3] ground truth if (not predicted) == (not exp2) and ok: s2_type_ok += 1
if (i + 1) % 25 == 0 or (i + 1) == len(rows): print(f"[{i + 1}/{len(rows)}] exact={n_exact / (i + 1):.3f}", flush=True)
n = len(rows) metrics: Dict[str, Any] = { "n": n, "exact_call_rate": n_exact / n if n else 0.0, "name_accuracy": n_name / n if n else 0.0, "parse_rate": n_parse / n if n else 0.0, "abstention_accuracy": (neg_ok / neg_total) if neg_total else 0.0, "false_positive_rate": (neg_fp / neg_total) if neg_total else 0.0, "n_abstention": neg_total, "by_category": { cat: { "n": c["n"], "exact_call_rate": c["exact"] / c["n"] if c["n"] else 0.0, "name_accuracy": c["name"] / c["n"] if c["n"] else 0.0, } for cat, c in by_cat.items() }, "model": args.model, "base_url": args.base_url, "data": str(args.data), "elapsed_s": round(time.time() - t0, 1), } if args.staged: metrics["stage1_n"] = s1_total metrics["stage2_n"] = s2_total metrics["stage1_exact"] = (s1_exact / s1_total) if s1_total else 0.0 metrics["stage2_type_accuracy"] = (s2_type_ok / s2_total) if s2_total else 0.0
(out / "predictions.jsonl").write_text( "\n".join(json.dumps(d, ensure_ascii=False) for d in details), encoding="utf-8" ) (out / "metrics.json").write_text(json.dumps(metrics, indent=2), encoding="utf-8") print(f"wrote {out / 'predictions.jsonl'} + {out / 'metrics.json'}") print_table(metrics)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596param( [string]$AdapterRepo = "DevGwardo/minicpm5-1b-toolcall", [string]$OutDir = "gguf", [string]$MergedDir = "merged", [switch]$SkipMerge)
$ErrorActionPreference = 'Stop'
# Project root = parent of this script's directory (pipeline\).$ProjectRoot = if ($PSScriptRoot) { Split-Path $PSScriptRoot -Parent } else { (Get-Location).Path }
function Resolve-FromRoot([string]$p) { if ([System.IO.Path]::IsPathRooted($p)) { return $p } return (Join-Path $ProjectRoot $p)}
$Python = Resolve-FromRoot '.venv\Scripts\python.exe'$MergeScript = Resolve-FromRoot 'pipeline\merge_local.py'$ConvertScript = Resolve-FromRoot 'llama.cpp-src\convert_hf_to_gguf.py'$Quantize = Resolve-FromRoot 'llama-bin\llama-quantize.exe'$MergedFull = Resolve-FromRoot $MergedDir$OutFull = Resolve-FromRoot $OutDir
# NOTE: $AdapterRepo is informational. pipeline/merge_local.py currently# hardcodes BASE="openbmb/MiniCPM5-1B" and ADAPTER="DevGwardo/minicpm5-1b-toolcall",# so a non-default -AdapterRepo value is accepted but NOT forwarded to the merge.if ($AdapterRepo -ne 'DevGwardo/minicpm5-1b-toolcall') { Write-Host ("WARNING: -AdapterRepo '{0}' is ignored by pipeline/merge_local.py (hardcoded adapter)." -f $AdapterRepo) -ForegroundColor Yellow}if ($MergedDir -ne 'merged') { Write-Host 'WARNING: pipeline/merge_local.py always writes to .\merged; a custom -MergedDir only affects convert/quantize inputs.' -ForegroundColor Yellow}
# 1) Sanity-check paths; create $OutDir.$required = @($Python, $MergeScript, $ConvertScript, $Quantize)foreach ($p in $required) { if (-not (Test-Path $p)) { throw "Missing required file: $p" }}New-Item -ItemType Directory -Force -Path $OutFull | Out-NullWrite-Host "Project root : $ProjectRoot"Write-Host "Merged dir : $MergedFull"Write-Host "Output dir : $OutFull"
Push-Location $ProjectRoottry { # 2) Merge (idempotent: skip when merged\config.json already exists). $mergedConfig = Join-Path $MergedFull 'config.json' if (Test-Path $mergedConfig) { Write-Host 'Merged model found, skipping merge.' -ForegroundColor Green } elseif ($SkipMerge) { Write-Host 'ERROR: merged model not found.' -ForegroundColor Red Write-Host (" Expected: {0}" -f $mergedConfig) Write-Host ' Run the merge first (one of):' Write-Host ' powershell -NoProfile -File pipeline\make_gguf.ps1' Write-Host ' .venv\Scripts\python.exe pipeline\merge_local.py' exit 1 } else { Write-Host 'Merging LoRA into base (pipeline\merge_local.py) ...' & $Python $MergeScript if ($LASTEXITCODE -ne 0) { throw "merge_local.py failed with exit code $LASTEXITCODE." } if (-not (Test-Path $mergedConfig)) { throw "Merge finished but config.json still missing: $mergedConfig" } }
# 3) Convert merged HF dir -> f16 GGUF. $f16 = Join-Path $OutFull 'minicpm5-1b-toolcall-f16.gguf' $q8 = Join-Path $OutFull 'minicpm5-1b-toolcall-Q8_0.gguf' $q4 = Join-Path $OutFull 'minicpm5-1b-toolcall-Q4_K_M.gguf'
Write-Host 'Converting to f16 GGUF ...' & $Python $ConvertScript $MergedFull --outfile $f16 --outtype f16 if ($LASTEXITCODE -ne 0) { throw "convert_hf_to_gguf.py failed with exit code $LASTEXITCODE." }
# 4) Quantize. Write-Host 'Quantizing Q8_0 ...' & $Quantize $f16 $q8 Q8_0 if ($LASTEXITCODE -ne 0) { throw "llama-quantize Q8_0 failed with exit code $LASTEXITCODE." }
Write-Host 'Quantizing Q4_K_M ...' & $Quantize $f16 $q4 Q4_K_M if ($LASTEXITCODE -ne 0) { throw "llama-quantize Q4_K_M failed with exit code $LASTEXITCODE." }
# 5) Report outputs + sizes. Write-Host '' Write-Host 'GGUF outputs:' Get-ChildItem $OutFull -Filter '*.gguf' | Select-Object Name, @{ Name = 'SizeMB'; Expression = { '{0:N1}' -f ($_.Length / 1MB) } }, @{ Name = 'Bytes'; Expression = { $_.Length } } | Format-Table -AutoSize | Out-String | Write-Host}finally { Pop-Location}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386"""Build a 50-example adversarial hard set from data_native/test.jsonl.
Categories (10 each): nested_args, enum_args, multi_call, long_tools, abstention.Deterministic (seed 13). Output: data_native/hard_test.jsonlSchema per row: {"tools":[...], "messages":[...], "_category":..., "_source_i":...}"""import copyimport jsonimport randomfrom pathlib import Path
SEED = 13N_PER_CAT = 10SRC = Path(__file__).resolve().parent.parent / "data_native" / "test.jsonl"DST = Path(__file__).resolve().parent.parent / "data_native" / "hard_test.jsonl"
TYPE_ALIASES = { "dict": "dict", "object": "dict", "array": "array", "list": "array", "string": "string", "str": "string", "int": "int", "integer": "int", "float": "float", "number": "float", "boolean": "boolean", "bool": "boolean",}
def norm_type(t): if isinstance(t, list): return [TYPE_ALIASES.get(str(x).lower(), str(x).lower()) for x in t] return TYPE_ALIASES.get(str(t).lower(), str(t).lower())
def type_ok(value, declared): allowed = norm_type(declared) if isinstance(declared, list) else [norm_type(declared)] for a in allowed: if a == "string" and isinstance(value, str): return True if a == "int" and isinstance(value, int) and not isinstance(value, bool): return True if a == "float" and isinstance(value, (int, float)) and not isinstance(value, bool): return True if a == "boolean" and isinstance(value, bool): return True if a == "dict" and isinstance(value, dict): return True if a == "array" and isinstance(value, list): return True if a == "null" and value is None: return True return False
def synth_values_for_type(declared, current, rng): """Two synthetic values of the same JSON kind as current (deterministic).""" if isinstance(current, bool): return [not current] if isinstance(current, int) and not isinstance(current, bool): return [current + 1, current + 2] if isinstance(current, float): return [round(float(current) + 0.5, 3), round(float(current) + 1.5, 3)] if isinstance(current, str): cands = [current + "_alt", current + "_v2", "auto", "manual", "standard"] out = [] for c in cands: if c != current and c not in out: out.append(c) if len(out) == 2: break return out if isinstance(current, list): return [[], current + current[:1]] if isinstance(current, dict): return [{}, current] return ["alt1", "alt2"]
def find_tool(tools, name): for t in tools: if t.get("name") == name: return t return None
def assistant_msg(row): for m in row["messages"]: if m.get("role") == "assistant": return m return None
def user_msg(row): for m in row["messages"]: if m.get("role") == "user": return m return None
# ---------------- transforms ----------------def make_nested(row, rng): r = copy.deepcopy(row) am = assistant_msg(r) tc = am["tool_calls"][0] tool = find_tool(r["tools"], tc["name"]) params = tool.setdefault("parameters", {}) props = params.get("properties", {}) req = list(params.get("required", [])) orig_args = dict(tc.get("arguments", {}) or {}) # wrap all original props under a nested object "request" nested_props = copy.deepcopy(props) tool["parameters"] = { "type": "dict", "properties": { "request": { "description": "Nested object grouping all request arguments.", "type": "dict", "properties": nested_props, **({"required": req} if req else {}), } }, "required": ["request"], } tc["arguments"] = {"request": orig_args} # rewrite every call of this tool in the turn the same way for other in am["tool_calls"][1:]: if other["name"] == tc["name"]: other["arguments"] = {"request": dict(other.get("arguments", {}) or {})} um = user_msg(r) um["content"] = um["content"].rstrip() + ( " Provide all details inside the single 'request' object parameter " "of the '%s' tool." % tc["name"] ) return r
def make_enum(row, rng): r = copy.deepcopy(row) am = assistant_msg(r) tc = am["tool_calls"][0] tool = find_tool(r["tools"], tc["name"]) props = tool.get("parameters", {}).get("properties", {}) args = tc.get("arguments", {}) or {} # prefer a string-valued arg present in schema, else any arg key in schema prop_key = None for k, v in args.items(): if k in props and isinstance(v, str): prop_key = k break if prop_key is None: for k in args: if k in props: prop_key = k break if prop_key is None: # fallback: first schema property (add arg for it if missing? keep valid: use existing) prop_key = next(iter(props.keys())) cur = args.get(prop_key) if cur is None: # arg missing for that prop; pick first existing arg instead prop_key = next(iter(args.keys())) cur = args[prop_key] prop = props[prop_key] extra = synth_values_for_type(prop.get("type", "string"), cur, rng) enum_vals = [cur] + [e for e in extra if e != cur] # ensure uniqueness preserving order, take 3 seen, enum_vals2 = set(), [] for e in enum_vals: key = json.dumps(e, sort_keys=True, default=str) if key not in seen: seen.add(key) enum_vals2.append(e) prop["enum"] = enum_vals2[:3] if len(prop["enum"]) < 2: prop["enum"] = prop["enum"] + ["fallback_option"] um = user_msg(r) um["content"] = um["content"].rstrip() + ( " The '%s' parameter must be exactly one of: %s." % (prop_key, ", ".join(json.dumps(e, ensure_ascii=False) for e in prop["enum"])) ) return r
def make_multi(row, rng): r = copy.deepcopy(row) um = user_msg(r) if not um["content"].rstrip().endswith("Please make all requested calls in one turn."): um["content"] = um["content"].rstrip() + " Please make all requested calls in one turn." return r
def make_long_tools(row, rng): r = copy.deepcopy(row) existing = {t.get("name") for t in r["tools"]} calls = {c["name"] for c in (assistant_msg(r).get("tool_calls") or [])} base_pool = [t for t in r["tools"]] # build distractors from clones with similar names i = 0 suffixes = ["Plus", "Pro", "v2", "Extended", "Helper", "Util", "V2", "Advanced", "Lite", "X"] while len(r["tools"]) < 20: src = base_pool[i % len(base_pool)] sfx = suffixes[(i // max(len(base_pool), 1)) % len(suffixes)] cand = "%s %s %d" % (src.get("name"), sfx, i) i += 1 if cand in existing: continue d = copy.deepcopy(src) d["name"] = cand r["tools"].append(d) existing.add(cand) if i > 500: break # shuffle distractors but keep target call valid (order irrelevant); deterministic targets = calls fixed = [t for t in r["tools"] if t.get("name") in targets] rest = [t for t in r["tools"] if t.get("name") not in targets] rng.shuffle(rest) # interleave: keep at least one target not at position 0 to force retrieval r["tools"] = rest[:10] + fixed + rest[10:] assert len(r["tools"]) == 20 return r
# ---------------- validation ----------------def validate_row(row): errs = [] tools = row.get("tools", []) names = {t.get("name") for t in tools} seen_prompts = None # checked globally for m in row.get("messages", []): if m.get("role") == "assistant" and m.get("tool_calls"): for tc in m["tool_calls"]: if tc.get("name") not in names: errs.append("call name %r not in tools" % tc.get("name")) continue tool = find_tool(tools, tc["name"]) params = tool.get("parameters", {}) if isinstance(tool, dict) else {} # nested_args rows: required lives on outer + inner; check outer only here, # deep check below handles nested required req = params.get("required", []) or [] args = tc.get("arguments", {}) or {} for rk in req: if rk not in args: errs.append("missing required arg %r for %s" % (rk, tc["name"])) props = params.get("properties", {}) or {} for k, v in args.items(): if k in props and isinstance(props[k], dict) and "type" in props[k]: ptype = props[k]["type"] if ptype in ("dict", "object") and isinstance(v, dict) and "properties" in props[k]: # deep-check nested object sub_props = props[k].get("properties", {}) or {} sub_req = props[k].get("required", []) or [] for rk in sub_req: if rk not in v: errs.append("missing nested required %r for %s" % (rk, tc["name"])) for sk, sv in v.items(): if sk in sub_props and isinstance(sub_props[sk], dict) and "type" in sub_props[sk]: if not type_ok(sv, sub_props[sk]["type"]): errs.append("type mismatch nested %r" % sk) if "enum" in sub_props[sk] and sv not in sub_props[sk]["enum"]: errs.append("enum violation nested %r" % sk) else: if not type_ok(v, ptype): errs.append("type mismatch %r: %r vs %s" % (k, v, ptype)) if "enum" in props[k] and v not in props[k]["enum"]: errs.append("enum violation %r" % k) return errs
def main(): rng = random.Random(SEED) rows = [json.loads(l) for l in SRC.open(encoding="utf-8")] pos_idx = [i for i, r in enumerate(rows) if assistant_msg(r).get("tool_calls")] abst_idx = [i for i, r in enumerate(rows) if not assistant_msg(r).get("tool_calls")]
def target_tool_of(i): r = rows[i] am = assistant_msg(r) tcs = am.get("tool_calls") or [] if not tcs: return None, None t = find_tool(r["tools"], tcs[0]["name"]) return t, tcs[0]
nested_pool = [i for i in pos_idx if (lambda x: x[0] is not None and (x[1].get("arguments")) and x[0].get("parameters", {}).get("properties"))(target_tool_of(i))] enum_pool = [i for i in pos_idx if (lambda x: x[0] is not None and (x[1].get("arguments")) and any(k in x[0].get("parameters", {}).get("properties", {}) for k in (x[1].get("arguments") or {})))(target_tool_of(i))] multi_pool = [i for i in pos_idx if 2 <= len(assistant_msg(rows[i]).get("tool_calls") or []) <= 3] long_pool = [i for i in pos_idx if len(rows[i]["tools"]) < 20]
for name, pool in [("nested", nested_pool), ("enum", enum_pool), ("multi", multi_pool), ("long", long_pool)]: print("%s candidates: %d" % (name, len(pool))) print("abstention candidates: %d" % len(abst_idx)) assert len(nested_pool) >= 10 and len(enum_pool) >= 10 and len(multi_pool) >= 10 and len(abst_idx) >= 10
rng.shuffle(nested_pool) rng.shuffle(enum_pool) rng.shuffle(multi_pool) rng.shuffle(long_pool) rng.shuffle(abst_idx)
used = set() out = []
def take(pool, n): sel = [] for i in pool: if i not in used: sel.append(i) if len(sel) == n: break assert len(sel) == n, "pool exhausted" used.update(sel) return sel
for i in take(nested_pool, N_PER_CAT): r = make_nested(rows[i], rng) r["_category"] = "nested_args" r["_source_i"] = i out.append(r) for i in take(enum_pool, N_PER_CAT): r = make_enum(rows[i], rng) r["_category"] = "enum_args" r["_source_i"] = i out.append(r) for i in take(multi_pool, N_PER_CAT): r = make_multi(rows[i], rng) r["_category"] = "multi_call" r["_source_i"] = i out.append(r) for i in take(long_pool, N_PER_CAT): r = make_long_tools(rows[i], rng) r["_category"] = "long_tools" r["_source_i"] = i out.append(r) for i in take(abst_idx, N_PER_CAT): r = copy.deepcopy(rows[i]) r["_category"] = "abstention" r["_source_i"] = i out.append(r)
assert len(out) == 50 # dedupe prompts seen = set() for r in out: p = user_msg(r)["content"] if p in seen: k = 1 while ("%s [variant %d]" % (p, k)) in seen: k += 1 p = "%s [variant %d]" % (p, k) user_msg(r)["content"] = p seen.add(p) assert len(seen) == 50, "duplicate prompts remain"
# validate from collections import Counter cat_counts = Counter(r["_category"] for r in out) n_pass, failures = 0, [] for r in out: errs = validate_row(r) if errs: failures.append((r["_category"], r["_source_i"], errs)) else: n_pass += 1 # global dup check assert len({user_msg(r)["content"] for r in out}) == 50
DST.parent.mkdir(parents=True, exist_ok=True) with DST.open("w", encoding="utf-8") as f: for r in out: f.write(json.dumps(r, ensure_ascii=False) + "\n")
print("wrote %s (%d rows)" % (DST, len(out))) print("category counts:", dict(cat_counts)) print("schema-validation pass: %d/%d" % (n_pass, len(out))) if failures: print("FAILURES:") for c, i, e in failures[:10]: print(" ", c, i, e) else: print("all rows valid; no duplicate prompts") # 2 example prompts for r in out[:2]: print("--- [%s src=%s] %s" % (r["_category"], r["_source_i"], user_msg(r)["content"][:220]))
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728"""Build an abstention-heavy training file by repeating no-tool examples.
The base run under-called abstention (0.71 vs the 0.90 gate), so v4 trains onevery call example once and every abstention example three times."""import jsonimport randomfrom pathlib import Path
SRC = Path("data_native/train.jsonl")OUT = Path("data_native/train_neg3x.jsonl")REPEAT = 3SEED = 21
def is_negative(row): last = row["messages"][-1] return last.get("role") == "assistant" and not last.get("tool_calls")
rows = [json.loads(l) for l in SRC.read_text(encoding="utf-8").splitlines() if l.strip()]pos = [r for r in rows if not is_negative(r)]neg = [r for r in rows if is_negative(r)]out = pos + neg * REPEATrandom.Random(SEED).shuffle(out)OUT.write_text("\n".join(json.dumps(r, ensure_ascii=False) for r in out) + "\n", encoding="utf-8")print(f"pos={len(pos)} neg={len(neg)} repeat={REPEAT} total={len(out)} -> {OUT}")print(f"abstention share={(len(neg) * REPEAT) / len(out):.1%}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501"""Shared scoring library for MiniCPM tool-call evaluation.
Stdlib only. Other agents import this module; the public API is:
parse_calls(text) -> list[dict] normalize_value(v) -> Any canon_call(call) -> tuple canon_calls(calls) -> list[tuple] categorize(row) -> str failure_bucket(expected, predicted, raw) -> str
Call-dict shape (produced by parse_calls, consumed by canon_call): {"name": <tool name str>, "arguments": {<arg str>: <value>}}"""
import astimport htmlimport jsonimport refrom collections import Counter
# ---------------------------------------------------------------------------# parse_calls# ---------------------------------------------------------------------------
_FUNCTION_RE = re.compile( r"<\s*(?:function|tool_call)\s+name\s*=\s*(?:\"([^\"]+)\"|'([^']+)'|([^\s>]+))\s*>(.*?)<\s*/\s*(?:function|tool_call)\s*>", re.DOTALL | re.IGNORECASE,)_PARAM_RE = re.compile( r"<\s*param\s+name\s*=\s*(?:\"([^\"]+)\"|'([^']+)'|([^\s>]+))\s*>(.*?)<\s*/\s*param\s*>", re.DOTALL | re.IGNORECASE,)_CDATA_RE = re.compile(r"<!\[CDATA\[(.*?)\]\]>", re.DOTALL)
def _unwrap_value(raw_value): """Strip CDATA wrappers and unescape HTML entities.""" text = _CDATA_RE.sub(lambda m: m.group(1), raw_value) text = html.unescape(text) return text.strip()
def _coerce_args(args): """Return args as a dict. JSON strings that decode to dicts are unpacked.""" if args is None: return {} if isinstance(args, dict): return dict(args) if isinstance(args, str): s = args.strip() if not s: return {} try: parsed = json.loads(s) if isinstance(parsed, dict): return parsed except Exception: pass try: parsed = ast.literal_eval(s) if isinstance(parsed, dict): return parsed except Exception: pass return {"value": args} return {"value": args}
def _normalize_json_call(item): """Normalize one JSON call object to {"name":..., "arguments": {...}}.
Accepts {"name", "arguments"|"parameters"|"args"|"input"} shapes as well as OpenAI-style {"function": {"name":..., "arguments":...}} wrappers. Returns None when no usable name is present. """ if not isinstance(item, dict): return None if isinstance(item.get("function"), dict): func = item["function"] name = func.get("name", item.get("name")) args = func.get("arguments", func.get("parameters", item.get("arguments", {}))) else: name = item.get("name") args = item.get("arguments", item.get("parameters", item.get("args", item.get("input", {})))) # Some producers nest single-call payloads as {"type":"function","function":{...}} if name is None and isinstance(item.get("function"), str): return None if not isinstance(name, str) or not name.strip(): return None return {"name": name.strip(), "arguments": _coerce_args(args)}
def _parse_json_calls(text): """Try to interpret text as JSON holding tool calls. Returns None if N/A.""" s = text.strip() if not s: return None data = None try: data = json.loads(s) except Exception: # Fall back: try decoding the first JSON object/array embedded in prose # (e.g. code-fenced ```json blocks or explanatory prefixes). start = None for i, ch in enumerate(s): if ch in "{[": start = i break if start is None: return None decoder = json.JSONDecoder() try: data, _ = decoder.raw_decode(s[start:]) except Exception: return None if isinstance(data, list): calls = [] for item in data: if isinstance(item, str): try: item = json.loads(item) except Exception: continue call = _normalize_json_call(item) if call is not None: calls.append(call) return calls if isinstance(data, dict): for key in ("tool_calls", "function_calls", "calls"): if isinstance(data.get(key), list): calls = [] for item in data[key]: call = _normalize_json_call(item) if call is not None: calls.append(call) return calls # OpenAI assistant-message shape: {"role":..., "tool_calls":[{"function":{...}}]} # is covered above; a bare single call {"name":...} is covered here. call = _normalize_json_call(data) if call is not None: return [call] return None return None
def parse_calls(text: str) -> list[dict]: """Parse MiniCPM XML tool calls out of raw model output.
XML form (one or more, params may span lines, values may be CDATA)::
<function name="get_weather"><param name="city">Paris</param></function>
Also accepts a JSON array of call objects, or a JSON object holding ``tool_calls`` (OpenAI assistant-message style included), or a single ``{"name": ..., "arguments": {...}}`` object. ``arguments`` given as an encoded JSON string is decoded. ``<tool_call name=...>`` tags are accepted as an alias of ``<function>``.
Returns a list of ``{"name": str, "arguments": dict}``; argument values stay as strings in the XML path (use :func:`normalize_value` / typed comparison downstream). Returns ``[]`` when nothing is found. """ if text is None: return [] if not isinstance(text, str): text = str(text) if not text.strip(): return []
calls = [] for match in _FUNCTION_RE.finditer(text): name = match.group(1) or match.group(2) or match.group(3) or "" body = match.group(4) or "" args = {} for pmatch in _PARAM_RE.finditer(body): key = pmatch.group(1) or pmatch.group(2) or pmatch.group(3) or "" args[key.strip()] = _unwrap_value(pmatch.group(4) or "") calls.append({"name": name.strip(), "arguments": args}) if calls: return calls
json_calls = _parse_json_calls(text) if json_calls: return json_calls return []
# ---------------------------------------------------------------------------# normalize_value / canon_call / canon_calls# ---------------------------------------------------------------------------
def normalize_value(v): """Map a value to a hashable ``(tag, normalised)`` pair.
- bool -> ``("bool", bool(v))`` (checked before int: bool is an int subclass) - int/float -> ``("num", float(v))`` - list/tuple -> ``("list", tuple(normalize_value(x) ...))`` - dict -> ``("dict", tuple(sorted((k, normalize_value(x)) ...)))`` - None -> ``("none", None)`` - str -> the string is stripped, then tried in order: ``json.loads``, ``ast.literal_eval``, case-insensitive ``true``/``false``/``null`` (plus ``none``/``nil``) handling; otherwise ``("str", stripped)``. Decoded results are normalised recursively, so ``"1"``, ``1`` and ``"1.0"`` all become ``("num", 1.0)`` and ``"true"``/``"True"``/``True`` all become ``("bool", True)``. - anything else -> ``("str", str(v).strip())``. """ if isinstance(v, bool): return ("bool", bool(v)) if isinstance(v, (int, float)): return ("num", float(v)) if isinstance(v, (list, tuple)): return ("list", tuple(normalize_value(x) for x in v)) if isinstance(v, dict): return ("dict", tuple(sorted( ((k, normalize_value(x)) for k, x in v.items()), key=lambda kv: str(kv[0]), ))) if v is None: return ("none", None) if isinstance(v, str): s = v.strip() try: parsed = json.loads(s) if not (isinstance(parsed, str) and parsed == s): return normalize_value(parsed) except Exception: pass try: parsed = ast.literal_eval(s) if not (isinstance(parsed, str) and parsed == s): return normalize_value(parsed) except Exception: pass low = s.lower() if low == "true": return ("bool", True) if low == "false": return ("bool", False) if low in ("null", "none", "nil"): return ("none", None) return ("str", s) return ("str", str(v).strip())
def canon_call(call: dict) -> tuple: """Canonical form: ``(name, tuple(sorted((key, normalize_value(val)))))``.
Accepts ``arguments`` under the aliases ``parameters``/``args``/``input``; a JSON-encoded string there is decoded first. The name is stripped. """ if not isinstance(call, dict): return ("", ()) name = call.get("name", "") name = name.strip() if isinstance(name, str) else str(name) args = call.get("arguments", call.get("parameters", call.get("args", call.get("input", {})))) args = _coerce_args(args) items = tuple(sorted( ((k, normalize_value(val)) for k, val in args.items()), key=lambda kv: str(kv[0]), )) return (name, items)
def canon_calls(calls: list) -> list: """Return ``sorted([canon_call(c) for c in calls])`` (``[]`` for empty).""" if not calls: return [] canon = [canon_call(c) for c in calls] try: return sorted(canon) except TypeError: return sorted(canon, key=repr)
# ---------------------------------------------------------------------------# categorize# ---------------------------------------------------------------------------
def _assistant_messages(messages): return [m for m in messages if isinstance(m, dict) and m.get("role") == "assistant"]
def _message_tool_calls(message): """Return the tool_calls list of a message (OpenAI + flat shapes).""" tc = message.get("tool_calls", []) if tc is None: return [] if isinstance(tc, dict): tc = [tc] return list(tc) if isinstance(tc, list) else []
def _call_arguments(call): if not isinstance(call, dict): return {} func = call.get("function") if isinstance(func, dict): args = func.get("arguments", func.get("parameters", {})) else: args = call.get("arguments", call.get("parameters", call.get("args", call.get("input", {})))) return _coerce_args(args)
def _schema_properties(tool): """Extract the {prop: schema} mapping from a tool definition, or {}.""" if not isinstance(tool, dict): return {} node = tool.get("function", tool) if isinstance(tool.get("function"), dict) else tool for key in ("parameters", "input_schema", "inputSchema", "schema"): params = node.get(key, None) if isinstance(params, dict): props = params.get("properties", params if "properties" not in params else None) if isinstance(props, dict): return props return {}
def categorize(row: dict) -> str: """Bucket a dataset row by structural difficulty.
Priority (first hit wins): ``abstention`` > ``multi_call`` > ``nested_args`` > ``enum_args`` > ``long_tools`` > ``single_call``.
- ``abstention``: the last assistant message has no ``tool_calls`` (also when there is no assistant message at all). - ``multi_call``: the last assistant message holds > 1 ``tool_calls``. - ``nested_args``: any property schema in any tool has ``type`` ``object``/``array``, or any actual argument value in any assistant message's tool calls is a dict/list (JSON-encoded strings that decode to dict/list count too). - ``enum_args``: any property schema in any tool defines ``enum``. - ``long_tools``: ``len(tools) >= 10``. - ``single_call``: none of the above. """ tools = row.get("tools", []) or [] messages = row.get("messages", []) or []
assistants = _assistant_messages(messages) target = assistants[-1] if assistants else None target_calls = _message_tool_calls(target) if target is not None else []
if not target_calls: return "abstention" if len(target_calls) > 1: return "multi_call"
nested_schema = False enum_schema = False for tool in tools: for prop_schema in _schema_properties(tool).values(): if not isinstance(prop_schema, dict): continue if prop_schema.get("type") in ("object", "array"): nested_schema = True if "enum" in prop_schema: enum_schema = True
nested_values = False for message in assistants: for call in _message_tool_calls(message): for val in _call_arguments(call).values(): if isinstance(val, (dict, list)): nested_values = True elif isinstance(val, str): s = val.strip() if s[:1] in "{[": try: if isinstance(json.loads(s), (dict, list)): nested_values = True except Exception: pass
if nested_schema or nested_values: return "nested_args" if enum_schema: return "enum_args" if len(tools) >= 10: return "long_tools" return "single_call"
# ---------------------------------------------------------------------------# failure_bucket# ---------------------------------------------------------------------------
def _name_counter(calls): names = [] for call in calls or []: if isinstance(call, dict): name = call.get("name", "") names.append(name.strip() if isinstance(name, str) else str(name)) return Counter(names)
def _is_strict_sub(a: Counter, b: Counter) -> bool: """True when multiset a is a strict sub-multiset of b.""" if a == b: return False for key, count in a.items(): if b.get(key, 0) < count: return False return any(b.get(key, 0) > a.get(key, 0) for key in set(a) | set(b))
def _str_norm(v) -> str: if isinstance(v, str): return v.strip().lower() if isinstance(v, bool): return str(v).lower() if v is None: return "null" return str(v).strip().lower()
def _value_typing_match(expected, predicted) -> bool: """Names (as multisets) and per-call arg keys match, typed canon differs, but every paired value agrees under case-insensitive str-normalization.""" exp_canon = canon_calls(expected) pred_canon = canon_calls(predicted) if exp_canon == pred_canon: return False exp_by_name = sorted(((c[0], c[1]) for c in exp_canon), key=repr) pred_by_name = sorted(((c[0], c[1]) for c in pred_canon), key=repr) if [n for n, _ in exp_by_name] != [n for n, _ in pred_by_name]: return False # Compare raw values pairwise (sorted-by-name order aligns duplicates). exp_raw = sorted((canon_call(c) for c in (expected or [])), key=repr) pred_raw = sorted((canon_call(c) for c in (predicted or [])), key=repr) exp_args = [dict((k, v) for k, v in items) for _, items in exp_by_name] _ = (exp_raw, pred_raw) # pairing is by sorted canon order; raw order unused exp_calls = sorted(expected or [], key=lambda c: repr(c.get("name", ""))) pred_calls = sorted(predicted or [], key=lambda c: repr(c.get("name", ""))) for e_call, p_call in zip(exp_calls, pred_calls): e_args = _coerce_args( e_call.get("arguments", e_call.get("parameters", e_call.get("args", e_call.get("input", {})))) if isinstance(e_call, dict) else {} ) p_args = _coerce_args( p_call.get("arguments", p_call.get("parameters", p_call.get("args", p_call.get("input", {})))) if isinstance(p_call, dict) else {} ) if set(e_args) != set(p_args): return False for key in e_args: if _str_norm(e_args[key]) != _str_norm(p_args[key]): return False return True
def failure_bucket(expected: list, predicted: list, raw: str) -> str: """Classify one prediction. Check order (first hit wins):
1. ``ok`` -- canonically equal (``canon_calls`` equal; includes both empty). 2. ``unparsed`` -- not ok, ``predicted`` empty, and ``raw`` contains ``"<function"`` or ``"tool_call"`` (evidence of an attempted call). 3. ``no_call`` -- ``expected`` non-empty, ``predicted`` empty. 4. ``spurious_call`` -- ``expected`` empty, ``predicted`` non-empty. 5. ``wrong_tool`` -- name multisets differ with neither a strict sub-/super-multiset of the other (disjoint or partially overlapping). 6. ``missing_call`` -- predicted names are a strict sub-multiset. 7. ``extra_call`` -- predicted names are a strict super-multiset. 8. ``value_typing`` -- names and per-call arg keys match, typed canon differs, but all values agree under case-insensitive str-normalization (narrower sub-case of arg_mismatch, so checked first). 9. ``arg_mismatch`` -- anything else with matching names but differing args.
Note on steps 5-7 and 8-9: the spec lists ``wrong_tool`` before the subset cases and ``arg_mismatch`` before ``value_typing``, but both pairs are general-then-narrow, so the narrow case is evaluated first within its pair; otherwise ``missing_call``/``extra_call``/``value_typing`` would be unreachable. Multiset (Counter) semantics reduce to set semantics when no tool name repeats. """ exp = list(expected or []) pred = list(predicted or []) raw_text = raw if isinstance(raw, str) else ("" if raw is None else str(raw))
if canon_calls(exp) == canon_calls(pred): return "ok" if not pred and ("<function" in raw_text or "tool_call" in raw_text): return "unparsed" if exp and not pred: return "no_call" if not exp and pred: return "spurious_call"
exp_names = _name_counter(exp) pred_names = _name_counter(pred) if exp_names != pred_names: if _is_strict_sub(pred_names, exp_names): return "missing_call" if _is_strict_sub(exp_names, pred_names): return "extra_call" return "wrong_tool"
if _value_typing_match(exp, pred): return "value_typing" return "arg_mismatch"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588"""A/B runtime comparison of two OpenAI-compatible endpoints on the same prompts.
Runs pipeline/eval_openai.py once per endpoint (via its ``evaluate`` functionwhen importable, otherwise as a subprocess) and compares the two result sets.
Usage: python pipeline/runtime_ab.py ^ --base-url-a http://127.0.0.1:8080/v1 --label-a "base Q8_0" ^ --base-url-b http://127.0.0.1:8081/v1 --label-b "tuned Q8_0" ^ --data data_native/test.jsonl --limit 100 --out reports/runtime_ab
Outputs: <out>.md two-column metrics table (A vs B), per-category deltas, per-prompt agreement rate, disagreement count, mean latency + tok/s from usage. <out>.json the same numbers in raw form.
Assumes pipeline/eval_openai.py and pipeline/metrics_lib.py exist(this script is not responsible for creating them)."""
import argparseimport importlib.utilimport inspectimport jsonimport subprocessimport sysimport tempfilefrom pathlib import Path
HERE = Path(__file__).resolve().parentEVAL_SCRIPT = HERE / "eval_openai.py"
try: import requestsexcept ImportError: # pragma: no cover requests = None
# ---------------------------------------------------------------- health check
def check_endpoint(base_url, label): """Return (ok, detail). Never raises: unreachable -> (False, reason).""" url = base_url.rstrip("/") + "/models" if requests is None: return False, "the 'requests' package is not installed" try: r = requests.get(url, timeout=10) if r.status_code < 500: return True, f"HTTP {r.status_code}" return False, f"HTTP {r.status_code}: {r.text[:200]}" except Exception as e: # connection refused, timeout, DNS, ... return False, f"{type(e).__name__}: {e}"
def start_hint(base_url): try: from urllib.parse import urlparse port = urlparse(base_url).port or 8080 except Exception: port = 8080 return ( f"llama-server -m <model.gguf> --port {port} " f"--jinja -c 2048 -ngl 0 # or: .\\pipeline\\start_servers.ps1" )
def fail_unreachable(problems): print("ERROR: one or more endpoints are unreachable.\n", file=sys.stderr) for label, base_url, detail in problems: print(f" [{label}] {base_url}\n reason: {detail}", file=sys.stderr) print(f" start it, e.g.: {start_hint(base_url)}\n", file=sys.stderr) print( "Fix the endpoints above, then re-run the same runtime_ab.py command.", file=sys.stderr, ) sys.exit(2)
# --------------------------------------------------------------- run one side
def _try_import_evaluate(): """Return the evaluate callable from eval_openai.py, or None.""" if not EVAL_SCRIPT.exists(): return None try: spec = importlib.util.spec_from_file_location("eval_openai_mod", EVAL_SCRIPT) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) except Exception: return None for name in ("evaluate", "run_eval", "main"): fn = getattr(mod, name, None) if callable(fn): return fn return None
def _call_imported_evaluate(fn, base_url, model, data, limit, out_dir): """Call evaluate() with whatever kwargs it accepts. Returns its result.""" sig = inspect.signature(fn) kwargs = {} candidates = { "base_url": base_url, "baseurl": base_url, "url": base_url, "model": model, "model_name": model, "data": data, "data_path": data, "limit": limit, "max_n": limit, "n": limit, "out": str(out_dir), "out_dir": str(out_dir), "outdir": str(out_dir), "output_dir": str(out_dir), } params = sig.parameters accepts_kwargs = any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values()) for pname, p in params.items(): for key, val in candidates.items(): if pname == key or (accepts_kwargs and pname in candidates): kwargs[pname] = val break # fill the obvious positional slots if the signature is positional-only args = [] if not kwargs and params: vals = [base_url, model, str(data), limit, str(out_dir)] for i, pname in enumerate(params): if i < len(vals): args.append(vals[i]) if args: return fn(*args) return fn(**kwargs)
def run_eval_side(base_url, label, model, data, limit, tmp_root, timeout_s): """Evaluate one endpoint. Returns the output directory Path.
Prefers the imported evaluate() function; falls back to a subprocess call of pipeline/eval_openai.py. """ out_dir = tmp_root / ("eval_" + "".join(c if c.isalnum() else "_" for c in label)) out_dir.mkdir(parents=True, exist_ok=True)
fn = _try_import_evaluate() if fn is not None and fn.__name__ != "main": try: _call_imported_evaluate(fn, base_url, model, data, limit, out_dir) return out_dir except SystemExit as e: # evaluate() called sys.exit on its own if e.code not in (None, 0): raise RuntimeError(f"evaluate() for [{label}] exited with {e.code}") return out_dir except Exception as e: print( f"WARN: imported evaluate() failed for [{label}] ({e}); " "falling back to subprocess.", file=sys.stderr, )
if not EVAL_SCRIPT.exists(): raise RuntimeError( f"Cannot evaluate [{label}]: pipeline/eval_openai.py not found " "and no usable evaluate() import. " "(runtime_ab.py assumes pipeline/eval_openai.py exists.)" ) cmd = [ sys.executable, str(EVAL_SCRIPT), "--base-url", base_url, "--model", model, "--data", str(data), "--limit", str(limit), "--out", str(out_dir), ] try: subprocess.run(cmd, check=True, timeout=timeout_s) except subprocess.CalledProcessError as e: raise RuntimeError( f"eval_openai.py subprocess for [{label}] failed " f"(exit {e.returncode}). Command: {' '.join(cmd)}" ) return out_dir
# --------------------------------------------------------------- load results
def _load_json(path): try: with open(path, encoding="utf-8") as f: return json.load(f) except Exception: return None
def find_metrics(out_dir): """Find the metrics dict produced by eval_openai.py (best effort).""" for name in ("metrics.json", "summary.json", "results.json", "eval.json"): d = _load_json(out_dir / name) if isinstance(d, dict): # unwrap common envelopes: {"metrics": {...}}, {"summary": {...}} for key in ("metrics", "summary", "scores", "results"): if isinstance(d.get(key), dict) and d.get(key): inner = d[key] if any(isinstance(v, (int, float)) for v in inner.values()): return inner if any(isinstance(v, (int, float)) for v in d.values()): return d for p in sorted(out_dir.glob("*.json")): d = _load_json(p) if isinstance(d, dict) and any(isinstance(v, (int, float)) for v in d.values()): return d return {}
def find_predictions(out_dir): """Find per-prompt records (list of dicts), best effort.""" for name in ("predictions.jsonl", "outputs.jsonl", "results.jsonl", "preds.jsonl", "completions.jsonl"): p = out_dir / name if p.exists(): rows = [] with open(p, encoding="utf-8") as f: for line in f: line = line.strip() if line: try: rows.append(json.loads(line)) except Exception: pass if rows: return rows for p in sorted(out_dir.glob("*.jsonl")): rows = [] with open(p, encoding="utf-8") as f: for line in f: line = line.strip() if line: try: rows.append(json.loads(line)) except Exception: pass if rows and isinstance(rows[0], dict): return rows for p in sorted(out_dir.glob("*.json")): d = _load_json(p) if isinstance(d, list) and d and isinstance(d[0], dict): return d if isinstance(d, dict): for key in ("predictions", "outputs", "rows", "data", "items"): v = d.get(key) if isinstance(v, list) and v and isinstance(v[0], dict): return v return []
def norm_output(rec): for key in ("output", "prediction", "completion", "text", "response", "pred"): v = rec.get(key) if isinstance(v, str) and v.strip(): return v.strip() if v is not None and not isinstance(v, str): return json.dumps(v, sort_keys=True, ensure_ascii=False) # OpenAI-style message envelope msg = rec.get("message") if isinstance(msg, dict): tc = msg.get("tool_calls") if tc: return json.dumps(tc, sort_keys=True, ensure_ascii=False) c = msg.get("content") if isinstance(c, str): return c.strip() tc = rec.get("tool_calls") if tc: return json.dumps(tc, sort_keys=True, ensure_ascii=False) return ""
def rec_latency(rec): for key in ("latency_s", "latency", "elapsed_s", "elapsed", "duration_s", "request_time_s"): v = rec.get(key) if isinstance(v, (int, float)): return float(v) return None
def rec_completion_tokens(rec): u = rec.get("usage") if isinstance(u, dict): for key in ("completion_tokens", "output_tokens", "generated_tokens"): v = u.get(key) if isinstance(v, (int, float)): return float(v) for key in ("completion_tokens", "output_tokens", "num_tokens"): v = rec.get(key) if isinstance(v, (int, float)): return float(v) return None
def rec_score(rec): for key in ("score", "correct", "exact_match", "passed", "ok", "accuracy"): v = rec.get(key) if isinstance(v, bool): return float(v) if isinstance(v, (int, float)): return float(v) return None
def rec_category(rec, i): for key in ("category", "split", "task", "domain", "dataset"): v = rec.get(key) if v: return str(v) return "all"
def mean(xs): xs = [x for x in xs if x is not None] return sum(xs) / len(xs) if xs else None
def fmt(x, digits=4): if x is None: return "n/a" if isinstance(x, float): return f"{x:.{digits}f}" return str(x)
def fmt_delta(d, digits=4): if d is None: return "n/a" sign = "+" if d >= 0 else "" return f"{sign}{d:.{digits}f}"
# ------------------------------------------------------------------- main
def parse_args(argv=None): p = argparse.ArgumentParser( description="Compare two OpenAI-compatible endpoints on the same prompts.") p.add_argument("--base-url-a", required=True, help="Base URL of endpoint A, e.g. http://127.0.0.1:8080/v1") p.add_argument("--label-a", default="A", help="Display label for A") p.add_argument("--base-url-b", required=True, help="Base URL of endpoint B, e.g. http://127.0.0.1:8081/v1") p.add_argument("--label-b", default="B", help="Display label for B") p.add_argument("--data", default="data_native/test.jsonl", help="Prompt file evaluated by eval_openai.py") p.add_argument("--limit", type=int, default=100, help="Max prompts per endpoint (default: 100)") p.add_argument("--model", default="local", help="Model name sent to the servers (default: local)") p.add_argument("--out", default="reports/runtime_ab", help="Output prefix; writes <out>.md and <out>.json") p.add_argument("--timeout", type=int, default=600, help="Per-endpoint eval timeout in seconds (subprocess mode)") return p.parse_args(argv)
def main(argv=None): args = parse_args(argv)
# 1) Reachability first: clean error, no traceback. problems = [] for label, url in ((args.label_a, args.base_url_a), (args.label_b, args.base_url_b)): ok, detail = check_endpoint(url, label) print(f"[{label}] {url} -> {'OK' if ok else 'UNREACHABLE'} ({detail})", flush=True) if not ok: problems.append((label, url, detail)) if problems: fail_unreachable(problems)
# 2) Evaluate each side into a temp dir. with tempfile.TemporaryDirectory(prefix="runtime_ab_") as tmp: tmp_root = Path(tmp) try: dir_a = run_eval_side(args.base_url_a, args.label_a, args.model, args.data, args.limit, tmp_root, args.timeout) dir_b = run_eval_side(args.base_url_b, args.label_b, args.model, args.data, args.limit, tmp_root, args.timeout) except RuntimeError as e: print(f"ERROR: {e}", file=sys.stderr) sys.exit(3)
metrics_a, metrics_b = find_metrics(dir_a), find_metrics(dir_b) preds_a, preds_b = find_predictions(dir_a), find_predictions(dir_b)
# 3) Aggregate comparison. n = max(len(preds_a), len(preds_b)) if not n: # eval produced metrics but no per-prompt file; still report metrics n = args.limit
lat_a = [rec_latency(r) for r in preds_a] lat_b = [rec_latency(r) for r in preds_b] tok_a = [rec_completion_tokens(r) for r in preds_a] tok_b = [rec_completion_tokens(r) for r in preds_b] tps_a = [t / l for t, l in zip(tok_a, lat_a) if t is not None and l not in (None, 0)] tps_b = [t / l for t, l in zip(tok_b, lat_b) if t is not None and l not in (None, 0)] mean_lat_a, mean_lat_b = mean(lat_a), mean(lat_b) mean_tps_a, mean_tps_b = mean(tps_a), mean(tps_b)
# Per-prompt agreement (pair by index; ids when available). def rec_id(rec, i): for key in ("id", "prompt_id", "idx", "index"): if rec.get(key) is not None: return str(rec[key]) return f"prompt_{i}"
m = min(len(preds_a), len(preds_b)) agree, disagreements = 0, [] for i in range(m): oa, ob = norm_output(preds_a[i]), norm_output(preds_b[i]) if oa == ob: agree += 1 else: disagreements.append(rec_id(preds_a[i], i)) agreement_rate = (agree / m) if m else None
# Per-category score deltas (uses per-prompt scores when the eval # records them; otherwise falls back to n/agreement per category). cats = {} for i in range(m): c = rec_category(preds_a[i], i) sa, sb = rec_score(preds_a[i]), rec_score(preds_b[i]) cats.setdefault(c, {"n": 0, "sa": [], "sb": [], "agree": 0, "total": 0}) cats[c]["n"] += 1 cats[c]["total"] += 1 if norm_output(preds_a[i]) == norm_output(preds_b[i]): cats[c]["agree"] += 1 if sa is not None: cats[c]["sa"].append(sa) if sb is not None: cats[c]["sb"].append(sb) have_scores = any(c["sa"] or c["sb"] for c in cats.values())
# Metrics union table (numeric entries from each metrics.json). metric_keys = [k for k in metrics_a.keys() | metrics_b.keys()] metric_keys.sort() rows = [] for k in metric_keys: va, vb = metrics_a.get(k), metrics_b.get(k) if isinstance(va, (int, float)) and isinstance(vb, (int, float)): d = vb - va else: d = None rows.append((k, va, vb, d))
result = { "label_a": args.label_a, "label_b": args.label_b, "base_url_a": args.base_url_a, "base_url_b": args.base_url_b, "model": args.model, "data": str(args.data), "limit": args.limit, "n_compared": m, "n_a": len(preds_a), "n_b": len(preds_b), "metrics_a": metrics_a, "metrics_b": metrics_b, "metric_deltas_b_minus_a": { k: d for k, _, _, d in rows if d is not None }, "agreement_rate": agreement_rate, "agreement_count": agree, "disagreement_count": len(disagreements), "disagreement_ids": disagreements[:50], "mean_latency_s": {"a": mean_lat_a, "b": mean_lat_b}, "mean_tok_per_s": {"a": mean_tps_a, "b": mean_tps_b}, "per_category": { c: { "n": v["n"], "mean_score_a": mean(v["sa"]), "mean_score_b": mean(v["sb"]), "delta_b_minus_a": ( (mean(v["sb"]) - mean(v["sa"])) if v["sa"] and v["sb"] else None ), "agreement_rate": (v["agree"] / v["total"]) if v["total"] else None, } for c, v in sorted(cats.items()) }, }
# 4) Write <out>.json and <out>.md. out_prefix = Path(args.out) out_prefix.parent.mkdir(parents=True, exist_ok=True) with open(str(out_prefix) + ".json", "w", encoding="utf-8") as f: json.dump(result, f, indent=2, ensure_ascii=False)
la, lb = args.label_a, args.label_b L = [] L.append(f"# Runtime A/B: {la} vs {lb}") L.append("") L.append(f"- A: `{args.base_url_a}` ({la})") L.append(f"- B: `{args.base_url_b}` ({lb})") L.append(f"- model: `{args.model}`, data: `{args.data}`, " f"limit: {args.limit}, compared: {m}") L.append("") L.append("## Metrics (A vs B)") L.append("") L.append(f"| metric | {la} (A) | {lb} (B) | delta (B-A) |") L.append("|---|---|---|---|") if rows: for k, va, vb, d in rows: L.append(f"| {k} | {fmt(va)} | {fmt(vb)} | {fmt_delta(d)} |") else: L.append("| _no numeric metrics found in eval output_ | n/a | n/a | n/a |") L.append("") L.append("## Per-category deltas") L.append("") if cats: if have_scores: L.append("| category | n | mean A | mean B | delta (B-A) | agree |") L.append("|---|---|---|---|---|---|") for c in sorted(cats): v = result["per_category"][c] L.append(f"| {c} | {v['n']} | {fmt(v['mean_score_a'])} | " f"{fmt(v['mean_score_b'])} | " f"{fmt_delta(v['delta_b_minus_a'])} | " f"{fmt(v['agreement_rate'])} |") else: L.append("_Per-prompt scores not recorded by the eval; " "showing n and A-vs-B agreement per category._") L.append("") L.append("| category | n | agreement | |") L.append("|---|---|---|---|") for c in sorted(cats): v = result["per_category"][c] L.append(f"| {c} | {v['n']} | {fmt(v['agreement_rate'])} | |") else: L.append("_No per-prompt records found; per-category breakdown " "unavailable._") L.append("") L.append("## Agreement") L.append("") L.append(f"- per-prompt agreement rate: **{fmt(agreement_rate)}** " f"({agree}/{m})") L.append(f"- disagreement count: **{len(disagreements)}**") if disagreements: shown = disagreements[:10] L.append(f"- first disagreements: {', '.join(shown)}" + (" ..." if len(disagreements) > 10 else "")) L.append("") L.append("## Latency / throughput (from usage)") L.append("") L.append(f"| side | mean latency (s) | mean tok/s | n timed |") L.append("|---|---|---|---|") L.append(f"| {la} (A) | {fmt(mean_lat_a)} | {fmt(mean_tps_a)} | " f"{len([x for x in lat_a if x is not None])} |") L.append(f"| {lb} (B) | {fmt(mean_lat_b)} | {fmt(mean_tps_b)} | " f"{len([x for x in lat_b if x is not None])} |") if mean_lat_a is None and mean_lat_b is None: L.append("") L.append("_No latency/usage fields recorded by the eval; " "tok/s unavailable._") L.append("") L.append("## Reproduce") L.append("") L.append("```powershell") L.append(f".\\pipeline\\start_servers.ps1 -BaseGguf <base.gguf> " f"-TunedGguf <tuned.gguf> # ports {args.base_url_a} / {args.base_url_b}") L.append(f"python pipeline/runtime_ab.py --base-url-a {args.base_url_a} " f"--label-a \"{la}\" --base-url-b {args.base_url_b} " f"--label-b \"{lb}\" --data {args.data} --limit {args.limit} " f"--out {args.out}") L.append("```") L.append("") with open(str(out_prefix) + ".md", "w", encoding="utf-8") as f: f.write("\n".join(L))
print(f"Wrote {args.out}.md and {args.out}.json (compared {m} prompts).") return 0
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293<#.SYNOPSIS Launch two llama-server processes (base vs tuned) for runtime A/B eval.
.EXAMPLE .\pipeline\start_servers.ps1 -BaseGguf .\output\base-Q8_0.gguf -TunedGguf .\output\tuned-Q8_0.gguf .\pipeline\start_servers.ps1 -BaseGguf .\a.gguf -TunedGguf .\b.gguf -PortA 8080 -PortB 8081#>param( [string]$BaseGguf, [string]$TunedGguf, [int]$PortA = 8080, [int]$PortB = 8081)
$ErrorActionPreference = 'Stop'
function Usage { Write-Host "Usage: .\pipeline\start_servers.ps1 -BaseGguf <base.gguf> -TunedGguf <tuned.gguf> [-PortA 8080] [-PortB 8081]" Write-Host "Launches two llama-server processes with --jinja -c 2048 -ngl 0 (CPU-safe)," Write-Host "waits for /health on each, writes PIDs, and prints the two base URLs."}
if ([string]::IsNullOrWhiteSpace($BaseGguf) -or [string]::IsNullOrWhiteSpace($TunedGguf)) { Write-Host "ERROR: -BaseGguf and -TunedGguf are both required." -ForegroundColor Red Usage exit 1}if ($PortA -eq $PortB) { Write-Host "ERROR: -PortA and -PortB must differ." -ForegroundColor Red exit 1}foreach ($f in @($BaseGguf, $TunedGguf)) { if (-not (Test-Path $f)) { Write-Host "ERROR: GGUF file not found: $f" -ForegroundColor Red Write-Host "Check the path and re-run. (This check runs at launch time only;" Write-Host " the script parses fine without the files existing.)" exit 1 }}
$RepoRoot = Split-Path (Split-Path $MyInvocation.MyCommand.Path -Parent) -Parent$Server = Join-Path $RepoRoot 'llama-bin\llama-server.exe'if (-not (Test-Path $Server)) { # fall back to PATH $cmd = Get-Command llama-server -ErrorAction SilentlyContinue if ($cmd) { $Server = $cmd.Source } else { Write-Host "ERROR: llama-server not found at $Server and not on PATH." -ForegroundColor Red exit 1 }}
function Start-Side { param([string]$Gguf, [int]$Port, [string]$Tag) $log = Join-Path $RepoRoot "llama-server-$Tag-$Port.log" $pidFile = Join-Path $RepoRoot "llama-server-$Tag-$Port.pid" Write-Host "Starting [$Tag] $Server -m $Gguf --port $Port ..." $proc = Start-Process -FilePath $Server ` -ArgumentList @('-m', $Gguf, '--port', "$Port", '--jinja', '-c', '2048', '-ngl', '0') ` -RedirectStandardOutput $log -RedirectStandardError ("$log.err") ` -PassThru $proc.Id | Out-File -FilePath $pidFile -Encoding ascii Write-Host " PID $($proc.Id) (pid file: $pidFile, log: $log)"
# Wait for /health (llama-server serves GET /health -> {"status":"ok"}). $deadline = (Get-Date).AddSeconds(300) while ((Get-Date) -lt $deadline) { if ($proc.HasExited) { Write-Host "ERROR: [$Tag] server (PID $($proc.Id)) exited early. See $log and $log.err" -ForegroundColor Red exit 1 } try { $r = Invoke-WebRequest -Uri "http://127.0.0.1:$Port/health" -TimeoutSec 5 -UseBasicParsing if ($r.StatusCode -eq 200) { Write-Host " [$Tag] healthy on port $Port"; return $proc.Id } } catch { Start-Sleep -Seconds 2 } } Write-Host "ERROR: [$Tag] server did not become healthy within 300s. See $log" -ForegroundColor Red exit 1}
$pidA = Start-Side -Gguf $BaseGguf -Port $PortA -Tag 'base'$pidB = Start-Side -Gguf $TunedGguf -Port $PortB -Tag 'tuned'
$urlA = "http://127.0.0.1:$PortA/v1"$urlB = "http://127.0.0.1:$PortB/v1"Write-Host ""Write-Host "Both servers up:"Write-Host " A (base): $urlA (PID $pidA)"Write-Host " B (tuned): $urlB (PID $pidB)"Write-Host ""Write-Host "Next:"Write-Host " python pipeline/runtime_ab.py --base-url-a $urlA --label-a `"base Q8_0`" --base-url-b $urlB --label-b `"tuned Q8_0`" --data data_native/test.jsonl --limit 100 --out reports/runtime_ab"Write-Host "Stop with: Stop-Process -Id $pidA,$pidB"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274"""Tests for metrics_lib. Run: .venv\\Scripts\\python.exe pipeline\\test_metrics_lib.py
Pytest-compatible (test_* functions) AND runnable as a script with anon-zero exit code on failure."""
import sysimport os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from metrics_lib import ( parse_calls, normalize_value, canon_call, canon_calls, categorize, failure_bucket,)
def _assistant(content="hi", tool_calls=None): m = {"role": "assistant", "content": content} if tool_calls is not None: m["tool_calls"] = tool_calls return m
def _tool(name, props): return {"function": {"name": name, "parameters": {"type": "object", "properties": props}}}
# ---------------- parse_calls ----------------
def test_xml_single(): calls = parse_calls('<function name="get_weather"><param name="city">Paris</param></function>') assert calls == [{"name": "get_weather", "arguments": {"city": "Paris"}}], calls
def test_xml_multiple(): text = ('<function name="a"><param name="x">1</param></function> ' 'some prose ' '<function name="b"><param name="y">2</param><param name="z">3</param></function>') calls = parse_calls(text) assert len(calls) == 2, calls assert calls[0]["name"] == "a" and calls[1]["name"] == "b" assert calls[1]["arguments"] == {"y": "2", "z": "3"}
def test_xml_multiline_param(): text = '<function name="search"><param name="query">line one\nline two\nline three</param></function>' calls = parse_calls(text) assert calls[0]["arguments"]["query"] == "line one\nline two\nline three", calls
def test_xml_cdata(): text = '<function name="run"><param name="code"><![CDATA[if x < 3 && y > 1 {"a": 1}]]></param></function>' calls = parse_calls(text) assert calls[0]["arguments"]["code"] == 'if x < 3 && y > 1 {"a": 1}', calls
def test_xml_single_quotes(): calls = parse_calls("<function name='f'><param name='k'>v</param></function>") assert calls == [{"name": "f", "arguments": {"k": "v"}}], calls
def test_json_array(): calls = parse_calls('[{"name": "a", "arguments": {"x": 1}}, {"name": "b", "arguments": {}}]') assert calls == [{"name": "a", "arguments": {"x": 1}}, {"name": "b", "arguments": {}}], calls
def test_json_tool_calls_object(): calls = parse_calls('{"tool_calls": [{"name": "a", "arguments": {"x": 1}}]}') assert calls == [{"name": "a", "arguments": {"x": 1}}], calls
def test_json_openai_wrapper(): text = ('{"role": "assistant", "tool_calls": ' '[{"id": "1", "type": "function", "function": {"name": "a", "arguments": "{\\"x\\": 1}"}}]}') calls = parse_calls(text) assert calls == [{"name": "a", "arguments": {"x": 1}}], calls
def test_json_single_object(): calls = parse_calls('{"name": "solo", "arguments": {"k": "v"}}') assert calls == [{"name": "solo", "arguments": {"k": "v"}}], calls
def test_json_args_string(): calls = parse_calls('{"name": "a", "arguments": "{\\"x\\": 2}"}') assert calls == [{"name": "a", "arguments": {"x": 2}}], calls
def test_parse_empty(): assert parse_calls("") == [] assert parse_calls("no calls here, just prose") == []
# ---------------- normalize_value ----------------
def test_norm_true_variants(): assert normalize_value(True) == ("bool", True) assert normalize_value("true") == ("bool", True) assert normalize_value("True") == ("bool", True) assert normalize_value("TRUE") == ("bool", True) assert normalize_value("false") == ("bool", False) assert normalize_value(False) == ("bool", False)
def test_norm_numeric_strings(): assert normalize_value("1") == normalize_value(1) == normalize_value("1.0") == ("num", 1.0) assert normalize_value(1.5) == ("num", 1.5) assert normalize_value("[1, 2]") == ("list", (("num", 1.0), ("num", 2.0))) assert normalize_value([1, 2]) == ("list", (("num", 1.0), ("num", 2.0)))
def test_norm_bool_is_not_num(): assert normalize_value(True) != normalize_value(1) assert normalize_value(True)[0] == "bool" and normalize_value(1)[0] == "num"
def test_norm_dict_and_none(): assert normalize_value({"b": 1, "a": "x"}) == ( "dict", (("a", ("str", "x")), ("b", ("num", 1.0)))) assert normalize_value("null") == ("none", None) assert normalize_value(None) == ("none", None) assert normalize_value("Paris") == ("str", "Paris")
def test_canon_sort_and_coercion(): c1 = canon_call({"name": "f", "arguments": {"b": "1", "a": 2}}) c2 = canon_call({"name": "f", "arguments": {"a": "2", "b": 1}}) assert c1 == c2 assert canon_calls([{"name": "b", "arguments": {}}]) > canon_calls([{"name": "a", "arguments": {}}]) assert canon_calls([]) == []
# ---------------- failure_bucket ----------------
def test_bucket_ok(): exp = [{"name": "a", "arguments": {"x": 1}}] pred = [{"name": "a", "arguments": {"x": "1"}}] # typed-equal after coercion assert failure_bucket(exp, pred, "raw") == "ok" assert failure_bucket([], [], "nothing") == "ok"
def test_bucket_unparsed(): exp = [{"name": "a", "arguments": {}}] assert failure_bucket(exp, [], 'I will call <function name="a"> now') == "unparsed" assert failure_bucket(exp, [], "using tool_call id=1 ...") == "unparsed"
def test_bucket_no_call(): exp = [{"name": "a", "arguments": {}}] assert failure_bucket(exp, [], "plain text, no attempt") == "no_call"
def test_bucket_spurious(): assert failure_bucket([], [{"name": "a", "arguments": {}}], "raw") == "spurious_call"
def test_bucket_wrong_tool(): exp = [{"name": "a", "arguments": {}}] assert failure_bucket(exp, [{"name": "b", "arguments": {}}], "raw") == "wrong_tool" exp2 = [{"name": "a", "arguments": {}}, {"name": "b", "arguments": {}}] pred2 = [{"name": "a", "arguments": {}}, {"name": "c", "arguments": {}}] assert failure_bucket(exp2, pred2, "raw") == "wrong_tool"
def test_bucket_missing_extra(): exp = [{"name": "a", "arguments": {}}, {"name": "b", "arguments": {}}] assert failure_bucket(exp, [{"name": "a", "arguments": {}}], "raw") == "missing_call" assert failure_bucket([{"name": "a", "arguments": {}}], exp, "raw") == "extra_call"
def test_bucket_arg_mismatch(): exp = [{"name": "a", "arguments": {"city": "Paris"}}] assert failure_bucket(exp, [{"name": "a", "arguments": {"city": "London"}}], "raw") == "arg_mismatch" assert failure_bucket(exp, [{"name": "a", "arguments": {"town": "Paris"}}], "raw") == "arg_mismatch"
def test_bucket_value_typing(): exp = [{"name": "a", "arguments": {"city": "Paris"}}] assert failure_bucket(exp, [{"name": "a", "arguments": {"city": "paris"}}], "raw") == "value_typing"
# ---------------- categorize ----------------
def test_cat_abstention(): row = {"tools": [], "messages": [{"role": "user", "content": "hi"}, _assistant("no tools")]} assert categorize(row) == "abstention"
def test_cat_multi(): tc = [{"name": "a", "arguments": {}}, {"name": "b", "arguments": {}}] row = {"tools": [], "messages": [{"role": "user", "content": "q"}, _assistant("x", tc)]} assert categorize(row) == "multi_call"
def test_cat_nested_schema(): row = {"tools": [_tool("f", {"obj": {"type": "object"}})], "messages": [{"role": "user", "content": "q"}, _assistant("x", [{"name": "f", "arguments": {"obj": "s"}}])]} assert categorize(row) == "nested_args"
def test_cat_nested_values(): row = {"tools": [_tool("f", {"s": {"type": "string"}})], "messages": [{"role": "user", "content": "q"}, _assistant("x", [{"name": "f", "arguments": {"s": {"deep": 1}}}])]} assert categorize(row) == "nested_args"
def test_cat_enum(): row = {"tools": [_tool("f", {"c": {"type": "string", "enum": ["r", "g"]}})], "messages": [{"role": "user", "content": "q"}, _assistant("x", [{"name": "f", "arguments": {"c": "r"}}])]} assert categorize(row) == "enum_args"
def test_cat_long_and_single(): tools = [_tool("f%d" % i, {"s": {"type": "string"}}) for i in range(10)] row = {"tools": tools, "messages": [{"role": "user", "content": "q"}, _assistant("x", [{"name": "f0", "arguments": {}}])]} assert categorize(row) == "long_tools" row2 = {"tools": [_tool("f", {"s": {"type": "string"}})], "messages": [{"role": "user", "content": "q"}, _assistant("x", [{"name": "f", "arguments": {"s": "v"}}])]} assert categorize(row2) == "single_call"
def test_cat_priority(): # abstention beats multi_call history: earlier assistant had 2 calls, last has none tc = [{"name": "a", "arguments": {}}, {"name": "b", "arguments": {}}] row = {"tools": [], "messages": [{"role": "user", "content": "q"}, _assistant("x", tc), {"role": "user", "content": "q2"}, _assistant("none")] } assert categorize(row) == "abstention" # multi beats nested schema row = {"tools": [_tool("f", {"o": {"type": "object"}})], "messages": [{"role": "user", "content": "q"}, _assistant("x", tc)]} assert categorize(row) == "multi_call" # nested beats enum row = {"tools": [_tool("f", {"o": {"type": "object"}, "c": {"type": "string", "enum": ["a"]}})], "messages": [{"role": "user", "content": "q"}, _assistant("x", [{"name": "f", "arguments": {"o": "v", "c": "a"}}])]} assert categorize(row) == "nested_args" # enum beats long_tools tools = [_tool("f%d" % i, {"s": {"type": "string"}}) for i in range(10)] tools[0]["function"]["parameters"]["properties"]["s"] = {"type": "string", "enum": ["a"]} row = {"tools": tools, "messages": [{"role": "user", "content": "q"}, _assistant("x", [{"name": "f0", "arguments": {"s": "a"}}])]} assert categorize(row) == "enum_args"
def main(): tests = sorted([(k, v) for k, v in sorted(globals().items()) if k.startswith("test_") and callable(v)]) failed = 0 for name, fn in tests: try: fn() except Exception as e: failed += 1 print("FAIL %s: %r" % (name, e)) else: print("PASS %s" % name) print("%d passed, %d failed, %d total" % (len(tests) - failed, failed, len(tests))) return 1 if failed else 0
if __name__ == "__main__": sys.exit(main())227 unmodified lines2282292302312322332342352362372382392402413 unmodified lines2452462472482492502515 unmodified lines257258259260261262263118 unmodified lines38238338438538638712 unmodified lines400401402403404405406227 unmodified linesfor r in rows]pred1 = [parse_output(t) for t in generate(p1)]pred2 = [parse_output(t) for t in generate(p2)]tok.padding_side = "right"model.config.use_cache = prev_caches1 = s2_type = 0gt2_calls, gt2_text = [], []for r, a, b in zip(rows, pred1, pred2):gt1 = r["messages"][1].get("tool_calls") or []if sorted(canon(c) for c in a) == sorted(canon(c) for c in gt1):s1 += 13 unmodified linesif gt2:gt2_calls.append((b, gt2))else:gt2_text.append(b)n = max(1, len(rows))mt = {5 unmodified linesif gt2_callselse None),"stage2_answer_rate": (sum(bool(b) for b in gt2_text) / len(gt2_text)) if gt2_text else None,}return mt118 unmodified linesap.add_argument("--max-train", type=int, default=0)ap.add_argument("--eval-limit", type=int, default=0)ap.add_argument("--push-to", default="")ap.add_argument("--extra-train", default="", help="extra JSONL of conversations (multi-turn) to append to train")ap.add_argument("--multiturn-test", default="", help="JSONL of 4-message loops for staged evaluation")ap.add_argument("--adapter", default="", help="eval-only: load this adapter repo instead of training")12 unmodified linestok.padding_side = "right"log("loading data...")train_rows = load_jsonl(data / "train.jsonl")val_rows = load_jsonl(data / "val.jsonl")test_rows = load_jsonl(data / "test.jsonl")if args.extra_train and Path(args.extra_train).exists():227 unmodified lines2282292302312322332342352362372382392402412423 unmodified lines2462472482492502512525 unmodified lines258259260261262263264265266267268118 unmodified lines38738838939039139239312 unmodified lines406407408409410411412227 unmodified linesfor r in rows]pred1 = [parse_output(t) for t in generate(p1)]t2 = generate(p2)pred2 = [parse_output(t) for t in t2]tok.padding_side = "right"model.config.use_cache = prev_caches1 = s2_type = 0gt2_calls, gt2_text = [], []for r, a, b, raw2 in zip(rows, pred1, pred2, t2):gt1 = r["messages"][1].get("tool_calls") or []if sorted(canon(c) for c in a) == sorted(canon(c) for c in gt1):s1 += 13 unmodified linesif gt2:gt2_calls.append((b, gt2))else:gt2_text.append((b, raw2))n = max(1, len(rows))mt = {5 unmodified linesif gt2_callselse None),# When the ground truth is an answer, a good model emits no call at all."stage2_no_spurious_call_rate": (sum(not b for b, _ in gt2_text) / len(gt2_text) if gt2_text else None),"stage2_answer_rate": (sum(bool(t.strip()) for _, t in gt2_text) / len(gt2_text)) if gt2_text else None,}return mt118 unmodified linesap.add_argument("--max-train", type=int, default=0)ap.add_argument("--eval-limit", type=int, default=0)ap.add_argument("--push-to", default="")ap.add_argument("--train-file", default="train.jsonl")ap.add_argument("--extra-train", default="", help="extra JSONL of conversations (multi-turn) to append to train")ap.add_argument("--multiturn-test", default="", help="JSONL of 4-message loops for staged evaluation")ap.add_argument("--adapter", default="", help="eval-only: load this adapter repo instead of training")12 unmodified linestok.padding_side = "right"log("loading data...")train_rows = load_jsonl(data / args.train_file)val_rows = load_jsonl(data / "val.jsonl")test_rows = load_jsonl(data / "test.jsonl")if args.extra_train and Path(args.extra_train).exists():
GGUF.mdAdded+69
__pycache__/analyze_failures.cpython-311.pycAdded
__pycache__/audit_dataset.cpython-311.pycAdded
__pycache__/build_card.cpython-311.pycAdded
__pycache__/check_gate.cpython-311.pycAdded
__pycache__/check_special.cpython-311.pycAdded
__pycache__/convert_hf_to_gguf.cpython-311.pycAdded
__pycache__/debug_base.cpython-311.pycAdded
__pycache__/debug_encode.cpython-311.pycAdded
__pycache__/debug_gen.cpython-311.pycAdded
__pycache__/eval_openai.cpython-311.pycAdded
__pycache__/inspect_mt.cpython-311.pycAdded
__pycache__/inspect_raw.cpython-311.pycAdded
__pycache__/make_hard_set.cpython-311.pycAdded
__pycache__/merge_local.cpython-311.pycAdded
__pycache__/metrics_lib.cpython-311.pycAdded
__pycache__/mt_lengths.cpython-311.pycAdded
__pycache__/prepare_multiturn.cpython-311.pycAdded
__pycache__/runtime_ab.cpython-311.pycAdded
__pycache__/test_encode.cpython-311.pycAdded
__pycache__/test_metrics_lib.cpython-311.pycAdded
__pycache__/test_runtime.cpython-311.pycAdded
__pycache__/train_eval.cpython-311.pyc
analyze_failures.pyAdded+222
audit_dataset.pyAdded+352
build_card.pyAdded+464
check_gate.pyAdded+321
convert_hf_to_gguf.pyAdded+342
eval_openai.pyAdded+485
make_gguf.ps1Added+96
make_hard_set.pyAdded+386
make_oversampled.pyAdded+28
metrics_lib.pyAdded+501
runtime_ab.pyAdded+588
start_servers.ps1Added+93
test_metrics_lib.pyAdded+274
train_eval.py+11-5