VisualInference's picture
Inkling 2 Mini for MLX, 2bit: weights, card, validation results
031489f verified
Raw History Blame Contribute Delete
3.36 kB
"""Held-out loss on assistant-side tokens. Usage: eval_nll.py <model_dir|native> <sequences.json> <out.json> <tag> [--fp32] [--actquant input,hidden]
Counts only tokens the model would generate itself (assistant messages: reasoning, text, tool calls, and the
end-of-turn token). Stores per-sequence sums so variants can be compared with paired statistics.
"""
import json, os, sys, time
import numpy as np
import mlx.core as mx
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import qlab
MODEL_TOK, END_MSG, EOS = 200001, 200010, 200006
def assistant_mask(ids):
mask, inside = [], False
for t in ids:
if t == MODEL_TOK:
inside = True
mask.append(inside or t == EOS)
if t == END_MSG:
inside = False
return mask
def main():
args = sys.argv[1:]
fp32 = "--fp32" in args
if fp32: args.remove("--fp32")
aq = None
if "--actquant" in args:
i = args.index("--actquant"); aq = tuple(args[i + 1].split(",")); del args[i:i + 2]
recipe = None
if "--recipe" in args:
i = args.index("--recipe"); rfile, rname = args[i + 1].split(":"); del args[i:i + 2]
recipe = json.load(open(rfile))[rname]
model_dir, seq_path, out_path, tag = args[:4]
path = qlab.NATIVE if model_dir == "native" else model_dir
model, _ = qlab.load_native(fp32=False, path=path)
size = None
if recipe is not None:
import recipes as R
R.apply(model, recipe, os.path.join(qlab.ROOT, "q", "shards"))
size = R.nbytes(model) / 2**30
if fp32:
qlab.to_fp32(model); mx.eval(model.parameters())
if aq:
import actquant
actquant.install(model, aq)
seqs = qlab.load_sequences(seq_path, split="eval", max_len=1024)
rows, t0 = [], time.time()
for s in seqs:
ids = s["ids"]
lg = qlab.logits_for(model, ids)
lp = qlab.log_softmax(lg)[:-1]
nxt = mx.array(ids[1:])
nll = -mx.take_along_axis(lp, nxt[:, None], axis=-1)[:, 0]
m = mx.array(assistant_mask(ids)[1:]).astype(mx.float32)
hit = (mx.argmax(lp, axis=-1) == nxt).astype(mx.float32)
vals = [(nll * m).sum(), m.sum(), (hit * m).sum()]
mx.eval(vals)
rows.append(dict(name=s["name"], kind=s["kind"].split(":")[0], nll=vals[0].item(), n=int(vals[1].item()), hit=vals[2].item()))
del lg, lp
res = json.load(open(out_path)) if os.path.exists(out_path) else {}
n = sum(r["n"] for r in rows)
summ = dict(tokens=n, nll=sum(r["nll"] for r in rows) / n, acc=sum(r["hit"] for r in rows) / n, seconds=round(time.time() - t0),
peak_gb=round(mx.get_peak_memory() / 2**30, 2), weights_gib=size, activations="fp32" if fp32 else "bf16", actquant=aq)
for kind in sorted({r["kind"] for r in rows}):
sel = [r for r in rows if r["kind"] == kind]
summ[kind] = dict(tokens=sum(r["n"] for r in sel), nll=sum(r["nll"] for r in sel) / max(1, sum(r["n"] for r in sel)))
summ["rows"] = rows
res[tag] = summ
json.dump(res, open(out_path, "w"))
print(f"{tag:28s} tokens {n} NLL {summ['nll']:.4f} ppl {np.exp(summ['nll']):.3f} acc {summ['acc']:.4f} "
+ " ".join(f"{k} {summ[k]['nll']:.4f}" for k in ("chat", "code", "wikitext") if k in summ) + f" ({summ['seconds']}s)", flush=True)
if __name__ == "__main__":
main()