File size: 17,028 Bytes
17b0632 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 | #!/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 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`.**
> `<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()
|