Download tools/run_gates.py from tailot/lingologos-thinkingpython: direct link, hf CLI and curl.
- Browser
- Download file 12.2 kB
-
https://huggingface.co/datasets/tailot/lingologos-thinkingpython/resolve/main/tools/run_gates.py
- Command line
-
hf download hf://datasets/tailot/lingologos-thinkingpython/tools/run_gates.py
-
curl -L -o run_gates.py https://huggingface.co/datasets/tailot/lingologos-thinkingpython/resolve/main/tools/run_gates.py
12.2 kB
| """Run every gate the specification declares. Any FAIL means no publication. | |
| Every gate is timed and the verdict of the run is written to `results/gates.json`, with a | |
| digest of the artifacts each number came from: a gate that cannot say which bytes it | |
| checked is not a gate. | |
| """ | |
| import argparse | |
| import hashlib | |
| import json | |
| import os | |
| import subprocess | |
| import sys | |
| import time | |
| from typing import Any, Dict, List | |
| ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| sys.path.insert(0, ROOT) | |
| from lingologos_thinkingpython import catalog # noqa: E402 | |
| RESULTS_DIR = os.path.join(ROOT, "results") | |
| COVERAGE = os.path.join(RESULTS_DIR, "coverage.json") | |
| HELDOUT = os.path.join(RESULTS_DIR, "heldout.json") | |
| BLIND = os.path.join(RESULTS_DIR, "heldout_blind.json") | |
| GATES = os.path.join(RESULTS_DIR, "gates.json") | |
| CORPUS_DIR = os.path.join(ROOT, "corpus") | |
| #: Splits never generated from the lexicon. SPECIFICATION.md 11. | |
| HELDOUT_SPLITS = ("heldout_model_authored.jsonl", "heldout_variants.jsonl") | |
| COMPOSED_FLOOR = 0.999 | |
| HELDOUT_TOP1_FLOOR = 0.60 | |
| HELDOUT_RECALL_FLOOR = 0.60 | |
| HELDOUT_PRECISION_FLOOR = 0.95 | |
| HELDOUT_REFUSAL_FLOOR = 0.95 | |
| HELDOUT_SPREAD_LIMIT = 0.20 | |
| REFUSAL_FLOOR = 0.90 | |
| #: Floors on the eval split for the classifier trained by tools/train_intent.py. The margin | |
| #: that gates the second opinion is itself chosen on that split, so these floors are the | |
| #: guard rail of that choice, never a second tuning knob. | |
| INTENT_PRECISION_FLOOR = 0.99 | |
| INTENT_REFUSAL_FLOOR = 0.99 | |
| INTENT_SPREAD_LIMIT = 0.05 | |
| CONTRASTIVE_FLOOR = 0.70 | |
| REGRESSION_LIMIT = 0.02 | |
| tools = os.path.join(ROOT, "tools") | |
| GATE_LOG: List[Dict[str, Any]] = [] | |
| def _run(cmd: list) -> int: | |
| return subprocess.run(cmd, cwd=ROOT).returncode | |
| def digest(path: str) -> str: | |
| """First 16 hex digits of the sha256 of an artifact, or MISSING.""" | |
| if not os.path.isfile(path): | |
| return "MISSING" | |
| sha = hashlib.sha256() | |
| with open(path, "rb") as handle: | |
| for block in iter(lambda: handle.read(65536), b""): | |
| sha.update(block) | |
| return sha.hexdigest()[:16] | |
| def gate(name: str, ok: bool, detail: str = "", seconds: float = 0.0, | |
| artifacts: tuple = ()) -> bool: | |
| print("gate %-22s %s %s [%.2fs]" % (name, "PASS" if ok else "FAIL", detail, seconds)) | |
| GATE_LOG.append({"gate": name, "status": "PASS" if ok else "FAIL", "detail": detail, | |
| "seconds": round(seconds, 2), | |
| "digests": {os.path.relpath(p, ROOT).replace(os.sep, "/"): digest(p) | |
| for p in artifacts}}) | |
| return ok | |
| def timed(cmd: list) -> tuple: | |
| started = time.time() | |
| code = _run(cmd) | |
| return code, time.time() - started | |
| def main(argv=None) -> int: | |
| parser = argparse.ArgumentParser(description="Run the publication gates.") | |
| parser.add_argument("--catalog-regress", action="store_true", | |
| help="compare routing top-1 with results/coverage.baseline.json") | |
| args = parser.parse_args(argv) | |
| ok = True | |
| entries = catalog.load_entries() | |
| defects = catalog.integrity(entries) | |
| ok &= gate("catalog_integrity", not defects, "%d entries, %d defects" | |
| % (len(entries), len(defects))) | |
| for line in defects[:5]: | |
| print(" %s" % line) | |
| policies = catalog.load_policies() | |
| ids = sorted(entry["id"] for entry in entries) | |
| missing = [("%s|%s" % (ids[i], ids[j])) | |
| for i in range(len(ids)) for j in range(i + 1, len(ids)) | |
| if catalog.policy_for(policies, ids[i], ids[j]) is None] | |
| ok &= gate("catalog_conflicts", not missing, "%d pairs declared, %d missing" | |
| % (len(ids) * (len(ids) - 1) // 2, len(missing))) | |
| os.makedirs(RESULTS_DIR, exist_ok=True) | |
| with open(os.path.join(RESULTS_DIR, "conflicts.json"), "w", encoding="utf-8", newline="\n") as handle: | |
| json.dump({"pairs": policies, "missing": missing, "entries": ids}, handle, | |
| indent=2, sort_keys=True) | |
| handle.write("\n") | |
| ok &= gate("corpus_fingerprint", | |
| _run([sys.executable, os.path.join(tools, "build_corpus.py"), "--check"]) == 0, | |
| "re-derived from catalog and lexicon", artifacts=( | |
| os.path.join(CORPUS_DIR, "corpus.jsonl"), | |
| os.path.join(ROOT, "catalog", "patterns.json"))) | |
| code, seconds = timed([sys.executable, os.path.join(tools, "measure_coverage.py")]) | |
| ok &= gate("coverage", code == 0, "measured train and eval splits", seconds, | |
| artifacts=(COVERAGE, os.path.join(CORPUS_DIR, "corpus.jsonl"))) | |
| if os.path.isfile(COVERAGE): | |
| with open(COVERAGE, "r", encoding="utf-8") as handle: | |
| stats = json.load(handle)["eval"] | |
| ok &= gate("generator_consistency", stats["top1"] >= COMPOSED_FLOOR, | |
| "composed eval top1=%.4f floor=%.3f" % (stats["top1"], COMPOSED_FLOOR)) | |
| ok &= gate("refusal_floor", stats["refusal"] >= REFUSAL_FLOOR, | |
| "eval refusal=%.4f floor=%.2f" % (stats["refusal"], REFUSAL_FLOOR)) | |
| contrastive = stats.get("by_level", {}).get("L3", {}).get("top1", 0.0) | |
| ok &= gate("contrastive_floor", contrastive >= CONTRASTIVE_FLOOR, | |
| "eval contrastive=%.4f floor=%.2f" % (contrastive, CONTRASTIVE_FLOOR)) | |
| ok &= gate("variety_spread", stats["worst_variety_gap"] <= 0.05, | |
| "gap=%.4f" % stats["worst_variety_gap"]) | |
| if args.catalog_regress: | |
| baseline = os.path.join(RESULTS_DIR, "coverage.baseline.json") | |
| if os.path.isfile(baseline): | |
| with open(baseline, "r", encoding="utf-8") as handle: | |
| old = json.load(handle)["top1"] | |
| drop = old - stats["top1"] | |
| ok &= gate("catalog_regress", drop <= REGRESSION_LIMIT, | |
| "drop=%.4f limit=%.2f" % (drop, REGRESSION_LIMIT)) | |
| else: | |
| with open(baseline, "w", encoding="utf-8") as handle: | |
| json.dump({"top1": stats["top1"]}, handle) | |
| ok &= gate("catalog_regress", True, "baseline written") | |
| else: | |
| ok &= gate("generator_consistency", False, "no results/coverage.json") | |
| # The held-out splits are written, not generated. These are the numbers the card | |
| # leads with; the composed numbers above only prove generator and router agree. | |
| splits = ",".join(os.path.join(CORPUS_DIR, name) for name in HELDOUT_SPLITS | |
| if os.path.isfile(os.path.join(CORPUS_DIR, name))) | |
| ok &= gate("heldout_present", bool(splits), splits.replace(ROOT + os.sep, "")) | |
| if splits: | |
| code, seconds = timed([sys.executable, os.path.join(tools, "measure_coverage.py"), | |
| "--corpus", splits, "--out", HELDOUT]) | |
| ok &= gate("heldout_measure", code == 0, splits.replace(ROOT + os.sep, ""), seconds, | |
| artifacts=tuple(os.path.join(CORPUS_DIR, name) for name in HELDOUT_SPLITS)) | |
| if os.path.isfile(HELDOUT): | |
| with open(HELDOUT, "r", encoding="utf-8") as handle: | |
| held = json.load(handle)["eval"] | |
| ok &= gate("heldout_top1_floor", held["top1"] >= HELDOUT_TOP1_FLOOR, | |
| "heldout top1=%.4f floor=%.2f" % (held["top1"], HELDOUT_TOP1_FLOOR)) | |
| ok &= gate("heldout_recall_floor", held.get("recall", 0.0) >= HELDOUT_RECALL_FLOOR, | |
| "heldout recall=%.4f floor=%.2f" | |
| % (held.get("recall", 0.0), HELDOUT_RECALL_FLOOR)) | |
| ok &= gate("heldout_precision_floor", | |
| held.get("precision", 0.0) >= HELDOUT_PRECISION_FLOOR, | |
| "heldout precision=%.4f floor=%.2f" | |
| % (held.get("precision", 0.0), HELDOUT_PRECISION_FLOOR)) | |
| ok &= gate("heldout_refusal_floor", held["refusal"] >= HELDOUT_REFUSAL_FLOOR, | |
| "heldout refusal=%.4f floor=%.2f" % (held["refusal"], HELDOUT_REFUSAL_FLOOR)) | |
| ok &= gate("heldout_spread", held["worst_variety_gap"] <= HELDOUT_SPREAD_LIMIT, | |
| "gap=%.4f limit=%.2f" % (held["worst_variety_gap"], HELDOUT_SPREAD_LIMIT)) | |
| else: | |
| ok &= gate("heldout_top1_floor", False, "no held-out corpus") | |
| # The blind slice is a harder test written without ever reading the lexicon. It is | |
| # measured and published with its own numbers, and it is reported, not gated: a floor | |
| # invented for it now would be a second tuning knob, and hiding it would be worse. | |
| blind = os.path.join(CORPUS_DIR, "heldout_blind_slice.jsonl") | |
| if os.path.isfile(blind): | |
| code, seconds = timed([sys.executable, os.path.join(tools, "measure_coverage.py"), | |
| "--corpus", blind, "--out", BLIND]) | |
| reported = False | |
| if code == 0 and os.path.isfile(BLIND): | |
| with open(BLIND, "r", encoding="utf-8") as handle: | |
| cell = json.load(handle)["eval"] | |
| reported = True | |
| ok &= gate("heldout_blind_reported", reported, | |
| "blind slice top1=%.4f recall=%.4f refusal=%.4f gap=%.4f, written to %s" | |
| % (cell.get("top1", 0.0), cell.get("recall", 0.0), | |
| cell.get("refusal", 0.0), cell.get("worst_variety_gap", 0.0), | |
| os.path.relpath(BLIND, ROOT).replace(os.sep, "/")) | |
| if reported else "the blind slice was not measured", | |
| seconds, artifacts=(blind, BLIND)) | |
| intent_model = os.path.join(ROOT, "models", "intent_model.json") | |
| intent_eval = os.path.join(RESULTS_DIR, "intent_model_eval.json") | |
| code, seconds = timed([sys.executable, os.path.join(tools, "train_intent.py"), "--check"]) | |
| ok &= gate("intent_model_reproducible", code == 0, "retrained from the corpus in memory", | |
| seconds, artifacts=(intent_model,)) | |
| if os.path.isfile(intent_eval): | |
| with open(intent_eval, "r", encoding="utf-8") as handle: | |
| booklet = json.load(handle) | |
| overall = booklet.get("overall", {}) | |
| ok &= gate("intent_model_eval", | |
| overall.get("precision", 0.0) >= INTENT_PRECISION_FLOOR | |
| and overall.get("refusal", 0.0) >= INTENT_REFUSAL_FLOOR | |
| and booklet.get("top1_spread", 1.0) <= INTENT_SPREAD_LIMIT, | |
| "eval precision=%.4f refusal=%.4f spread=%.4f margin=%s" | |
| % (overall.get("precision", 0.0), overall.get("refusal", 0.0), | |
| booklet.get("top1_spread", 0.0), booklet.get("margin")), | |
| artifacts=(intent_eval,)) | |
| else: | |
| ok &= gate("intent_model_eval", False, "no results/intent_model_eval.json") | |
| for name, cmd, artifacts in ( | |
| ("seed_project", [sys.executable, os.path.join(tools, "make_seed_project.py"), | |
| "--check"], (os.path.join(ROOT, "tools", "make_seed_project.py"),)), | |
| ("maintenance", [sys.executable, os.path.join(tools, "run_maintenance.py")], | |
| (os.path.join(ROOT, "corpus", "maintenance.jsonl"), | |
| os.path.join(RESULTS_DIR, "maintenance.json"))), | |
| ("confine", [sys.executable, os.path.join(tools, "selfcheck_confine.py")], ()), | |
| ("tests", [sys.executable, "-m", "pytest", "-q", os.path.join(ROOT, "tests")], ())): | |
| code, seconds = timed(cmd) | |
| ok &= gate(name, code == 0, "", seconds, artifacts=artifacts) | |
| ok &= gate("coverage_report", | |
| _run([sys.executable, os.path.join(tools, "measure_test_coverage.py")]) == 0, | |
| "share of package functions entered by the suite", | |
| artifacts=(os.path.join(RESULTS_DIR, "test_coverage.json"),)) | |
| verdict = "ALL_GATES_PASS" if ok else "GATES_FAILED" | |
| with open(GATES, "w", encoding="utf-8", newline="\n") as handle: | |
| json.dump({"verdict": verdict, | |
| "corpus_fingerprint": digest(os.path.join(CORPUS_DIR, "corpus.jsonl")), | |
| "gates": GATE_LOG}, handle, indent=2, sort_keys=True) | |
| handle.write("\n") | |
| print("verdict %s (%d gates, results/gates.json written)" % (verdict, len(GATE_LOG))) | |
| return 0 if ok else 1 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |