Download source/scripts/benchmarks/predict_ime_zh.py from Voltline/vimeml-zh-v2: direct link, hf CLI and curl.
- Browser
- Download file 16.1 kB
-
https://huggingface.co/Voltline/vimeml-zh-v2/resolve/main/source/scripts/benchmarks/predict_ime_zh.py
- Command line
-
hf download hf://Voltline/vimeml-zh-v2/source/scripts/benchmarks/predict_ime_zh.py
-
curl -L -o predict_ime_zh.py https://huggingface.co/Voltline/vimeml-zh-v2/resolve/main/source/scripts/benchmarks/predict_ime_zh.py
16.1 kB
| """Run and score the Chinese prediction benchmark ime-predict-zh-v1-r1 on development. | |
| run decode tracks A, C (both key modes) and B for one model; development only | |
| adapters: vime (vimeml-tiny-zh), hf (Hugging Face causal LM), char5 (5-gram) | |
| build-ngram the character 5-gram baseline from a fixed sample of export-r1/train | |
| score Top-k rates (A, C), keystroke savings with the tuned threshold (B), coverage (D) | |
| Protocol: docs/zh-CN/benchmarks/predict-zh-plan.md. Decoder: vimeml.benchmarks.predict_zh. | |
| The blind split is never read here. | |
| """ | |
| import argparse | |
| import json | |
| import math | |
| import subprocess | |
| import sys | |
| import time | |
| import warnings | |
| from pathlib import Path | |
| ROOT = Path(__file__).resolve().parents[2] | |
| sys.path.insert(0, str(ROOT / "src")) | |
| import torch # noqa: E402 | |
| from vimeml.benchmarks import predict_zh as P # noqa: E402 | |
| from vimeml.training.data import file_sha, write_json # noqa: E402 | |
| VERSION = "ime-predict-zh-v1-r1" | |
| FROZEN = ROOT / "outputs/benchmarks/ime-predict-zh-v1/frozen-r1" | |
| FROZEN_SHA = { | |
| "items-a.jsonl": "493fc4702b9dc37b1f645fcfdcc3efa515f840adcef7e1423c3d233b21eea87f", | |
| "messages-b.jsonl": "2640d6b573fb2e45996a7b6556a2aeafe9af3e42e96603588947ba75fb7a1c71", | |
| "items-c.jsonl": "dc88bc5f0a7e1ed2e3c0ee2e9ae7841ca2712e13a34151e293e2b205df21fb2e", | |
| "manifest.json": "002dc9a39113e1831b5d2352187a079e15705770310dc81de6e06a87e68f6415", | |
| } | |
| RIME = ROOT / "datasets/ime-standard-zh-v1/engine/rime-ice" | |
| NGRAM = ROOT / "outputs/benchmarks/ime-predict-zh-v1/baselines/char5-kn.npz" | |
| CHUNK = 2048 # jobs decoded together (each beam step of them shares the forward passes) | |
| QUANTILES = [q / 100 for q in range(5, 100, 5)] | |
| MODES = (("first_syllable", "syllable", "keys_first_syllable"), ("initials", "initials", "keys_initials")) | |
| def log(*parts): | |
| print(time.strftime("%H:%M:%S"), *parts, file=sys.stderr, flush=True) | |
| def development(name, limit): | |
| rows = [r for r in P.read_jsonl(FROZEN / name) if r["split"] == "development"] | |
| if limit: # smoke runs: the first `limit` items of every source | |
| seen = {} | |
| rows = [r for r in rows if seen.setdefault(r["source"], []).append(1) or len(seen[r["source"]]) <= limit] | |
| return rows | |
| def write_jsonl(path, rows): | |
| with open(path, "w", encoding="utf-8") as stream: | |
| for row in rows: | |
| stream.write(json.dumps(row, ensure_ascii=False) + "\n") | |
| def quantile(values, q): | |
| values = sorted(values) | |
| position = q * (len(values) - 1) | |
| low = math.floor(position) | |
| high = min(low + 1, len(values) - 1) | |
| return values[low] + (values[high] - values[low]) * (position - low) | |
| def load_model(args): | |
| if args.model == "vime": | |
| from vimeml.benchmarks.zh13_lm_scores import load | |
| from vimeml.training.joint_zh13 import SPECIAL | |
| model, processor, meta = load(args.checkpoint, args.tokenizer, args.device) | |
| return P.VimeLM(model, processor, args.device, SPECIAL), {**meta, "dtype": "float32"} | |
| if args.model == "hf": | |
| from huggingface_hub import HfApi | |
| from vimeml.benchmarks.predict_zh_external import HFLM | |
| revision = args.revision or HfApi().model_info(args.name).sha | |
| dtype = {"float32": torch.float32, "bfloat16": torch.bfloat16}[args.dtype] | |
| lm = HFLM.from_pretrained(args.name, revision, args.device, dtype, args.context_length) | |
| return lm, {"name": args.name, "revision": revision, "dtype": args.dtype, | |
| "parameters": sum(p.numel() for p in lm.model.parameters()), | |
| "reachable_tokens": len(lm.vocabulary.han_ids)} | |
| if args.model == "char5": | |
| from vimeml.benchmarks.predict_zh_external import CharNgramLM | |
| lm = CharNgramLM.load(args.ngram) | |
| info = json.loads(Path(args.ngram).with_suffix(".json").read_text(encoding="utf-8")) | |
| return lm, {"ngram": str(args.ngram), "ngram_sha256": file_sha(args.ngram), **info, "dtype": "float32"} | |
| raise SystemExit(f"Unknown model adapter {args.model}") | |
| def build_ngram(args): | |
| from vimeml.benchmarks.predict_zh_external import CharNgramLM, char_ngram_documents | |
| out = Path(args.out) | |
| if out.exists(): | |
| raise SystemExit(f"{out} exists") | |
| out.parent.mkdir(parents=True, exist_ok=True) | |
| export = Path(args.export) | |
| documents, stats = char_ngram_documents(export, args.web_chars, args.chat_chars, log) | |
| lm = CharNgramLM.build(documents, log) | |
| lm.save(out) | |
| info = {"export_manifest_sha256": file_sha(export / "manifest.json"), "sample": stats, | |
| "web_target_han": args.web_chars, "chat_target_chars": args.chat_chars, | |
| "order": lm.ORDER, "min_count": lm.MIN_COUNT, "vocabulary": len(lm.chars), | |
| "discounts": {str(k): v for k, v in lm.discounts.items()}} | |
| write_json(out.with_suffix(".json"), info) | |
| log("saved", out, info) | |
| def run(args): | |
| for name, sha in FROZEN_SHA.items(): | |
| if file_sha(FROZEN / name) != sha: | |
| raise SystemExit(f"{name} differs from the frozen {VERSION}") | |
| out = Path(args.out) | |
| out.mkdir(parents=True, exist_ok=True) | |
| lm, model_meta = load_model(args) | |
| dicts = RIME / "cn_dicts" | |
| readings = P.load_readings(dicts) | |
| with warnings.catch_warnings(): | |
| warnings.simplefilter("ignore") | |
| import jieba | |
| import pypinyin | |
| jieba.setLogLevel(60) | |
| rime_commit = subprocess.run(["git", "-C", str(RIME), "rev-parse", "HEAD"], capture_output=True, | |
| text=True).stdout.strip() | |
| meta = { | |
| "version": VERSION, "split": "development", "limit_per_source": args.limit, | |
| "model": {"adapter": args.model, **model_meta, "device": args.device}, | |
| "decoder": {"beam": P.BEAM, "max_chars": P.MAX_CHARS, "min_chars": P.MIN_CHARS, "top": P.TOP, | |
| "show": P.SHOW, "reserve": P.RESERVE, "context_length": lm.context_length}, | |
| "frozen_sha256": FROZEN_SHA, | |
| "readings": {"rime_ice_commit": rime_commit, | |
| **{n: file_sha(dicts / n) for n in ("8105.dict.yaml", "41448.dict.yaml")}}, | |
| "jieba": jieba.__version__, "pypinyin": pypinyin.__version__, "torch": torch.__version__, | |
| } | |
| started = time.time() | |
| rows_a, items = [], development("items-a.jsonl", args.limit) | |
| for start in range(0, len(items), CHUNK): | |
| chunk = items[start:start + CHUNK] | |
| decoded = P.predict_many(lm, [(item["previous_turns"], item["prefix"], None) for item in chunk]) | |
| for item, candidates in zip(chunk, decoded): | |
| rank, chars = P.rank_of_hit(candidates, item["continuation"]) | |
| rows_a.append({"id": item["id"], "source": item["source"], "dialogue": item["dialogue"], | |
| "candidates": candidates, "rank": rank, "hit_chars": chars, | |
| "confidence": candidates[0][1] if candidates else None}) | |
| log("A", len(rows_a), len(items)) | |
| write_jsonl(out / "track-a.jsonl", rows_a) | |
| meta["seconds_a"] = round(time.time() - started, 1) | |
| meta["tracks"] = args.tracks | |
| if args.tracks == "a": # the primary metric only; B and C stay descriptive and can be run later | |
| meta["seconds_total"] = meta["seconds_a"] | |
| write_json(out / "meta.json", meta) | |
| log("done (track A only)", meta["seconds_total"], "s") | |
| return | |
| rows_c, items = [], development("items-c.jsonl", args.limit) | |
| for start in range(0, len(items), CHUNK): | |
| chunk = [(item, mode, kind, field) for item in items[start:start + CHUNK] for mode, kind, field in MODES] | |
| decoded = P.predict_many(lm, [(item["previous_turns"], item["prefix"], P.Constraint(kind, item[field])) | |
| for item, _, kind, field in chunk], readings) | |
| for (item, mode, _, field), candidates in zip(chunk, decoded): | |
| rows_c.append({"id": item["id"], "source": item["source"], "dialogue": item["dialogue"], | |
| "mode": mode, "keys": item[field], "candidates": candidates, | |
| "rank": P.rank_exact(candidates, item["target"])}) | |
| log("C", start + len(chunk) // len(MODES), len(items)) | |
| write_jsonl(out / "track-c.jsonl", rows_c) | |
| meta["seconds_c"] = round(time.time() - started - meta["seconds_a"], 1) | |
| scores = [r["confidence"] for r in rows_a if r["confidence"] is not None] | |
| grid = [P.NEG] + [quantile(scores, q) for q in QUANTILES] | |
| meta["threshold_grid"] = [P.finite(t) for t in grid] | |
| def pinyin(run): | |
| return pypinyin.lazy_pinyin(run, style=pypinyin.Style.NORMAL) | |
| def cut(message): | |
| return jieba.lcut(message, HMM=False) | |
| # Each message's simulations ask for predictions position by position. They run in rounds: | |
| # every simulation goes as far as the decoded positions allow, the positions they stop at are | |
| # decoded together, and the rounds repeat. The positions decoded are exactly those asked for. | |
| items = development("messages-b.jsonl", args.limit) | |
| memos, decodes = [{} for _ in items], 0 | |
| setup = [(P.keystrokes(item["message"], pinyin), P.boundaries(item["message"], cut)) for item in items] | |
| class Missing(Exception): | |
| pass | |
| def simulate_all(index): | |
| message, memo, (costs, ends) = items[index]["message"], memos[index], setup[index] | |
| missing, results = set(), [] | |
| def predictions(position): | |
| if position not in memo: | |
| raise Missing(position) | |
| return memo[position] | |
| for t in grid: | |
| try: | |
| results.append(P.simulate(message, costs, ends, predictions, t)) | |
| except Missing as stop: | |
| missing.add(stop.args[0]) | |
| return missing, results | |
| rows_b, open_ = [None] * len(items), list(range(len(items))) | |
| while open_: | |
| needed, still = [], [] | |
| for index in open_: | |
| missing, results = simulate_all(index) | |
| if missing: | |
| needed += [(index, position) for position in sorted(missing)] | |
| still.append(index) | |
| else: | |
| item = items[index] | |
| rows_b[index] = {"id": item["id"], "source": item["source"], "dialogue": item["dialogue"], | |
| "results": results} | |
| for start in range(0, len(needed), CHUNK): | |
| chunk = needed[start:start + CHUNK] | |
| decoded = P.predict_many(lm, [(items[i]["previous_turns"], items[i]["message"][:p], None) | |
| for i, p in chunk]) | |
| for (i, p), candidates in zip(chunk, decoded): | |
| memos[i][p] = candidates | |
| decodes += len(needed) | |
| open_ = still | |
| log("B", len(items) - len(open_), len(items), "decodes", decodes) | |
| write_jsonl(out / "track-b.jsonl", rows_b) | |
| meta["decodes_b"] = decodes | |
| meta["seconds_total"] = round(time.time() - started, 1) | |
| write_json(out / "meta.json", meta) | |
| log("done", meta["seconds_total"], "s") | |
| def savings(rows, index): | |
| keys = sum(r["results"][index]["keys"] for r in rows) | |
| base = sum(r["results"][index]["baseline_keys"] for r in rows) | |
| shows = sum(r["results"][index]["shows"] for r in rows) | |
| clicks = sum(r["results"][index]["clicks"] for r in rows) | |
| return {"savings": 1 - keys / base, "keys": keys, "baseline_keys": base, "shows": shows, | |
| "clicks": clicks, "click_rate": clicks / shows if shows else None} | |
| def score(args): | |
| run_dir = Path(args.run) | |
| meta = json.loads((run_dir / "meta.json").read_text(encoding="utf-8")) | |
| rows_a = P.read_jsonl(run_dir / "track-a.jsonl") | |
| hits3 = [r["hit_chars"] for r in rows_a if r["rank"] and r["rank"] <= 3] | |
| result = {"version": meta["version"], "split": meta["split"], "model": meta["model"], | |
| "track_a": {**P.rates(rows_a, "rank"), | |
| "mean_hit_chars_top3": sum(hits3) / len(hits3) if hits3 else None}} | |
| if meta.get("tracks") == "a": | |
| result["track_d"] = P.coverage_curve([{"id": r["id"], "confidence": r["confidence"], "rank": r["rank"]} | |
| for r in rows_a]) | |
| write_json(run_dir / "score.json", result) | |
| a = result["track_a"] | |
| print(f"A top1 {a['top1']['micro']:.4f} top3 {a['top3']['micro']:.4f} (macro {a['top3']['macro']:.4f})" | |
| f" top5 {a['top5']['micro']:.4f} hit chars {a['mean_hit_chars_top3']:.2f} (track A only)") | |
| return | |
| rows_c = P.read_jsonl(run_dir / "track-c.jsonl") | |
| result["track_c"] = {mode: P.rates([r for r in rows_c if r["mode"] == mode], "rank") for mode, _, _ in MODES} | |
| rows_b = P.read_jsonl(run_dir / "track-b.jsonl") | |
| grid = meta["threshold_grid"] | |
| table = [{"threshold": t, **savings(rows_b, i)} for i, t in enumerate(grid)] | |
| # best savings; ties go to the higher threshold (fewer shows) | |
| best = max(range(len(grid)), key=lambda i: (table[i]["savings"], i)) | |
| sources = sorted({r["source"] for r in rows_b}) | |
| result["track_b"] = {"chosen": table[best], | |
| "by_source": {s: savings([r for r in rows_b if r["source"] == s], best)["savings"] | |
| for s in sources}, | |
| "grid": table} | |
| result["track_d"] = P.coverage_curve([{"id": r["id"], "confidence": r["confidence"], "rank": r["rank"]} | |
| for r in rows_a]) | |
| write_json(run_dir / "score.json", result) | |
| a, b = result["track_a"], result["track_b"]["chosen"] | |
| print(f"A top1 {a['top1']['micro']:.4f} top3 {a['top3']['micro']:.4f} (macro {a['top3']['macro']:.4f})" | |
| f" top5 {a['top5']['micro']:.4f} hit chars {a['mean_hit_chars_top3']:.2f}") | |
| for mode in result["track_c"]: | |
| c = result["track_c"][mode] | |
| print(f"C {mode:14s} top1 {c['top1']['micro']:.4f} top3 {c['top3']['micro']:.4f}" | |
| f" top5 {c['top5']['micro']:.4f}") | |
| print(f"B savings {b['savings']:.4f} threshold {b['threshold']} shows {b['shows']}" | |
| f" clicks {b['clicks']} click rate {b['click_rate']}") | |
| print("D ", {k: round(v["top1"], 4) for k, v in result["track_d"].items()}) | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| sub = parser.add_subparsers(dest="command", required=True) | |
| r = sub.add_parser("run") | |
| r.add_argument("--model", default="vime", choices=("vime", "hf", "char5")) | |
| r.add_argument("--checkpoint", default=str(ROOT / "artifacts/models/tiny-zh13-12k-fresh-s1-d384-l9/final.pt")) | |
| r.add_argument("--tokenizer", default=str(ROOT / "artifacts/tokenizers/zh-v13/zh-unigram-12288/tokenizer.model")) | |
| r.add_argument("--name", help="hf: model repository, e.g. Qwen/Qwen2.5-0.5B") | |
| r.add_argument("--revision", help="hf: commit; default the current one, recorded in meta.json") | |
| r.add_argument("--dtype", default="float32", choices=("float32", "bfloat16")) | |
| r.add_argument("--context-length", type=int, default=512, help="hf: context tokens") | |
| r.add_argument("--ngram", default=str(NGRAM), help="char5: model built by build-ngram") | |
| r.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu") | |
| r.add_argument("--limit", type=int, default=0, help="items per source, for smoke runs") | |
| r.add_argument("--out", required=True) | |
| r.add_argument("--tracks", default="all", choices=("all", "a"), help="a: track A (the primary metric) only") | |
| g = sub.add_parser("build-ngram", help="character 5-gram from a fixed sample of export-r1/train") | |
| g.add_argument("--export", default=str(ROOT / "outputs/zh-corpus/export-r1")) | |
| g.add_argument("--web-chars", type=int, default=9_500_000, help="target Chinese characters of web text") | |
| g.add_argument("--chat-chars", type=int, default=500_000, help="target characters of LCCC dialogues") | |
| g.add_argument("--out", default=str(NGRAM)) | |
| s = sub.add_parser("score") | |
| s.add_argument("--run", required=True) | |
| args = parser.parse_args() | |
| {"run": run, "score": score, "build-ngram": build_ngram}[args.command](args) | |
| if __name__ == "__main__": | |
| main() | |