Files
leleka/scripts/quality/q_lib.py
T

130 lines
6.7 KiB
Python

"""Parsers and metrics of the model quality gate. Offline analysis only; no runtime use.
A *row* is one engine's output at one position of one token path: the top-k log-probabilities of the next token given the
tokens up to and including `pos`. Both engines print them in the same tab-separated form (verify.cpp `window_logprobs`):
pos target lp(target) top1 lp(top1) match lp(extra) lp(target without extra) id:lp ... (descending)
"""
import json, math, os, re, statistics
class Row:
__slots__ = ("pos", "target", "lp_target", "topk")
def __init__(self, pos, target, lp_target, topk):
self.pos, self.target, self.lp_target, self.topk = pos, target, lp_target, topk # topk: [(id, lp)] descending
@property
def top1(self): return self.topk[0][0]
@property
def margin(self): return self.topk[0][1] - self.topk[1][1]
def lp(self, token):
for t, v in self.topk:
if t == token: return v
return None
def rank(self, token):
for i, (t, _) in enumerate(self.topk):
if t == token: return i + 1
return None
def parse_row(line):
f = line.rstrip("\n").split("\t")
if len(f) < 9 or not f[0].lstrip("-").isdigit(): return None
topk = [(int(a.split(":")[0]), float(a.split(":")[1])) for a in f[8:] if ":" in a]
if len(topk) < 2: return None
return Row(int(f[0]), int(f[1]), float(f[2]), topk)
def load_orig_logpos(run_dir):
"""The Original's STRATA_LOGPOS file as one {pos: Row} dict per request, in request order (a request starts when the
position does not increase)."""
segments, prev = [], None
for line in open(os.path.join(run_dir, "logpos"), errors="replace"):
row = parse_row(line)
if row is None: continue
if prev is None or row.pos != prev + 1: segments.append({})
prev = row.pos
segments[-1][row.pos] = row
nf = os.path.join(run_dir, "reqs.txt.names")
names = [n for n in open(nf).read().split(chr(10)) if n] if os.path.exists(nf) else []
return segments, names
def load_case(cases_dir, name):
return [int(x) for x in open(os.path.join(cases_dir, name + ".ids")).read().strip().split(",")]
def orig_reads(run_dir, cases_dir):
"""{label: (case name, request keys, {pos: Row})} for the teacher-forced read requests of an Original run; repeated labels
get a '#k' suffix. Rows of the read requests only."""
segments, names = load_orig_logpos(run_dir)
out, seen = {}, {}
for seg, label in zip(segments, names):
if not label.startswith("read:"): continue
spec = label[5:]
case = spec.split(":")[0]
k = seen.get(spec, 0); seen[spec] = k + 1
out[spec + ("" if k == 0 else f"#{k}")] = (case, spec.split(":")[1:], seg)
return out
def parse_port_log(path):
"""The port smoke log -> list of runs {index, pass, forced, windows:[(position, inputs, [Row])], output:[ids] or None}.
Rows are attached to the window announced by the preceding `DBG logprobs window` line."""
runs, cur, win = [], None, None
for line in open(path, errors="replace"):
m = re.match(r"DBG corpus (\d+) pass=(\d+) begin forced=(true|false)", line)
if m:
cur = {"index": int(m[1]), "pass": int(m[2]), "forced": m[3] == "true", "windows": [], "output": None, "notes": []}
runs.append(cur); win = None; continue
if cur is None: continue
m = re.match(r"DBG logprobs window position=(\d+) inputs=\[([0-9, -]*)\] argmax_ids=\[([0-9, -]*)\]", line)
if m:
win = (int(m[1]), [int(x) for x in m[2].split(",") if x.strip()], [])
cur["windows"].append(win); continue
m = re.match(r"DBG corpus (\d+) output(?: pass=(\d+))? \((\d+) tokens, rounds (\d+)\): ([0-9 ]*)", line)
if m and int(m[1]) == cur["index"] and int(m[2] or 0) == cur["pass"]:
cur["output"] = [int(x) for x in m[5].split()]; continue
if line.startswith("DBG corpus") and "forced:" in line: cur["notes"].append(line.strip()); continue
row = parse_row(line)
if row is not None and win is not None and len(win[2]) < len(win[1]):
win[2].append(row)
return runs
def valid_rows(windows, truth):
"""{pos: Row} of the rows whose consumed tokens (the window's inputs up to the row) equal the token path `truth`
(the first occurrence of a position wins). A row after a rejected draft token is conditioned on text that is not on
the path and is skipped."""
out = {}
for position, inputs, rows in windows:
for r, row in enumerate(rows):
if position + r >= len(truth) or inputs[: r + 1] != truth[position : position + r + 1]: break
out.setdefault(position + r, row)
return out
def compare(ref, other, first_pos=0, last_pos=10**9):
"""Per common position of two {pos: Row} dicts, in [first_pos, last_pos]."""
res = []
for pos in sorted(set(ref) & set(other)):
if not first_pos <= pos <= last_pos: continue
a, b = ref[pos], other[pos]
common = [t for t, _ in a.topk if b.lp(t) is not None]
dmax = max((abs(a.lp(t) - b.lp(t)) for t in common), default=float("nan"))
d1 = abs(a.topk[0][1] - b.lp(a.top1)) if b.lp(a.top1) is not None else float("nan")
res.append({"pos": pos, "dmax": dmax, "ncommon": len(common), "flip": a.top1 != b.top1,
"ref_margin": a.margin, "other_margin": b.margin, "ref_top1": a.top1, "other_top1": b.top1,
"other_rank_of_ref_top1": b.rank(a.top1), "ref_rank_of_other_top1": a.rank(b.top1),
"d_target": abs(a.lp_target - b.lp_target), "d_top1": d1})
return res
def quantile(values, q):
v = sorted(x for x in values if not math.isnan(x))
if not v: return float("nan")
k = (len(v) - 1) * q; lo, hi = int(math.floor(k)), int(math.ceil(k))
return v[lo] + (v[hi] - v[lo]) * (k - lo)
def _qs(v):
v = [x for x in v if not math.isnan(x)]
return {"median": quantile(v, .5), "p90": quantile(v, .9), "p99": quantile(v, .99), "max": max(v, default=float("nan"))}
def summary(rows):
"""Distribution of the three per-position deviations: dmax (max over the common top-k, the tail included), d_top1 (the
reference's argmax token) and d_target (the token on the path); plus the argmax flips and the reference margin at each."""
flips = [r for r in rows if r["flip"]]
return {"n": len(rows), "dmax": _qs([r["dmax"] for r in rows]), "d_top1": _qs([r["d_top1"] for r in rows]),
"d_target": _qs([r["d_target"] for r in rows]), "flips": len(flips),
"flip_margins": sorted(round(r["ref_margin"], 3) for r in flips),
"flip_pos": [(r.get("case"), r["pos"], round(r["ref_margin"], 3), round(r["other_margin"], 3)) for r in flips]}