luoke-bench / ime /predict /run_predict.py
jason926's picture
luoke-bench (4745f55dec)
e39a6b5
Raw History Blame Contribute Delete
7.18 kB
#!/usr/bin/env python3
"""联想(预测下一个词)评测:调用 luoke-ime 的 engines/personal/eval_predict.py,结果存到 results/<label>/。
run_predict.py --label 1109-local 本机模型(eval_predict.py 默认的打分模型)跑全部 300 道
run_predict.py --label 1109-hub --hub <主控的 socket> 经主控的联想任务(luoke-ime.predict)续写
run_predict.py --label try --limit 3 只跑前 3 道,看能不能起来
--model DIR 换本机打分模型(传给 eval_predict.py --model)
--corpus FILE 换题文件(默认 sets/predict.tsv)
luoke-ime 的位置:环境变量 LUOKE_IME,默认 luoke-bench 旁边的 ../luoke-ime。
eval_predict.py 只读题的类别、前文、正确结果三列:把前文交给模型接着写,按个人化组件挑联想的办法(personal.picked)取前三个,
看正确结果是不是以某个联想开头。它对几个把握门槛分别报给出联想的比例、第一个对、前三个有对;这里再按类别算一遍(用它 --result 的逐条结果)。
results/<label>/ 里:
report.txt eval_predict.py 的标准输出(各门槛的总分)
stderr.txt 它的标准错误(进度、出错原因)
dump.jsonl 每道的前文末尾、正确结果、模型给的说法(--dump)
result.json luoke-core V1 证据格式(--result,带逐条的类别和对错,不带原文)
by_category.md 按类别的分数(现在用的门槛)
run.json 这次怎么跑的:命令、luoke-ime 的提交、题文件的哈希、开始结束时间、退出码
只用标准库,兼容 Python 3.9。
"""
import argparse
import collections
import hashlib
import json
import os
import subprocess
import sys
import time
HERE = os.path.dirname(os.path.abspath(__file__))
BENCH = os.path.normpath(os.path.join(HERE, "..", ".."))
NOT_EVALUATED = 3 # eval_predict.py 的退出码:没评成(主控拒了、一直没就绪)
def luoke_ime():
return os.path.abspath(os.environ.get("LUOKE_IME") or os.path.join(BENCH, "..", "luoke-ime"))
def git_head(path):
try:
out = subprocess.run(["git", "-C", path, "rev-parse", "--short", "HEAD"], capture_output=True, text=True, timeout=10)
dirty = subprocess.run(["git", "-C", path, "status", "--porcelain"], capture_output=True, text=True, timeout=10)
return out.stdout.strip() + ("+改动" if dirty.stdout.strip() else "")
except (OSError, subprocess.SubprocessError):
return None
def sha256(path):
h = hashlib.sha256()
with open(path, "rb") as f:
h.update(f.read())
return h.hexdigest()
def by_category(result_path, out_path):
"""按类别汇总 --result 里的逐条结果(门槛是 eval_predict.py 现在用的那个)。"""
with open(result_path, encoding="utf-8") as f:
res = json.load(f)
tally = collections.OrderedDict()
for it in res.get("items", []):
t = tally.setdefault(it.get("category"), [0, 0, 0, 0])
t[0] += 1
t[1] += bool(it.get("shown"))
t[2] += bool(it.get("top1"))
t[3] += bool(it.get("top3"))
gate = (res.get("score") or {}).get("gate")
lines = ["# 联想按类别(门槛 %s)" % gate, "",
"| 类别 | 题数 | 给出联想 | 给出时第一个对 | 给出时前三个有对 | 所有题里前三个有对 |", "|---|---|---|---|---|---|"]
for cat, (n, shown, top1, top3) in tally.items():
lines.append("| %s | %d | %.1f%% | %.1f%% | %.1f%% | %.1f%% |" % (
cat, n, 100.0 * shown / n, 100.0 * top1 / max(shown, 1), 100.0 * top3 / max(shown, 1), 100.0 * top3 / n))
with open(out_path, "w", encoding="utf-8") as f:
f.write("\n".join(lines) + "\n")
return "\n".join(lines)
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--label", required=True, help="这次跑的名字,结果放 results/<label>/")
ap.add_argument("--corpus", default=os.path.join(HERE, "sets", "predict.tsv"))
ap.add_argument("--limit", type=int)
ap.add_argument("--model", metavar="DIR", help="本机打分模型的目录(不写用 eval_predict.py 的默认)")
ap.add_argument("--hub", metavar="SOCKET", help="经这个主控续写(必须写明)")
ap.add_argument("--python", default=sys.executable, help="跑 eval_predict.py 的 Python(默认就是跑本脚本的这个)")
ap.add_argument("--force", action="store_true", help="results/<label>/ 已经有东西时照样覆盖")
args = ap.parse_args()
ime = luoke_ime()
script = os.path.join(ime, "engines", "personal", "eval_predict.py")
if not os.path.exists(script):
ap.error("找不到 %s(用环境变量 LUOKE_IME 指到 luoke-ime 的 checkout)" % script)
corpus = os.path.abspath(args.corpus)
if not os.path.exists(corpus):
ap.error("找不到题文件:%s" % corpus)
if args.label in ("", ".", "..") or os.sep in args.label:
ap.error("--label 只写一个名字,不带路径")
out = os.path.join(HERE, "results", args.label)
if os.path.isdir(out) and os.listdir(out) and not args.force:
ap.error("%s 已经有结果;换个 --label 或加 --force" % out)
os.makedirs(out, exist_ok=True)
cmd = [args.python, script, corpus, "--dump", os.path.join(out, "dump.jsonl"), "--result", os.path.join(out, "result.json")]
if args.limit:
cmd += ["--limit", str(args.limit)]
if args.model:
cmd += ["--model", args.model]
if args.hub:
cmd += ["--hub", args.hub]
run = {"label": args.label, "cmd": cmd, "luoke_ime": ime, "luoke_ime_commit": git_head(ime), "luoke_bench_commit": git_head(BENCH),
"corpus": os.path.relpath(corpus, BENCH), "corpus_sha256": sha256(corpus), "start": time.strftime("%Y-%m-%dT%H:%M:%S%z")}
print("跑:" + " ".join(cmd), flush=True)
t0 = time.time()
with open(os.path.join(out, "report.txt"), "w", encoding="utf-8") as so, open(os.path.join(out, "stderr.txt"), "w", encoding="utf-8") as se:
p = subprocess.run(cmd, cwd=os.path.dirname(script), stdout=so, stderr=se)
run.update(end=time.strftime("%Y-%m-%dT%H:%M:%S%z"), seconds=round(time.time() - t0, 1), returncode=p.returncode)
with open(os.path.join(out, "run.json"), "w", encoding="utf-8") as f:
json.dump(run, f, ensure_ascii=False, indent=1)
f.write("\n")
with open(os.path.join(out, "report.txt"), encoding="utf-8") as f:
sys.stdout.write(f.read())
if p.returncode != 0:
with open(os.path.join(out, "stderr.txt"), encoding="utf-8") as f:
tail = f.read()[-800:]
what = "没评成" if p.returncode == NOT_EVALUATED else "出错"
print("eval_predict.py %s(退出码 %d):\n%s" % (what, p.returncode, tail), file=sys.stderr)
sys.exit(p.returncode)
if os.path.exists(os.path.join(out, "result.json")):
print(by_category(os.path.join(out, "result.json"), os.path.join(out, "by_category.md")))
print("结果:" + out)
if __name__ == "__main__":
main()