classify onnxcl.py
Browse files- scripts_full/onnxcl.py +36 -0
scripts_full/onnxcl.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""exact-label accuracy of an ONNX artifact decoded exactly like the validator engine. usage: onnxcl.py <artifact_dir> <jsonl> [N]"""
|
| 2 |
+
import json, os, re, sys, time
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np, onnxruntime as ort
|
| 5 |
+
from tokenizers import Tokenizer
|
| 6 |
+
H = Path(os.path.expanduser("~/mt92"))
|
| 7 |
+
D = Path(sys.argv[1]); SET = H/sys.argv[2]; N = int(sys.argv[3]) if len(sys.argv) > 3 else 300
|
| 8 |
+
so = ort.SessionOptions(); so.intra_op_num_threads = int(os.environ.get("THREADS", "8"))
|
| 9 |
+
sess = ort.InferenceSession(str(D/"model.onnx"), so, providers=["CPUExecutionProvider"])
|
| 10 |
+
tk = Tokenizer.from_file(str(D/"tokenizer.json"))
|
| 11 |
+
inames = {i.name for i in sess.get_inputs()}; past_inputs = [i.name for i in sess.get_inputs() if i.name.startswith("past_key_values")]
|
| 12 |
+
shapes = {i.name: i.shape for i in sess.get_inputs()}
|
| 13 |
+
def empty_past():
|
| 14 |
+
p = {}
|
| 15 |
+
for n in past_inputs:
|
| 16 |
+
s = [d if isinstance(d, int) else 0 for d in shapes[n]]; s[0] = 1; p[n] = np.zeros(s, dtype=np.float32)
|
| 17 |
+
return p
|
| 18 |
+
def carry(outs):
|
| 19 |
+
names = [o.name for o in sess.get_outputs()]
|
| 20 |
+
pres = {n.replace("present", "past_key_values", 1): v for n, v in zip(names, outs) if n.startswith("present")}
|
| 21 |
+
return {n: pres[n] for n in past_inputs if n in pres}
|
| 22 |
+
def run(prompt, maxout=16):
|
| 23 |
+
toks = list(tk.encode(prompt).ids); produced = []; past = empty_past(); cursor = toks
|
| 24 |
+
for step in range(maxout):
|
| 25 |
+
f = {"input_ids": np.asarray([cursor], dtype=np.int64)}
|
| 26 |
+
if "attention_mask" in inames: f["attention_mask"] = np.ones((1, len(toks)+len(produced)), dtype=np.int64)
|
| 27 |
+
if "position_ids" in inames:
|
| 28 |
+
off = len(toks)+len(produced)-len(cursor); f["position_ids"] = np.asarray([list(range(off, off+len(cursor)))], dtype=np.int64)
|
| 29 |
+
f.update(past); outs = sess.run(None, f); nxt = int(np.argmax(outs[0][0, -1])); produced.append(nxt)
|
| 30 |
+
if nxt == 151643: break
|
| 31 |
+
past = carry(outs); cursor = [nxt]
|
| 32 |
+
return tk.decode(produced)
|
| 33 |
+
norm = lambda s: re.sub(r"\s+", " ", str(s).strip().lower())
|
| 34 |
+
rows = [json.loads(l) for l in SET.read_text().splitlines() if l.strip()][:N]
|
| 35 |
+
ok = sum(norm(run(r["prompt"])) == norm(r["completion"]) for r in rows)
|
| 36 |
+
print(f"=== {D} on {SET.name} first {len(rows)}: ACCURACY {ok/len(rows):.4f}")
|