judge_variance.py

scripts/judge_variance.py

Measure the judge's per-decision FLIP RATE against answers a run already froze.

_candidates

list[dict] judge_variance._candidates(Path answers)

Every ruled verdict decision in a run, paired with its answer prose.

scripts/judge_variance.py:65

Show on the map →

Called by cmd_sample

Calls none

Source · 34 lines
def _candidates(answers: Path) -> list[dict]:
    """A decision whose `hit` is null was never ruled — including it would measure the transport
    rather than the judge.

    @brief Judged pairs from a run.
    @return Candidates.
    @version 2
    """
    out: list[dict] = []
    for sidecar in sorted(answers.glob("*.grade.json")):
        prose = answers / f"{sidecar.name.removesuffix('.grade.json')}.md"
        if not prose.is_file():
            continue
        answer = prose.read_text(encoding="utf-8")
        if len(answer) < MIN_ANSWER_CHARS:
            continue
        doc = json.loads(sidecar.read_text(encoding="utf-8"))
        for i, decision in enumerate(doc.get("decisions") or []):
            if decision.get("kind") not in VERDICT_KINDS or decision.get("hit") is None:
                continue
            out.append(
                {
                    "cell": doc.get("cell", sidecar.stem),
                    "index": i,
                    "kind": decision["kind"],
                    "mark": decision.get("mark", ""),
                    "recorded": "HIT" if decision["hit"] else "MISS",
                    "model": doc.get("judge_model", ""),
                    "answer": answer,
                }
            )
    return out

Activity · 14 steps
lines 73–73out: list[dict] = []lines 74–74◇ for sidecar in sorted(answers.glob("*.grade.json"))lines 75–75prose = answers / f"{sidecar.name.removesuffix('.grade.json')}.md"lines 76–76◇ if not prose.is_file()lines 77–77continuelines 78–78answer = prose.read_text(encoding="utf-8")lines 79–79◇ if len(answer) < MIN_ANSWER_CHARSlines 80–80continuelines 81–81doc = json.loads(sidecar.read_text(encoding="utf-8"))lines 82–82◇ for i, decision in enumerate(doc.get("decisions") or [])lines 83–83◇ if decision.get("kind") not in VERDICT_KINDS or decision.get("hit") is Nonelines 84–84continuelines 85–95out.append( { "cell": doc.get("cell", sidecar.stem), "index": i, "kind": decision["kind"], "mark": decision.get("mark", ""), "recorded": "HIT" if decision["hit"] else "MISS", "model": doc.get("judge_model", ""), "answer": answer, } )lines 96–96return out

Flows

cmd_report

int judge_variance.cmd_report()

Report the flip rate, split by mark kind, errors separate.

scripts/judge_variance.py:217

Show on the map →

Called by main

Calls none

Source · 61 lines
def cmd_report() -> int:
    """A pair FLIPPED if its successful verdicts are not unanimous. Errors are excluded from the
    unanimity test and counted on their own line — treating an error as a verdict turns flaky
    infrastructure into a result.

    DIRECTION IS PRINTED, because it is the whole interpretation. A symmetric drift against the
    recorded verdicts is judge noise; a ONE-WAY drift is a CHANGE — the prompt, the model or the
    input differs from whatever produced the recorded verdict, and the number is not variance at
    all. That distinction is what caught this file's own first version.

    @brief Report judge variance.
    @return Exit code.
    @version 2
    """
    if not RESULTS.is_file():
        print(f"REFUSING: no results at {RESULTS} — run `run` first", file=sys.stderr)
        return 2
    rows = [json.loads(x) for x in RESULTS.read_text(encoding="utf-8").splitlines() if x]
    by_pair: dict[tuple, list[dict]] = defaultdict(list)
    for row in rows:
        by_pair[(row["cell"], row["index"])].append(row)

    stats: dict[str, Counter] = defaultdict(Counter)
    errors = sum(1 for r in rows if not r.get("verdict"))
    for reps in by_pair.values():
        kind = reps[0]["kind"]
        good = [r["verdict"] for r in reps if r["verdict"]]
        if not good:
            stats[kind]["all_errored"] += 1
            continue
        stats[kind]["pairs"] += 1
        if len(set(good)) > 1:
            stats[kind]["flipped"] += 1
        majority = Counter(good).most_common(1)[0][0]
        recorded = reps[0]["recorded"]
        if majority != recorded:
            stats[kind][f"{recorded}->{majority}"] += 1

    rate = errors / max(1, len(rows))
    print(f"calls: {len(rows)}   transport/parse errors: {errors} ({rate:.1%})")
    print(f"\n{'kind':<12} {'pairs':>6} {'flipped':>8} {'flip rate':>10}")
    for kind in VERDICT_KINDS:
        s = stats.get(kind) or Counter()
        if not s["pairs"]:
            print(f"{kind:<12} {0:>6}   — no pairs measured")
            continue
        print(f"{kind:<12} {s['pairs']:>6} {s['flipped']:>8} {s['flipped'] / s['pairs']:>9.1%}")
        if s["MISS->HIT"] or s["HIT->MISS"]:
            print(f"{'':<12} vs recorded: MISS->HIT {s['MISS->HIT']}  HIT->MISS {s['HIT->MISS']}")
        if s["all_errored"]:
            print(f"{'':<12} {s['all_errored']} pair(s) errored on every rep — NOT flips")
    pairs = sum(s["pairs"] for s in stats.values())
    flips = sum(s["flipped"] for s in stats.values())
    if pairs and not flips:
        print(
            f"\n0 flips in {pairs} pairs bounds the rate at ~<={3 / pairs:.1%} at 95% confidence "
            f"(rule of three). It does NOT show the rate is zero."
        )
    return 0

Activity · 40 steps
lines 231–231◇ if not RESULTS.is_file()lines 232–232print(f"REFUSING: no results at {RESULTS} — run `run` first", file=sys.stderr)lines 233–233return 2lines 234–234rows = [json.loads(x) for x in RESULTS.read_text(encoding="utf-8").splitlines() if x]lines 235–235by_pair: dict[tuple, list[dict]] = defaultdict(list)lines 236–236◇ for row in rowslines 237–237by_pair[(row["cell"], row["index"])].append(row)lines 239–239stats: dict[str, Counter] = defaultdict(Counter)lines 240–240errors = sum(1 for r in rows if not r.get("verdict"))lines 241–241◇ for reps in by_pair.values()lines 242–242kind = reps[0]["kind"]lines 243–243good = [r["verdict"] for r in reps if r["verdict"]]lines 244–244◇ if not goodlines 245–245stats[kind]["all_errored"] += 1lines 246–246continuelines 247–247stats[kind]["pairs"] += 1lines 248–248◇ if len(set(good)) > 1lines 249–249stats[kind]["flipped"] += 1lines 250–250majority = Counter(good).most_common(1)[0][0]lines 251–251recorded = reps[0]["recorded"]lines 252–252◇ if majority != recordedlines 253–253stats[kind][f"{recorded}->{majority}"] += 1lines 255–255rate = errors / max(1, len(rows))lines 256–256print(f"calls: {len(rows)} transport/parse errors: {errors} ({rate:.1%})")lines 257–257print(f"\n{'kind':<12} {'pairs':>6} {'flipped':>8} {'flip rate':>10}")lines 258–258◇ for kind in VERDICT_KINDSlines 259–259s = stats.get(kind) or Counter()lines 260–260◇ if not s["pairs"]lines 261–261print(f"{kind:<12} {0:>6} — no pairs measured")lines 262–262continuelines 263–263print(f"{kind:<12} {s['pairs']:>6} {s['flipped']:>8} {s['flipped'] / s['pairs']:>9.1%}")lines 264–264◇ if s["MISS->HIT"] or s["HIT->MISS"]lines 265–265print(f"{'':<12} vs recorded: MISS->HIT {s['MISS->HIT']} HIT->MISS {s['HIT->MISS']}")lines 266–266◇ if s["all_errored"]lines 267–267print(f"{'':<12} {s['all_errored']} pair(s) errored on every rep — NOT flips")lines 268–268pairs = sum(s["pairs"] for s in stats.values())lines 269–269flips = sum(s["flipped"] for s in stats.values())lines 270–270◇ if pairs and not flipslines 271–274print( f"\n0 flips in {pairs} pairs bounds the rate at ~<={3 / pairs:.1%} at 95% confidence " f"(rule of three). It does NOT show the rate is zero." )lines 275–275return 0

Flows

cmd_run

int judge_variance.cmd_run(int k)

Re-judge every sampled pair k times, appending as results land.

scripts/judge_variance.py:158

Source · 56 lines
def cmd_run(k: int) -> int:
    """Append-only JSONL, so an interrupted run keeps everything already paid for. Each call is
    a fresh tool-less process with no memory of the last, which is what makes repeats a variance
    measurement rather than a conversation.

    @brief Re-judge the sample.
    @return Exit code.
    @version 2
    """
    if not MANIFEST.is_file():
        print(f"REFUSING: no manifest at {MANIFEST} — run `sample` first", file=sys.stderr)
        return 2
    sample = json.loads(MANIFEST.read_text(encoding="utf-8"))["sample"]
    done: set[str] = set()
    if RESULTS.is_file():
        for line in RESULTS.read_text(encoding="utf-8").splitlines():
            try:
                row = json.loads(line)
            except json.JSONDecodeError:
                continue
            done.add(f"{row['cell']}#{row['index']}#{row['rep']}")

    jobs = [
        (item, rep)
        for item in sample
        for rep in range(k)
        if f"{item['cell']}#{item['index']}#{rep}" not in done
    ]
    print(f"{len(sample)} pairs x {k} reps = {len(sample) * k} calls; {len(jobs)} remaining")

    def one(job: tuple[dict, int]) -> dict:
        item, rep = job
        reply = judge.ask(
            judge.verdict_prompt(item["mark"], judge.anonymise(item["answer"])), item["model"]
        )
        verdict = None if reply.error else judge.read_verdict(reply.text)
        return {
            "cell": item["cell"],
            "index": item["index"],
            "kind": item["kind"],
            "recorded": item["recorded"],
            "rep": rep,
            "verdict": verdict,
            "error": reply.error or ("unparseable" if verdict is None else ""),
        }

    with RESULTS.open("a", encoding="utf-8") as fh, ThreadPoolExecutor(WORKERS) as pool:
        for i, row in enumerate(pool.map(one, jobs), 1):
            fh.write(json.dumps(row) + "\n")
            fh.flush()
            if i % 10 == 0:
                print(f"  {i}/{len(jobs)}")
    print(f"wrote -> {RESULTS.relative_to(REPO)}")
    return 0

Activity · 23 steps
lines 167–167◇ if not MANIFEST.is_file()lines 168–168print(f"REFUSING: no manifest at {MANIFEST} — run `sample` first", file=sys.stderr)lines 169–169return 2lines 170–170sample = json.loads(MANIFEST.read_text(encoding="utf-8"))["sample"]lines 171–171done: set[str] = set()lines 172–172◇ if RESULTS.is_file()lines 173–173◇ for line in RESULTS.read_text(encoding="utf-8").splitlines()lines 174–174trylines 175–175row = json.loads(line)lines 176–176except json.JSONDecodeErrorlines 177–177continuelines 178–178done.add(f"{row['cell']}#{row['index']}#{row['rep']}")lines 180–185jobs = [ (item, rep) for item in sample for rep in range(k) if f"{item['cell']}#{item['index']}#{rep}" not in done ]lines 186–186print(f"{len(sample)} pairs x {k} reps = {len(sample) * k} calls; {len(jobs)} remaining")lines 188–202def one(job: tuple[dict, int]) -> dict: item, rep = job reply = judge.ask( judge.verdict_prompt(item["mark"], judge.anonymise(item["answer"])), item["model"] ) verdict = None if reply.error else judge.read_verdict(reply.text) return { "cell": item["cell"], "index": item["index"], "kind": item["kind"], "recorded": item["recorded"], "rep": rep, "verdict": verdict, "error": reply.error or ("unparseable" if verdict is None else ""), }lines 204–204with RESULTS.open("a", encoding="utf-8") as fh, ThreadPoolExecutor(WORKERS) as poollines 205–205◇ for i, row in enumerate(pool.map(one, jobs), 1)lines 206–206fh.write(json.dumps(row) + "\n")lines 207–207fh.flush()lines 208–208◇ if i % 10 == 0lines 209–209print(f" {i}/{len(jobs)}")lines 210–210print(f"wrote -> {RESULTS.relative_to(REPO)}")lines 211–211return 0

Flows

cmd_sample

int judge_variance.cmd_sample(Path answers, int n, int seed)

Choose a stratified sample and write the manifest.

scripts/judge_variance.py:105

Source · 49 lines
def cmd_sample(answers: Path, n: int, seed: int) -> int:
    """Stratified by mark kind, because the split IS the finding. An unstratified sample is
    dominated by whichever kind is commoner and reports one blended rate — the number least
    useful for deciding what the schema must carry.

    @brief Write a stratified sample.
    @return Exit code.
    @version 2
    """
    pool = _candidates(answers)
    if not pool:
        print(f"REFUSING: no ruled verdict decisions under {answers}", file=sys.stderr)
        return 2
    rng = random.Random(seed)
    by_kind: dict[str, list[dict]] = defaultdict(list)
    for item in pool:
        by_kind[item["kind"]].append(item)

    half = max(1, n // len(VERDICT_KINDS))
    chosen: list[dict] = []
    for kind in VERDICT_KINDS:
        bucket = by_kind.get(kind) or []
        rng.shuffle(bucket)
        take = bucket[:half]
        chosen.extend(take)
        if len(take) < half:
            print(f"NOTE: only {len(take)} {kind} pairs available, wanted {half} — disclosed")

    OUT.mkdir(parents=True, exist_ok=True)
    MANIFEST.write_text(
        json.dumps(
            {
                "answers": str(answers),
                "seed": seed,
                "requested": n,
                "pool": {k: len(v) for k, v in by_kind.items()},
                "sample": chosen,
            },
            indent=2,
        ),
        encoding="utf-8",
    )
    print(
        f"pool: {len(pool)} ruled verdict decisions  { ({k: len(v) for k, v in by_kind.items()}) }"
    )
    print(f"sampled: {len(chosen)} -> {MANIFEST.relative_to(REPO)}")
    return 0

Activity · 22 steps
lines 114–114pool = _candidates(answers)lines 115–115◇ if not poollines 116–116print(f"REFUSING: no ruled verdict decisions under {answers}", file=sys.stderr)lines 117–117return 2lines 118–118rng = random.Random(seed)lines 119–119by_kind: dict[str, list[dict]] = defaultdict(list)lines 120–120◇ for item in poollines 121–121by_kind[item["kind"]].append(item)lines 123–123half = max(1, n // len(VERDICT_KINDS))lines 124–124chosen: list[dict] = []lines 125–125◇ for kind in VERDICT_KINDSlines 126–126bucket = by_kind.get(kind) or []lines 127–127rng.shuffle(bucket)lines 128–128take = bucket[:half]lines 129–129chosen.extend(take)lines 130–130◇ if len(take) < halflines 131–131print(f"NOTE: only {len(take)} {kind} pairs available, wanted {half} — disclosed")lines 133–133OUT.mkdir(parents=True, exist_ok=True)lines 134–146MANIFEST.write_text( json.dumps( { "answers": str(answers), "seed": seed, "requested": n, "pool": {k: len(v) for k, v in by_kind.items()}, "sample": chosen, }, indent=2, ), encoding="utf-8", )lines 147–149print( f"pool: {len(pool)} ruled verdict decisions { ({k: len(v) for k, v in by_kind.items()}) }" )lines 150–150print(f"sampled: {len(chosen)} -> {MANIFEST.relative_to(REPO)}")lines 151–151return 0

Flows

main

int judge_variance.main()

CLI entry point.

scripts/judge_variance.py:281

Source · 22 lines
def main() -> int:
    """@brief Dispatch subcommands.
    @return Exit code.
    @version 2
    """
    parser = argparse.ArgumentParser(description=__doc__)
    sub = parser.add_subparsers(dest="cmd", required=True)
    s = sub.add_parser("sample")
    s.add_argument("--answers", type=Path, required=True)
    s.add_argument("--n", type=int, default=40)
    s.add_argument("--seed", type=int, default=7)
    r = sub.add_parser("run")
    r.add_argument("--k", type=int, default=3)
    sub.add_parser("report")
    args = parser.parse_args()
    if args.cmd == "sample":
        return cmd_sample(args.answers, args.n, args.seed)
    if args.cmd == "run":
        return cmd_run(args.k)
    return cmd_report()

Activity · 15 steps
lines 286–286parser = argparse.ArgumentParser(description=__doc__)lines 287–287sub = parser.add_subparsers(dest="cmd", required=True)lines 288–288s = sub.add_parser("sample")lines 289–289s.add_argument("--answers", type=Path, required=True)lines 290–290s.add_argument("--n", type=int, default=40)lines 291–291s.add_argument("--seed", type=int, default=7)lines 292–292r = sub.add_parser("run")lines 293–293r.add_argument("--k", type=int, default=3)lines 294–294sub.add_parser("report")lines 295–295args = parser.parse_args()lines 296–296◇ if args.cmd == "sample"lines 297–297return cmd_sample(args.answers, args.n, args.seed)lines 298–298◇ if args.cmd == "run"lines 299–299return cmd_run(args.k)lines 300–300return cmd_report()

Flows