#!/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: /chart.svg). Never invents numbers: any missing value renders as "n/a" and its claim is omitted. """ from __future__ import annotations import argparse import html import json from pathlib import Path BASE_MODEL = "openbmb/MiniCPM5-1B" ADAPTER = "LoRA r=16 on all linear layers" CONTEXT = 1024 DATASET_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 template llama-server \\ -m minicpm5-1b-toolcall-q4_k_m.gguf \\ --jinja -c 2048 --temp 0 ``` ```bash curl 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`.** > ``, ``, ``, `` 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'', "Base vs +LoRA on single-turn tool-call metrics", f"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.", f'' "Base vs +LoRA (single-turn)", # legend f'', f'Base', f'', f'+LoRA', ] # gridlines + y labels for g in (0.0, 0.25, 0.5, 0.75, 1.0): yy = y(g) parts.append( f'' f'{g:.2f}' ) # axes parts.append(f'') parts.append(f'') parts.append( f'rate' ) parts.append( f'metric' ) 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'n/a' ) else: top, bot = y(v), y(0) parts.append( f"" f"{html.escape(label)} {html.escape(tag)}: {v:.3f}" ) parts.append( f'{v:.2f}' ) parts.append( f'{html.escape(CHART_SHORT[key])}' ) parts.append("") 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: /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()