gate_figures.py

scripts/gate_figures.py

The per-repo acceptance gate, as `acceptance/runs/1.4.0-pending/PRE-REGISTRATION.md` states it.

_scores

dict[str, dict[str, list[float]]] gate_figures._scores(Path run, str target)

Ruled scores per (question, arm) for one target, in points.

scripts/gate_figures.py:60

Source · 12 lines
def _scores(run: Path, target: str) -> dict[str, dict[str, list[float]]]:
    """@brief Collect scores; a null score is excluded. @return Scores."""
    out: dict[str, dict[str, list[float]]] = defaultdict(lambda: defaultdict(list))
    for path in (run / target / "answers").glob("*.grade.json"):
        grade = json.loads(path.read_text(encoding="utf-8"))
        score = grade.get("score")
        if score is not None:
            question = path.name.split("_")[0]
            out[question][grade["arm"]].append(100 * score if score <= 1 else score)
    return out

Activity · 8 steps
lines 62–62out: dict[str, dict[str, list[float]]] = defaultdict(lambda: defaultdict(list))lines 63–63◇ for path in (run / target / "answers").glob("*.grade.json")lines 64–64grade = json.loads(path.read_text(encoding="utf-8"))lines 65–65score = grade.get("score")lines 66–66◇ if score is not Nonelines 67–67question = path.name.split("_")[0]lines 68–68out[question][grade["arm"]].append(100 * score if score <= 1 else score)lines 69–69return out

Flows

_tokens

dict[str, int] gate_figures._tokens(Path run, str target)

Summed total tokens per arm for one target.

scripts/gate_figures.py:46

Source · 9 lines
def _tokens(run: Path, target: str) -> dict[str, int]:
    """@brief Sum tokens per arm. @return Totals."""
    total: dict[str, int] = defaultdict(int)
    for path in (run / target / "answers").glob("*.meta.json"):
        meta = json.loads(path.read_text(encoding="utf-8"))
        total[meta["arm"]] += sum(int(meta.get(k) or 0) for k in _TOKEN_KEYS)
    return dict(total)

Activity · 5 steps
lines 48–48total: dict[str, int] = defaultdict(int)lines 49–49◇ for path in (run / target / "answers").glob("*.meta.json")lines 50–50meta = json.loads(path.read_text(encoding="utf-8"))lines 51–51total[meta["arm"]] += sum(int(meta.get(k) or 0) for k in _TOKEN_KEYS)lines 52–52return dict(total)

Flows

gate

tuple[bool, bool] gate_figures.gate(dict comparator, dict candidate)

The pre-registered gate for one repo's index_only arm.

scripts/gate_figures.py:103

Show on the map →

Called by main, test_the_gate_is_cost_lower_and_quality_within_tolerance

Calls none

Source · 7 lines
def gate(comparator: dict, candidate: dict) -> tuple[bool, bool]:
    """@brief Cost strictly lower; quality within the tolerance. @return Both verdicts."""
    cost = candidate["tokens_pct"] < comparator["tokens_pct"]
    quality = candidate["separation"] >= comparator["separation"] - TOLERANCE
    return cost, quality

Activity · 3 steps
lines 105–105cost = candidate["tokens_pct"] < comparator["tokens_pct"]lines 106–106quality = candidate["separation"] >= comparator["separation"] - TOLERANCElines 107–107return cost, quality

Flows

main

int gate_figures.main(Path run, Path|None comparator=None)

Print the per-repo table for a candidate run, against a comparator run when given.

scripts/gate_figures.py:135

Show on the map →

Called by test_a_standalone_run_prints_figures_and_no_verdict

Calls gate, repo_figures, standalone

Source · 29 lines
def main(run: Path, comparator: Path | None = None) -> int:
    """@brief Print the gate, or figures only. @return 0 or 1."""
    if comparator is None:
        return standalone(run)
    passed = True
    print(
        f"{'repo':10} {'arm':10} {'tok cmp':>8} {'tok new':>8} {'sep cmp':>8} {'sep new':>8}  gate"
    )
    for target in TARGETS:
        old, new = repo_figures(comparator, target), repo_figures(run, target)
        for arm in ARMS:
            a, b = old[arm], new[arm]
            verdict = ""
            if arm == "index_only":
                cost, quality = gate(a, b)
                passed &= cost and quality
                verdict = ("PASS" if cost and quality else "MISS") + (
                    f" (cost {'ok' if cost else 'miss'}, quality {'ok' if quality else 'miss'})"
                )
            print(
                f"{target:10} {arm:10} {a['tokens_pct']:+7.1f}% {b['tokens_pct']:+7.1f}% "
                f"{a['separation']:+8.2f} {b['separation']:+8.2f}  {verdict}"
            )
        drift = new["baseline_mean"] - old["baseline_mean"]
        tok = 100 * (new["baseline_tokens"] / old["baseline_tokens"] - 1)
        print(f"{target:10} baseline drift {drift:+.2f} pt, tokens {tok:+.1f}%")
    return 0 if passed else 1

Activity · 18 steps
lines 137–137◇ if comparator is Nonelines 138–138return standalone(run)lines 139–139passed = Truelines 140–142print( f"{'repo':10} {'arm':10} {'tok cmp':>8} {'tok new':>8} {'sep cmp':>8} {'sep new':>8} gate" )lines 143–143◇ for target in TARGETSlines 144–144old, new = repo_figures(comparator, target), repo_figures(run, target)lines 145–145◇ for arm in ARMSlines 146–146a, b = old[arm], new[arm]lines 147–147verdict = ""lines 148–148◇ if arm == "index_only"lines 149–149cost, quality = gate(a, b)lines 150–150passed &= cost and qualitylines 151–153verdict = ("PASS" if cost and quality else "MISS") + ( f" (cost {'ok' if cost else 'miss'}, quality {'ok' if quality else 'miss'})" )lines 154–157print( f"{target:10} {arm:10} {a['tokens_pct']:+7.1f}% {b['tokens_pct']:+7.1f}% " f"{a['separation']:+8.2f} {b['separation']:+8.2f} {verdict}" )lines 158–158drift = new["baseline_mean"] - old["baseline_mean"]lines 159–159tok = 100 * (new["baseline_tokens"] / old["baseline_tokens"] - 1)lines 160–160print(f"{target:10} baseline drift {drift:+.2f} pt, tokens {tok:+.1f}%")lines 161–161return 0 if passed else 1

Flows

repo_figures

dict gate_figures.repo_figures(Path run, str target)

Token % and separation per arm for one target, plus baseline mean.

scripts/gate_figures.py:77

Show on the map →

Called by main, standalone, test_reproduces_the_published_1_3_0_final_figures

Calls _scores, _tokens

Source · 21 lines
def repo_figures(run: Path, target: str) -> dict:
    """@brief One repo's figures. @return Figures."""
    tokens, scores = _tokens(run, target), _scores(run, target)
    out: dict = {
        "baseline_mean": st.mean(x for q in scores.values() for x in q["baseline"]),
        "baseline_tokens": tokens["baseline"],
    }
    for arm in ARMS:
        seps = {
            q: st.mean(v[arm]) - st.mean(v["baseline"])
            for q, v in scores.items()
            if v.get(arm) and v.get("baseline")
        }
        out[arm] = {
            "tokens_pct": 100 * (tokens[arm] / tokens["baseline"] - 1),
            "separation": st.mean(seps.values()),
            "clusters": dict(sorted(seps.items())),
        }
    return out

Activity · 6 steps
lines 79–79tokens, scores = _tokens(run, target), _scores(run, target)lines 80–83out: dict = { "baseline_mean": st.mean(x for q in scores.values() for x in q["baseline"]), "baseline_tokens": tokens["baseline"], }lines 84–84◇ for arm in ARMSlines 85–89seps = { q: st.mean(v[arm]) - st.mean(v["baseline"]) for q, v in scores.items() if v.get(arm) and v.get("baseline") }lines 90–94out[arm] = { "tokens_pct": 100 * (tokens[arm] / tokens["baseline"] - 1), "separation": st.mean(seps.values()), "clusters": dict(sorted(seps.items())), }lines 95–95return out

Flows

standalone

int gate_figures.standalone(Path run)

Print one run's per-repo figures with no comparator and no verdict.

scripts/gate_figures.py:114

Source · 15 lines
def standalone(run: Path) -> int:
    """@brief Print figures only, per repo, arm and question. @return 0."""
    print(f"{'repo':10} {'arm':10} {'tokens':>8} {'sep':>8}  per question")
    for target in TARGETS:
        fig = repo_figures(run, target)
        for arm in ARMS:
            a = fig[arm]
            per_q = "  ".join(f"{q} {v:+.2f}" for q, v in a["clusters"].items())
            print(f"{target:10} {arm:10} {a['tokens_pct']:+7.1f}% {a['separation']:+8.2f}  {per_q}")
        print(
            f"{target:10} baseline mean {fig['baseline_mean']:.2f}, tokens {fig['baseline_tokens']}"
        )
    return 0

Activity · 9 steps
lines 116–116print(f"{'repo':10} {'arm':10} {'tokens':>8} {'sep':>8} per question")lines 117–117◇ for target in TARGETSlines 118–118fig = repo_figures(run, target)lines 119–119◇ for arm in ARMSlines 120–120a = fig[arm]lines 121–121per_q = " ".join(f"{q} {v:+.2f}" for q, v in a["clusters"].items())lines 122–122print(f"{target:10} {arm:10} {a['tokens_pct']:+7.1f}% {a['separation']:+8.2f} {per_q}")lines 123–125print( f"{target:10} baseline mean {fig['baseline_mean']:.2f}, tokens {fig['baseline_tokens']}" )lines 126–126return 0

Flows