File size: 11,571 Bytes
e39a6b5 | 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 | #!/usr/bin/env python3
"""Which question sets have been run on which model: one table, with the gaps showing.
python3 mail/coverage.py [--write] # --write: also save mail/results/COVERAGE.md
Rows are the question sets under mail/results/, columns the models named in mail/coverage.json (the base model of
each tier) plus any other model that has results. A cell is the latest result's headline score; "—" means never run.
Reads only the result files. Stdlib only.
"""
from __future__ import annotations
import argparse
import glob
import json
import os
HERE = os.path.dirname(os.path.abspath(__file__))
def headline(kind: str, score: dict) -> str:
"""One short score per kind of result."""
if not isinstance(score, dict) or not score:
return "?"
if kind == "triage":
parts = [f"action {score['action']}/{score['n']}"] if score.get("n") else []
if score.get("basic_n") or score.get("hard_n"):
parts.append(f"scored, all right {score.get('basic', 0) + score.get('hard', 0)}/{score.get('basic_n', 0) + score.get('hard_n', 0)}")
if score.get("watch_n"):
parts.append(f"observed, all right {score['watch']}/{score['watch_n']}")
return ", ".join(parts) or "?"
if kind == "tasks":
s = f"{score.get('ok', '?')}/{score.get('n', '?')}"
return s + (f", hard failures {score['hard_failures']}" if score.get("hard_failures") else "")
if kind == "text#summary":
return f"{score.get('summary', '?')}/{score.get('n', '?')}"
if kind == "text#reply":
return f"{score.get('reply', '?')}/{score.get('reply_n', '?')}"
if kind == "text#reason":
return f"{score.get('reason_must', '?')}/{score.get('reason_must_n', '?')}"
if kind == "bills":
return f"right {score.get('right', '?')}, wrong but caught {score.get('caught', '?')}, wrong and not caught {score.get('checked_but_wrong', '?')}"
return "?"
# One benchmark: where a question came from (a real mail, a rewrite of one, a set added later) is not reported apart. These rows are summed into one, per model, when every part has a result.
MERGED = {
"triage": ("邮件分类", ("triage/real", "triage/rewrite")),
"tasks/thread-bench": ("回复邮件·要不要回", ("tasks/thread-rw",)),
"tasks/draft-bench": ("回复邮件·写回信", ("tasks/draft",)),
"tasks/digest-read-bench": ("订阅管理·列精选", ("tasks/digest-read",)),
"tasks/digest-pick-bench": ("订阅管理·挑精选", ("tasks/digest-pick",)),
"tasks/senders-bench": ("订阅管理·退订建议", ("tasks/senders-real", "tasks/senders-rw")),
"tasks/cleanup-bench": ("收件箱清理", ("tasks/cleanup-real", "tasks/cleanup-rw")),
"tasks/learn-orgs-bench": ("邮件内容分析·来信", ("tasks/learn-orgs-rw", "tasks/learn-orgs-more")),
"tasks/learn-sent-bench": ("邮件内容分析·发出的信", ("tasks/learn-sent-rw", "tasks/learn-sent-more")),
}
# parts added later, summed in when a model has them: the cell's count (178 or 225) shows which
LATER = {"triage": ("triage/local",), "tasks/cleanup-bench": ("tasks/cleanup-local",),
"tasks/senders-bench": ("tasks/senders-local",), "tasks/learn-orgs-bench": ("tasks/learn-orgs-local",),
"tasks/learn-sent-bench": ("tasks/learn-sent-public",), "tasks/thread-bench": ("tasks/thread-public",),
"tasks/draft-bench": ("tasks/draft-public",), "tasks/digest-read-bench": ("tasks/digest-read-local",),
"tasks/digest-pick-bench": ("tasks/digest-pick-local",)}
RENAMED = {"triage/all": "triage"}
# one text result answers three steps of handling a mail; each is its own row
SPLIT = {"text": ("text#reason", "text#summary", "text#reply")}
NAMES = {"text#reason": "邮件分类·可疑理由", "text#summary": "看懂邮件·摘要", "text#reply": "回复邮件·回复要点",
"bills": "账单和数据提取", "triage/samples": "对照:luoke-mail 发布题·邮件分类"}
for _t, _n in (("cleanup", "收件箱清理"), ("senders", "订阅管理·退订建议"), ("learn-sent", "邮件内容分析·发出的信"),
("learn-orgs", "邮件内容分析·来信"), ("thread", "回复邮件·要不要回")):
NAMES[f"tasks/{_t}"] = f"对照:luoke-mail 发布题·{_n}"
# the rows in the order a user handles a mail: sort it, read it, reply, subscriptions, bills, clean up, what it says about them
ORDER = ("triage", "text#reason", "text#summary", "tasks/thread-bench", "text#reply", "tasks/draft-bench",
"tasks/digest-read-bench", "tasks/digest-pick-bench", "tasks/senders-bench", "bills", "tasks/cleanup-bench",
"tasks/learn-orgs-bench", "tasks/learn-sent-bench")
# a part a model has run without the rest stays its own row, under the set it belongs to
PARENT = {p: row for row, (_, parts) in MERGED.items() for p in parts + LATER.get(row, ())}
for _p, _row in PARENT.items():
NAMES[_p] = f"{MERGED[_row][0]}(只跑了 {_p.split('/')[-1]})"
def add_scores(kind: str, scores: list) -> dict:
"""The parts' scores summed, for the fields the headline reads."""
keys = ("watch", "watch_n") if kind == "triage" else ("ok", "n", "hard_failures")
return {k: sum(int(sc.get(k) or 0) for sc in scores) for k in keys}
def merge(raw: dict) -> dict:
"""{row: {model: (date, label, score dict, machine)}} -> the same with the parts of one set summed. A model with
only some parts keeps them as separate rows, so nothing is shown as more complete than it is."""
out = {RENAMED.get(r, r): dict(cells) for r, cells in raw.items()}
for row, (_, parts) in MERGED.items():
kind = row.split("/")[0]
for m in {m for p in parts for m in out.get(p, {})}:
cells = [out.get(p, {}).get(m) for p in parts]
if row in out and m in out[row]:
continue # a run of the whole set (triage --set all) wins
if all(cells):
used = parts + tuple(p for p in LATER.get(row, ()) if out.get(p, {}).get(m))
cells = [out[p][m] for p in used]
dates = sorted({c[0] for c in cells})
out.setdefault(row, {})[m] = (dates[-1] if len(dates) == 1 else f"{dates[0]}–{dates[-1]}",
"+".join(c[1] for c in cells), add_scores(kind, [c[2] for c in cells]),
"、".join(sorted({c[3] for c in cells if c[3]})))
for p in used:
del out[p][m]
return {r: c for r, c in out.items() if c}
def machine(m) -> str:
"""The machine a result was run on, short: 'M3 Ultra 256 GB'. Empty when the result does not say."""
if not isinstance(m, dict) or not m.get("cpu"):
return ""
cpu = str(m["cpu"]).replace("Apple ", "")
gb = m.get("memory_gb")
return cpu + (f" {int(gb)} GB" if isinstance(gb, (int, float)) else "")
def thinking(d: dict) -> bool:
"""A run with the model's thinking on: its own column, since the app asks with it off (recipe: think false)."""
notes = ((d.get("run") or {}).get("notes") or {}) if isinstance(d.get("run"), dict) else {}
return str(notes.get("thinking", "")).lower() in ("on", "true", "1") or d.get("think") is True
def collect(results_dir: str) -> dict:
"""{row: {model: (date, label, score text, machine)}}, keeping the latest result per row and model.
Two results of one day: the one whose file name sorts later wins (the date has no time in it)."""
table: dict = {}
for path in sorted(glob.glob(os.path.join(results_dir, "**", "*.json"), recursive=True)):
rel = os.path.relpath(path, results_dir).split(os.sep)
kind = rel[0]
if kind == "engine":
continue # engine comparisons are not baselines
row = "/".join(rel[:-1])
try:
with open(path, encoding="utf-8") as f:
d = json.load(f)
except ValueError:
continue
if not isinstance(d, dict) or not d.get("model"):
continue
cell = (str(d.get("date", "")), d.get("label") or os.path.basename(path)[:-5], d.get("score"), machine(d.get("machine")))
col = d["model"] + ("(开思考)" if thinking(d) else "")
cur = table.setdefault(row, {}).get(col)
if cur is None or cell[0] >= cur[0]:
table[row][col] = cell
merged = merge(table)
for row, parts in SPLIT.items():
if row in merged:
cells = merged.pop(row)
for p in parts:
merged[p] = dict(cells)
return {row: {m: (c[0], c[1], headline(row.split("/")[0], c[2]), c[3]) for m, c in cells.items()}
for row, cells in merged.items()}
def render(table: dict, tiers: dict) -> str:
wanted = list(dict.fromkeys(tiers.values()))
models = wanted + sorted({m for cells in table.values() for m in cells} - set(wanted))
by_model = {m: [t for t, x in tiers.items() if x == m] for m in models}
# "the model the tier uses", not "run on a machine of that tier": the machine is in each cell
head = [m + (f"({'、'.join(by_model[m])} 档用的模型)" if by_model[m] else "") for m in models]
lines = ["| 题 | " + " | ".join(head) + " |", "|---|" + "---|" * len(models)]
missing = 0
def place(r):
name = MERGED.get(r, (NAMES.get(r, r),))[0]
at = PARENT.get(r, r)
return (ORDER.index(at) if at in ORDER else len(ORDER), name.startswith("对照"), r in PARENT, r)
for row in sorted(table, key=place):
cells = []
for m in models:
c = table[row].get(m)
if c is None:
cells.append("—")
missing += m in wanted
else:
cells.append(f"{c[2]}({','.join(x for x in (c[0], c[3]) if x)})")
name = MERGED.get(row, (NAMES.get(row),))[0] or row
lines.append(f"| {name} | " + " | ".join(cells) + " |")
lines.append("")
lines.append(f"{len(table)} 套题;档位用的模型里还没跑过的格子 {missing} 个。")
machines = sorted({c[3] for cells in table.values() for c in cells.values() if c[3]})
sizes = {int(x.split()[-2]) for x in machines if x.endswith(" GB") and x.split()[-2].isdigit()}
untested = [t for t in tiers if t.isdigit() and int(t) not in sizes]
lines.append("")
lines.append("每格括号里是日期和跑的机器" + (f"({'、'.join(machines)})" if machines else "") + "。表头的档位说的是那一档用这个模型,"
"不是在那一档内存的机器上跑过。" + (f"还没有在 {'、'.join(untested)} GB 的机器上跑出来的结果。" if untested else ""))
return "\n".join(lines) + "\n"
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--write", action="store_true")
ap.add_argument("--results", default=os.path.join(HERE, "results"))
a = ap.parse_args()
with open(os.path.join(HERE, "coverage.json"), encoding="utf-8") as f:
tiers = json.load(f)["tiers"]
text = render(collect(a.results), tiers)
print(text)
if a.write:
with open(os.path.join(a.results, "COVERAGE.md"), "w", encoding="utf-8") as f:
f.write("# 邮件:哪些题在哪个模型上跑过\n\n`python3 mail/coverage.py --write` 生成,别手改。每格是最近一次结果的主要分数。\n\n" + text)
if __name__ == "__main__":
main()
|