Download source/scripts/ja/benchmarks/latency_ja.py from Voltline/vimeml-ja-v6: direct link, hf CLI and curl.
- Browser
- Download file 9.35 kB
-
https://huggingface.co/Voltline/vimeml-ja-v6/resolve/main/source/scripts/ja/benchmarks/latency_ja.py
- Command line
-
hf download hf://Voltline/vimeml-ja-v6/source/scripts/ja/benchmarks/latency_ja.py
-
curl -L -o latency_ja.py https://huggingface.co/Voltline/vimeml-ja-v6/resolve/main/source/scripts/ja/benchmarks/latency_ja.py
9.35 kB
| """Desktop latency of the Japanese kana pipeline in PyTorch (vimeml-ja-v6): AzooKey rerank and full flow. | |
| usage: | |
| python -X utf8 scripts/ja/benchmarks/latency_ja.py --checkpoint CKPT --out FILE.json [--device cuda|cpu] | |
| [--backend eager|graph] [--dtype fp32|fp16|bf16] [--threads N] [--every 1] [--reference ROWS.jsonl] | |
| Per item of ime-kana-ja-v1 development (every Nth item, full reading, its left context), two | |
| timings, each end to end with the device synchronized: | |
| - rerank: the AzooKey N-best 20 scored with task-mode gen_score and LM-mode lm_score and ordered by | |
| gen + 1.6 * lm (kana_gen_ja.merge_and_rank). This is the list the client shows on every key. | |
| - full: constrained beam 16 search (top 10, kana_gen_ja's search call), then the union with the | |
| AzooKey 20 scored and merged the same way. This is the list the client merges after a pause. | |
| Model time of the search (prefill, decode) is reported separately; the rest of the search is Python. | |
| One warm-up pass over the first 5 items is not counted. | |
| --backend graph replays the search's decode step from CUDA graphs (zh_torch_graph.GraphBackend; the | |
| capture time is reported and not counted); --dtype casts the weights, which scoring uses too. | |
| Accuracy: notation-lenient and exact Top-1 of both lists over the timed items, and with --reference | |
| (evaluate_arm development rows of the same checkpoint, FP32) the share of items whose full-flow | |
| displayed top 1 equals the reference's. | |
| """ | |
| import argparse | |
| import json | |
| import platform | |
| import statistics | |
| import sys | |
| import time | |
| from pathlib import Path | |
| ROOT = Path(__file__).resolve().parents[3] | |
| sys.path.insert(0, str(ROOT / "src")) | |
| import torch # noqa: E402 | |
| from vimeml.benchmarks import kana_gen_ja as kg # noqa: E402 | |
| from vimeml.deployment.ja_search import KanaIndex, search as kana_search # noqa: E402 | |
| from vimeml.deployment.zh_torch_backend import ModelBatchBackend # noqa: E402 | |
| from vimeml.deployment.zh_torch_graph import GraphBackend # noqa: E402 | |
| DTYPES = {"fp32": torch.float32, "fp16": torch.float16, "bf16": torch.bfloat16} | |
| LAM = 1.6 | |
| class Timed: | |
| """Wraps a backend; adds the synchronized wall time of every call to `seconds`.""" | |
| def __init__(self, inner, device): | |
| self.inner, self.device, self.seconds = inner, device, 0.0 | |
| def _time(self, fn, *args): | |
| sync(self.device) | |
| start = time.perf_counter() | |
| out = fn(*args) | |
| sync(self.device) | |
| self.seconds += time.perf_counter() - start | |
| return out | |
| def prefill(self, *args): | |
| return self._time(self.inner.prefill, *args) | |
| def decode(self, *args): | |
| return self._time(self.inner.decode, *args) | |
| def sync(device): | |
| if device.startswith("cuda"): | |
| torch.cuda.synchronize() | |
| def pct(values, q): | |
| values = sorted(values) | |
| return values[min(len(values) - 1, int(round(q * (len(values) - 1))))] | |
| def summary(rows, key): | |
| v = [r[key] for r in rows] | |
| return {"n": len(v), "p50": 1000 * pct(v, 0.5), "p95": 1000 * pct(v, 0.95), "mean": 1000 * statistics.fmean(v), | |
| "max": 1000 * max(v)} | |
| def main(): | |
| p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| p.add_argument("--checkpoint", required=True) | |
| p.add_argument("--out", required=True) | |
| p.add_argument("--device", default="cuda") | |
| p.add_argument("--backend", choices=("eager", "graph"), default="eager") | |
| p.add_argument("--dtype", choices=tuple(DTYPES), default="fp32") | |
| p.add_argument("--threads", type=int, default=0) | |
| p.add_argument("--every", type=int, default=1, help="take every Nth development item") | |
| p.add_argument("--beam", type=int, default=16) | |
| p.add_argument("--reference", help="FP32 development rows of the same checkpoint (evaluate_arm)") | |
| p.add_argument("--tokenizer", default=str(ROOT / "artifacts/tokenizers/ja-kana-v1/ja-unigram-12288/tokenizer.model")) | |
| p.add_argument("--index", default=str(ROOT / "outputs/ja-gen-stage2/kana-index.json")) | |
| p.add_argument("--pool", default=str(ROOT / "artifacts/benchmarks/ime-candidates-v3-imported/kana-ja-v1-development-n20")) | |
| args = p.parse_args() | |
| if Path(args.out).exists(): | |
| raise SystemExit(f"{args.out} exists") | |
| if args.threads: | |
| torch.set_num_threads(args.threads) | |
| if args.device.startswith("cuda"): | |
| torch.backends.cuda.matmul.allow_tf32 = False | |
| torch.backends.cudnn.allow_tf32 = False | |
| model, sp, meta = kg.load_zh_model(args.checkpoint, args.tokenizer, args.device) | |
| model.float().eval() | |
| capture = None | |
| if args.backend == "graph": | |
| start = time.perf_counter() | |
| backend = GraphBackend(model, args.device, rows=args.beam, dtype=DTYPES[args.dtype]) | |
| capture = time.perf_counter() - start | |
| else: | |
| backend = ModelBatchBackend(model, args.device) # casts to FP32 | |
| if args.dtype != "fp32": | |
| model.to(DTYPES[args.dtype]) | |
| timed = Timed(backend, args.device) | |
| index = KanaIndex.load(args.index) | |
| _, pool = kg.load_dev_pool(args.pool) | |
| items = pool[::args.every] | |
| reference = {} | |
| if args.reference: | |
| reference = {r["id"]: r["shown"][0] if r["shown"] else None for r in kg.read_jsonl(args.reference)} | |
| def one(row): | |
| az = [c["text"] for c in row["candidates"]] | |
| context = row.get("left_context") or "" | |
| reading = kg.row_reading(row) | |
| with torch.inference_mode(): | |
| sync(args.device) | |
| start = time.perf_counter() | |
| g = kg.task_scores(model, sp, reading, context, az, device=args.device) | |
| lm = kg.lm_scores_safe(model, sp, context, az, device=args.device) | |
| reranked = kg.merge_and_rank(az, [], g, lm, lam=LAM) | |
| sync(args.device) | |
| rerank = time.perf_counter() - start | |
| timed.seconds = 0.0 | |
| start = time.perf_counter() | |
| ranked, stats = kana_search(timed, sp, index, reading, context, beam=args.beam, topk=10, | |
| search_mode="constrained", fallback_free=True) | |
| searched = time.perf_counter() | |
| gen = [t for t, _, _ in ranked] | |
| union = list(dict.fromkeys(az + gen)) | |
| g = kg.task_scores(model, sp, reading, context, union, device=args.device) | |
| lm = kg.lm_scores_safe(model, sp, context, union, device=args.device) | |
| shown = kg.merge_and_rank(az, gen, g, lm, lam=LAM) | |
| sync(args.device) | |
| end = time.perf_counter() | |
| return {"rerank": rerank, "full": end - start, "search": searched - start, "score": end - searched, | |
| "model": timed.seconds, "python": searched - start - timed.seconds, "calls": stats.calls, | |
| "fallback": bool(stats.fallback), "candidates": len(union), | |
| "rerank_top1": reranked[0] if reranked else None, "shown_top1": shown[0] if shown else None, | |
| "rerank_lenient": kg.hit_at_k(reranked, row["answers"], 1, "lenient"), | |
| "rerank_exact": kg.hit_at_k(reranked, row["answers"], 1, "exact"), | |
| "full_lenient": kg.hit_at_k(shown, row["answers"], 1, "lenient"), | |
| "full_exact": kg.hit_at_k(shown, row["answers"], 1, "exact")} | |
| for row in items[:5]: | |
| one(row) | |
| rows = [] | |
| for row in items: | |
| r = {"id": row["id"], "band": kg.length_band(row), "chars": len(kg.row_reading(row)), **one(row)} | |
| if reference: | |
| r["same_as_reference"] = r["shown_top1"] == reference.get(row["id"]) | |
| rows.append(r) | |
| accuracy = {k: sum(r[k] for r in rows) for k in ("rerank_lenient", "rerank_exact", "full_lenient", "full_exact")} | |
| accuracy["fallbacks"] = sum(r["fallback"] for r in rows) | |
| if reference: | |
| accuracy["full_top1_same_as_reference"] = sum(r["same_as_reference"] for r in rows) | |
| result = {"checkpoint": Path(args.checkpoint).parent.name, "checkpoint_sha256": meta["checkpoint_sha256"], | |
| "device": args.device, "backend": args.backend, "capture_seconds": capture, | |
| "dtype": args.dtype, "threads": torch.get_num_threads(), "beam": args.beam, "lambda": LAM, | |
| "every": args.every, "items": len(rows), "torch": torch.__version__, | |
| "python": platform.python_version(), | |
| "gpu": torch.cuda.get_device_name() if args.device.startswith("cuda") else None, | |
| "cpu": platform.processor(), "accuracy": accuracy, | |
| "summary": {band: {k: summary([r for r in rows if band in ("all", r["band"])], k) | |
| for k in ("rerank", "full", "search", "score", "model", "python")} | |
| for band in ("all", "4-10", "11-20", "21-40")}, | |
| "rows": rows} | |
| Path(args.out).parent.mkdir(parents=True, exist_ok=True) | |
| Path(args.out).write_text(json.dumps(result, ensure_ascii=False, indent=1) + "\n", "utf-8") | |
| s = result["summary"]["all"] | |
| print(f"{result['checkpoint']} {args.device} {args.backend} {args.dtype}: n {len(rows)}, rerank p50/p95 " | |
| f"{s['rerank']['p50']:.0f}/{s['rerank']['p95']:.0f} ms, full {s['full']['p50']:.0f}/{s['full']['p95']:.0f} ms " | |
| f"(search model {s['model']['p50']:.0f}, python {s['python']['p50']:.0f}, score {s['score']['p50']:.0f}); " | |
| f"{json.dumps(accuracy)}") | |
| if __name__ == "__main__": | |
| main() | |