onw 0.10.0: long contexts with a paged INT8 KV cache (32K default, up to the model max); Gemma RoPE fix; Ubuntu launcher fix
3aabffd verified Download compare_kv.py from ryugyosoft/onw: direct link, hf CLI and curl.
- Browser
- Download file 2.44 kB
-
https://huggingface.co/ryugyosoft/onw/resolve/main/compare_kv.py
- Command line
-
hf download hf://ryugyosoft/onw/compare_kv.py
-
curl -L -o compare_kv.py https://huggingface.co/ryugyosoft/onw/resolve/main/compare_kv.py
2.44 kB
| """Paged KV cache vs the legacy in-graph caches on one model: first-token logits and greedy tokens. | |
| usage: python compare_kv.py MODEL_DIR [n_tokens=24] (runs each mode in its own process)""" | |
| import json, os, subprocess, sys | |
| import numpy as np | |
| PROMPT = "日本の首都について2文で説明してください。" | |
| def run(d, n, out): | |
| from transformers import AutoTokenizer | |
| import openvino as ov | |
| from onw.runtime import SegmentedModel | |
| tok = AutoTokenizer.from_pretrained(d) | |
| kw = {"enable_thinking": False} if "enable_thinking" in (tok.chat_template or "") else {} | |
| ids = tok.apply_chat_template([{"role": "user", "content": PROMPT}], add_generation_prompt=True, tokenize=False, **kw) | |
| ids = tok(ids, add_special_tokens=False)["input_ids"] | |
| m = SegmentedModel(ov.Core(), d, "NPU", {"CACHE_DIR": os.path.join(d, "npu_cache")}) | |
| lg = None | |
| for s in range(0, len(ids), m.S): | |
| lg = m.step(ids[s:s + m.S]) | |
| first = np.asarray(lg[-1], np.float32) | |
| toks = [int(first.argmax())] | |
| for _ in range(n - 1): | |
| toks.append(int(np.asarray(m.step([toks[-1]])[-1], np.float32).argmax())) | |
| np.savez(out, first=first, toks=np.array(toks)) | |
| print(tok.decode(toks), flush=True) | |
| def main(): | |
| if sys.argv[1] == "--run": | |
| return run(sys.argv[2], int(sys.argv[3]), sys.argv[4]) | |
| d = sys.argv[1] | |
| n = int(sys.argv[2]) if len(sys.argv) > 2 else 24 | |
| res = {} | |
| for mode in ("legacy", "paged"): | |
| out = os.path.join(d, f"cmp_{mode}.npz") | |
| env = {**os.environ, "ONW_KV": mode, "PYTHONUTF8": "1"} | |
| r = subprocess.run([sys.executable, __file__, "--run", d, str(n), out], env=env, capture_output=True, text=True, | |
| encoding="utf8", errors="replace") | |
| print(f"{mode}: {r.stdout.strip().splitlines()[-1] if r.stdout.strip() else r.stderr[-400:]}", flush=True) | |
| with np.load(out) as z: | |
| res[mode] = {k: z[k] for k in z.files} | |
| os.remove(out) | |
| a, b = res["legacy"], res["paged"] | |
| err = np.linalg.norm(a["first"] - b["first"]) / np.linalg.norm(a["first"]) | |
| same = int(np.argmax(a["toks"] != b["toks"])) if (a["toks"] != b["toks"]).any() else len(a["toks"]) | |
| print(json.dumps({"first_token_logits_rel_diff": round(float(err), 4), "top1_same": bool(a["toks"][0] == b["toks"][0]), | |
| "greedy_identical_tokens": same, "of": len(a["toks"])})) | |
| if __name__ == "__main__": | |
| main() | |