Files

268 lines
13 KiB
Python

#!/usr/bin/env python3
"""Analysis of the 245k equivalence test. Offline; no runtime use.
Inputs
--data DIR q245_prep output (p<k>.ids, r_<source><k>.ids, meta.json)
--orig NAME=RUNDIR Original run (q245_orig.py --out; plan.json + logpos); the arm is NAME, with the request keys of a read appended
(`NAME` for plain reads, `NAME.k=v` for reads with keys)
--port NAME=LOG:CAPNAME:LABEL[,LABEL...]
port replay-smoke log (LELEKA_REPLAY_FORCE=1, LELEKA_TRACE_LOGPROBS=16, LELEKA_BRINGUP_TRACE=1) of the capture
dir <data>/cap-CAPNAME (sources in the order given to q245_prep.py mkcap); the arm labels (LELEKA_REPLAY_ARMS)
in order; the arm named LABEL becomes `NAME.LABEL`
--pair A:B compare B against A (A is the reference: d_top1 is taken on A's argmax); repeatable
--envelope A:B,A:B,... the pairs that form the Original's own envelope (tolerance = the largest value among them, per statistic)
--judge A:B,... the pairs judged against that tolerance
Row alignment: a row is keyed by its position (the input token's index); only positions of the reply region, from the last token of the prompt
(its row predicts the first reply token) to the second-to-last reply token, that both arms have are compared. Port rows are valid when the window's consumed tokens equal the path.
Statistics per pair (pooled over the rows, and per request): d_top1 = |lp_A(argmax_A) - lp_B(argmax_A)| (what decides tokens), dmax16 = largest
difference over the tokens both top-16 lists hold, argmax flips (with A's top1-top2 margin), top-5 / top-16 overlap, and on the forced text
dNLL = lp_A(target) - lp_B(target) per row (mean +- standard error; exp of the mean is the perplexity ratio B/A).
"""
import argparse, json, math, os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import q_lib
IM_START = 248045
def ids_file(path):
return [int(x) for x in open(path).read().strip().split(",") if x]
class Data:
def __init__(self, d):
self.d = d
self.meta = json.load(open(os.path.join(d, "meta.json")))["requests"]
self.prompts, self.replies = {}, {}
def prompt(self, k):
if k not in self.prompts:
self.prompts[k] = ids_file(os.path.join(self.d, f"p{k}.ids"))
return self.prompts[k]
def reply(self, source, k):
key = (source, k)
if key not in self.replies:
p = os.path.join(self.d, f"r_{source}{k}.ids")
self.replies[key] = ids_file(p) if os.path.exists(p) else None
return self.replies[key]
def path(self, source, k):
r = self.reply(source, k)
return None if r is None else self.prompt(k) + r
def region(data, source, k, rows):
"""rows {pos: Row} -> the rows of the reply region whose target is the path's next token."""
path = data.path(source, k)
p = len(data.prompt(k))
out = {}
for pos, row in rows.items():
if p - 1 <= pos < len(path) - 1 and row.target == path[pos + 1]:
out[pos] = row
return out
def load_orig(data, name, run_dir):
plan = json.load(open(os.path.join(run_dir, "plan.json")))
arms = {}
lines = open(os.path.join(run_dir, "logpos"), "rb").read()
for req in plan["requests"]:
if req["kind"] != "read":
continue
chunk = lines[req["off0"]:req["off1"]].decode("utf-8", "replace").split("\n")
rows = {}
for line in chunk:
row = q_lib.parse_row(line)
if row is not None:
rows[row.pos] = row
arm = name + ("." + req["keys"] if req["keys"] else "")
reg = region(data, req["source"], req["k"], rows)
if req.get("resume") is not None and req["resume"] > req["turn_at"]:
print(f"WARNING {arm} source {req['source']} k {req['k']}: resumed from {req['resume']} > turn_at {req['turn_at']}: rows missing", file=sys.stderr)
arms.setdefault(arm, {})[(req["source"], req["k"])] = reg
return arms
def load_port(data, name, log, capname, labels):
capdir = os.path.join(data.d, "cap-" + capname)
docs = []
for f in sorted(os.listdir(capdir)):
if f.startswith("req-") and f.endswith(".json"):
d = json.load(open(os.path.join(capdir, f)))
docs.append((d["source"], d["k"]))
arms = {}
by = {}
for run in q_lib.parse_port_log(log):
if run["forced"]:
by.setdefault(run["pass"], {})[run["index"]] = run
for pass_no, label in enumerate(labels):
for n, run in sorted(by.get(pass_no, {}).items()):
if n >= len(docs):
continue
source, k = docs[n]
path = data.path(source, k)
valid = q_lib.valid_rows(run["windows"], path)
arms.setdefault(f"{name}.{label}", {})[(source, k)] = region(data, source, k, valid)
return arms
def stats_of(rows):
"""rows: list of per-row dicts"""
n = len(rows)
if not n:
return {"n": 0}
d1 = [r["d_top1"] for r in rows if not math.isnan(r["d_top1"])]
dm = [r["dmax"] for r in rows if not math.isnan(r["dmax"])]
fl = [r for r in rows if r["flip"]]
dn = [r["dnll"] for r in rows]
mean = sum(dn) / n
sd = math.sqrt(sum((x - mean) ** 2 for x in dn) / max(1, n - 1))
return {"n": n, "missing_top1": n - len(d1),
"d_top1": {"p50": q_lib.quantile(d1, .5), "p90": q_lib.quantile(d1, .9), "p99": q_lib.quantile(d1, .99), "max": max(d1, default=float("nan"))},
"dmax16": {"p50": q_lib.quantile(dm, .5), "p99": q_lib.quantile(dm, .99), "max": max(dm, default=float("nan"))},
"flips": len(fl), "flip_rate": len(fl) / n,
"flip_margin_max": max((r["ref_margin"] for r in fl), default=0.0),
"decisive_flips": sum(1 for r in fl if r["ref_margin"] >= 0.25),
"top5": sum(r["top5"] for r in rows) / n, "top16": sum(r["top16"] for r in rows) / n,
"dnll_mean": mean, "dnll_se": sd / math.sqrt(n), "dnll_abs_mean": sum(abs(x) for x in dn) / n,
"nll_ref": -sum(r["lp_a"] for r in rows) / n, "nll_other": -sum(r["lp_b"] for r in rows) / n}
def pair_rows(a_arm, b_arm):
out = {}
for key in sorted(set(a_arm) & set(b_arm)):
A, B = a_arm[key], b_arm[key]
rows = []
for pos in sorted(set(A) & set(B)):
a, b = A[pos], B[pos]
common = [t for t, _ in a.topk if b.lp(t) is not None]
top1_b = b.lp(a.top1)
rows.append({
"pos": pos,
"d_top1": abs(a.topk[0][1] - top1_b) if top1_b is not None else float("nan"),
"dmax": max((abs(a.lp(t) - b.lp(t)) for t in common), default=float("nan")),
"flip": a.top1 != b.top1, "ref_margin": a.margin,
"top5": len({t for t, _ in a.topk[:5]} & {t for t, _ in b.topk[:5]}) / 5.0,
"top16": len(common) / float(len(a.topk)),
"dnll": a.lp_target - b.lp_target, "lp_a": a.lp_target, "lp_b": b.lp_target})
out[key] = rows
return out
def fmt(s):
if not s["n"]:
return "no common rows"
return (f"n {s['n']:5d} d_top1 p50 {s['d_top1']['p50']:.4f} p99 {s['d_top1']['p99']:.3f} max {s['d_top1']['max']:.3f} "
f"dmax16 p99 {s['dmax16']['p99']:.2f} max {s['dmax16']['max']:.2f} flips {s['flips']} ({100 * s['flip_rate']:.2f}%, max margin {s['flip_margin_max']:.2f}, "
f"decisive>=0.25: {s['decisive_flips']}) top5 {s['top5']:.3f} top16 {s['top16']:.3f} dNLL {s['dnll_mean']:+.4f}+-{s['dnll_se']:.4f} (|.| {s['dnll_abs_mean']:.4f}) ppl ratio {math.exp(-s['dnll_mean']):.4f}")
def pool(per):
return [r for rows in per.values() for r in rows]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--data", required=True)
ap.add_argument("--orig", action="append", default=[])
ap.add_argument("--port", action="append", default=[])
ap.add_argument("--pair", action="append", default=[])
ap.add_argument("--envelope", default="")
ap.add_argument("--judge", default="")
ap.add_argument("--sources", default="", help="restrict to these sources (comma list)")
ap.add_argument("--json", default="")
ap.add_argument("--per-request", action="store_true")
a = ap.parse_args()
data = Data(a.data)
arms = {}
for spec in a.orig:
name, d = spec.split("=", 1)
arms.update(load_orig(data, name, d))
for spec in a.port:
name, rest = spec.split("=", 1)
log, cap, labels = rest.split(":")
arms.update(load_port(data, name, log, cap, labels.split(",")))
keep = set(s for s in a.sources.split(",") if s)
if keep:
arms = {n: {k: v for k, v in arm.items() if k[0] in keep} for n, arm in arms.items()}
print("arms:", {n: sorted(arm) and sum(len(v) for v in arm.values()) for n, arm in arms.items()})
for n, arm in arms.items():
miss = [(s, k) for s in sorted({s for s, _ in arm}) for k in sorted({k for _, k in arm}) if (s, k) not in arm]
if miss:
print(f" note: {n} lacks requests {miss}")
print(chr(10) + "FREE GREEDY REPLIES at each depth (the port's recorded reply of the capture against the Original's own free reply to the same prompt)")
for m in data.meta:
k = m["k"]
ra, rb = data.reply("port", k), data.reply("orig", k)
if ra is None or rb is None:
continue
n = next((i for i in range(min(len(ra), len(rb))) if ra[i] != rb[i]), None)
print(f" prompt {k} ({m.get('prompt_len')} tokens): port reply {len(ra)} tokens, Original reply {len(rb)} tokens, first different token: {'none within the shorter' if n is None else n}")
results, cache = {}, {}
def evaluate(pairspec):
if pairspec in cache:
return cache[pairspec]
ra, rb = pairspec.split(":")
per = pair_rows(arms[ra], arms[rb])
pooled = stats_of(pool(per))
res = {"pooled": pooled, "per_request": {f"{s}{k}": stats_of(rows) for (s, k), rows in per.items()}}
cache[pairspec] = res
return res
pairs = list(a.pair) + [p for p in a.envelope.split(",") if p] + [p for p in a.judge.split(",") if p]
for p in dict.fromkeys(pairs):
res = evaluate(p)
results[p] = res
print(f"\n{p}\n pooled {fmt(res['pooled'])}")
if a.per_request:
for key, s in res["per_request"].items():
print(f" {key:8s} {fmt(s)}")
env = [p for p in a.envelope.split(",") if p]
if env:
tol = {"d_top1_p99": 0, "d_top1_max": 0, "dmax16_p99": 0, "flip_rate": 0, "flip_margin_max": 0, "dnll_abs_mean": 0, "dnll_mean_abs": 0, "top5_min": 1.0, "top16_min": 1.0}
for p in env:
s = results[p]["pooled"]
if not s["n"]:
continue
tol["d_top1_p99"] = max(tol["d_top1_p99"], s["d_top1"]["p99"])
tol["d_top1_max"] = max(tol["d_top1_max"], s["d_top1"]["max"])
tol["dmax16_p99"] = max(tol["dmax16_p99"], s["dmax16"]["p99"])
tol["flip_rate"] = max(tol["flip_rate"], s["flip_rate"])
tol["flip_margin_max"] = max(tol["flip_margin_max"], s["flip_margin_max"])
tol["dnll_abs_mean"] = max(tol["dnll_abs_mean"], s["dnll_abs_mean"])
tol["dnll_mean_abs"] = max(tol["dnll_mean_abs"], abs(s["dnll_mean"]))
tol["top5_min"] = min(tol["top5_min"], s["top5"])
tol["top16_min"] = min(tol["top16_min"], s["top16"])
print("\nTOLERANCE (the Original's own envelope, largest over " + ", ".join(env) + "):")
print(" " + json.dumps({k: round(v, 4) for k, v in tol.items()}))
results["tolerance"] = tol
for p in [x for x in a.judge.split(",") if x]:
s = results[p]["pooled"]
if not s["n"]:
print(f"JUDGE {p}: no rows")
continue
miss = lambda t5: max(0.0, 1.0 - t5)
ratios = {
"d_top1_p99": s["d_top1"]["p99"] / tol["d_top1_p99"],
"d_top1_max": s["d_top1"]["max"] / (1.6 * tol["d_top1_max"]), # the largest of 3000 rows is one sample: allowed 1.6x the Original pairs' largest
"flip_rate": s["flip_rate"] / tol["flip_rate"],
"mean|dNLL|": s["dnll_abs_mean"] / tol["dnll_abs_mean"],
"top5_miss": miss(s["top5"]) / max(1e-9, miss(tol["top5_min"])),
"mean_dNLL": abs(s["dnll_mean"]) / max(tol["dnll_mean_abs"], 2 * s["dnll_se"]),
}
worst = max(ratios.values())
verdict = "PASS" if worst <= 1.0 else ("INSIDE_1.25x" if worst <= 1.25 else "FAIL(" + ",".join(k for k, v in ratios.items() if v > 1.25) + ")")
print(f"JUDGE {p}: {verdict} ratio to the Original's envelope (d_top1_max against 1.6x): " + " ".join(f"{k} {v:.2f}" for k, v in ratios.items()))
results[p]["verdict"] = verdict
results[p]["ratios"] = ratios
if a.json:
json.dump(results, open(a.json, "w"), indent=1, default=lambda x: None)
if __name__ == "__main__":
main()