File size: 14,256 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 | """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 argparse
import datetime
import json
import sys
from pathlib import Path
try:
import requests
except ImportError: # pragma: no cover
requests = None
ROOT = Path(__file__).resolve().parent.parent
# Thresholds (per spec).
MIN_ABSTENTION = 0.90
MIN_POSITIVE_EXACT = 0.65
MIN_PARSE = 0.95
MIN_MT_STAGE1 = 0.60
MIN_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())
|