|
| 1 | +"""Offline best-of-N picker over cached memo JSONL sets. |
| 2 | +
|
| 3 | +This script is the no-API counterpart to ``scripts/bestofn_judge.py``. It |
| 4 | +loads N candidate memo sets and picks the highest-scoring memo per |
| 5 | +``custom_id`` using only the laptop-local heuristic from |
| 6 | +:func:`yuholens.agents.memo_critic.heuristic_score` — no OpenAI calls, |
| 7 | +no GPU, no network. The intended use cases are: |
| 8 | +
|
| 9 | + * Reproducing the best-of-N pick distribution on a flight or any |
| 10 | + offline laptop without burning batch credits. |
| 11 | + * Comparing the heuristic pick distribution against the cached judge |
| 12 | + pick distribution to validate the heuristic-vs-judge agreement |
| 13 | + claim made in ``docs/blog_post.md`` and ``docs/model-card.md``. |
| 14 | + * Smoke-testing the picker contract during development before |
| 15 | + shipping a fresh judge pass. |
| 16 | +
|
| 17 | +Output schema mirrors ``scripts/bestofn_pick.py`` so the picked artefacts |
| 18 | +drop into the same downstream rescore tooling. The script also emits a |
| 19 | +pick-share summary and the heuristic mean per source set. |
| 20 | +""" |
| 21 | + |
| 22 | +from __future__ import annotations |
| 23 | + |
| 24 | +import argparse |
| 25 | +import json |
| 26 | +import statistics |
| 27 | +import sys |
| 28 | +from collections import Counter |
| 29 | +from pathlib import Path |
| 30 | +from typing import Any |
| 31 | + |
| 32 | + |
| 33 | +def _ensure_yuholens_on_path() -> None: |
| 34 | + """Insert ``src/`` into ``sys.path`` so the script runs without ``-m``.""" |
| 35 | + repo_src = Path(__file__).resolve().parents[1] / "src" |
| 36 | + if str(repo_src) not in sys.path: |
| 37 | + sys.path.insert(0, str(repo_src)) |
| 38 | + |
| 39 | + |
| 40 | +_ensure_yuholens_on_path() |
| 41 | + |
| 42 | +from yuholens.agents.memo_critic import heuristic_score # noqa: E402 |
| 43 | + |
| 44 | + |
| 45 | +def _load_memos(path: Path) -> dict[str, str]: |
| 46 | + """Load a candidate memo JSONL file as a ``custom_id -> memo`` map. |
| 47 | +
|
| 48 | + Args: |
| 49 | + path: Path to a candidate memo JSONL with ``{"custom_id", "memo"}`` |
| 50 | + rows. |
| 51 | +
|
| 52 | + Returns: |
| 53 | + Mapping keyed by ``custom_id``. Rows missing either field are |
| 54 | + skipped silently because best-of-N is robust to partial sets. |
| 55 | + """ |
| 56 | + out: dict[str, str] = {} |
| 57 | + with path.open("r", encoding="utf-8") as fh: |
| 58 | + for line in fh: |
| 59 | + line = line.strip() |
| 60 | + if not line: |
| 61 | + continue |
| 62 | + row = json.loads(line) |
| 63 | + cid = row.get("custom_id") |
| 64 | + memo = row.get("memo") |
| 65 | + if isinstance(cid, str) and isinstance(memo, str): |
| 66 | + out[cid] = memo |
| 67 | + return out |
| 68 | + |
| 69 | + |
| 70 | +def main() -> int: |
| 71 | + parser = argparse.ArgumentParser(description=__doc__) |
| 72 | + parser.add_argument( |
| 73 | + "--memos", |
| 74 | + type=Path, |
| 75 | + nargs="+", |
| 76 | + required=True, |
| 77 | + help="Candidate memos JSONL files, in priority order (ties go to first).", |
| 78 | + ) |
| 79 | + parser.add_argument("--picked-memos", type=Path, required=True) |
| 80 | + parser.add_argument("--picked-scores", type=Path, required=True) |
| 81 | + parser.add_argument( |
| 82 | + "--labels", |
| 83 | + type=str, |
| 84 | + nargs="+", |
| 85 | + default=None, |
| 86 | + help="Human-readable labels per input set; defaults to file stems.", |
| 87 | + ) |
| 88 | + args = parser.parse_args() |
| 89 | + |
| 90 | + labels = args.labels or [p.stem for p in args.memos] |
| 91 | + if len(labels) != len(args.memos): |
| 92 | + raise SystemExit("--labels length must match --memos") |
| 93 | + |
| 94 | + memo_sets: list[dict[str, str]] = [_load_memos(path) for path in args.memos] |
| 95 | + if not any(memo_sets): |
| 96 | + raise SystemExit("no memos loaded from any --memos input") |
| 97 | + |
| 98 | + cids: list[str] = sorted(set().union(*[set(m.keys()) for m in memo_sets])) |
| 99 | + picked_memos: list[dict[str, Any]] = [] |
| 100 | + picked_scores: list[dict[str, Any]] = [] |
| 101 | + pick_counter: Counter[str] = Counter() |
| 102 | + per_source_scores: dict[str, list[float]] = {label: [] for label in labels} |
| 103 | + skipped = 0 |
| 104 | + |
| 105 | + for cid in cids: |
| 106 | + best_idx: int | None = None |
| 107 | + best_score = float("-inf") |
| 108 | + for idx, memo_set in enumerate(memo_sets): |
| 109 | + memo = memo_set.get(cid) |
| 110 | + if memo is None: |
| 111 | + continue |
| 112 | + score = heuristic_score(memo) |
| 113 | + per_source_scores[labels[idx]].append(score) |
| 114 | + if score > best_score: |
| 115 | + best_idx = idx |
| 116 | + best_score = score |
| 117 | + if best_idx is None: |
| 118 | + skipped += 1 |
| 119 | + continue |
| 120 | + picked_memos.append( |
| 121 | + {"custom_id": cid, "memo": memo_sets[best_idx][cid]} |
| 122 | + ) |
| 123 | + picked_scores.append( |
| 124 | + { |
| 125 | + "custom_id": cid, |
| 126 | + "heuristic_score": round(best_score, 4), |
| 127 | + "source": labels[best_idx], |
| 128 | + } |
| 129 | + ) |
| 130 | + pick_counter[labels[best_idx]] += 1 |
| 131 | + |
| 132 | + args.picked_memos.parent.mkdir(parents=True, exist_ok=True) |
| 133 | + with args.picked_memos.open("w", encoding="utf-8") as fh: |
| 134 | + for record in picked_memos: |
| 135 | + fh.write(json.dumps(record, ensure_ascii=False) + "\n") |
| 136 | + args.picked_scores.parent.mkdir(parents=True, exist_ok=True) |
| 137 | + args.picked_scores.write_text( |
| 138 | + json.dumps(picked_scores, indent=2, ensure_ascii=False) + "\n", |
| 139 | + encoding="utf-8", |
| 140 | + ) |
| 141 | + |
| 142 | + print( |
| 143 | + f"[bestofn-offline] picked {len(picked_memos)} memos " |
| 144 | + f"(skipped {skipped})" |
| 145 | + ) |
| 146 | + for label, count in sorted(pick_counter.items()): |
| 147 | + share = count / max(len(picked_memos), 1) |
| 148 | + scores = per_source_scores[label] |
| 149 | + if scores: |
| 150 | + mean = statistics.fmean(scores) |
| 151 | + print( |
| 152 | + f" pick_share[{label}]: {count}/{len(picked_memos)} " |
| 153 | + f"({share:.1%}) source_mean_heuristic={mean:.3f}" |
| 154 | + ) |
| 155 | + else: |
| 156 | + print(f" pick_share[{label}]: {count}/{len(picked_memos)} ({share:.1%})") |
| 157 | + if picked_scores: |
| 158 | + all_picks = [r["heuristic_score"] for r in picked_scores] |
| 159 | + print( |
| 160 | + f"[bestofn-offline] picked_mean_heuristic=" |
| 161 | + f"{statistics.fmean(all_picks):.3f} " |
| 162 | + f"median={statistics.median(all_picks):.3f} " |
| 163 | + f"n={len(all_picks)}" |
| 164 | + ) |
| 165 | + print(f"[bestofn-offline] wrote picked memos -> {args.picked_memos}") |
| 166 | + print(f"[bestofn-offline] wrote picked scores -> {args.picked_scores}") |
| 167 | + return 0 |
| 168 | + |
| 169 | + |
| 170 | +if __name__ == "__main__": |
| 171 | + raise SystemExit(main()) |
0 commit comments