Files
leleka/scripts/quality/q_port.py
T

395 lines
20 KiB
Python

"""Port sections of the quality-gate report (see q_analyze.py): port vs Original, port envelope, divergence positions, verdict."""
import math
from q_lib import compare, summary, valid_rows, load_case
EOS = 248046
def fmt(x, nd=3):
return "-" if x is None or (isinstance(x, float) and math.isnan(x)) else f"{x:.{nd}f}"
def gen_rng(q, case):
return q.meta[case]["n_prompt"] - 1, len(q.paths[case]) - 2
def forced_rows(q, run, i):
"""Rows of the port's forced pass for corpus prompt i, valid on the Original's pass-0 path O<i>."""
truth = q.paths[f"O{i}"]
for r in q.ports.get(run, []):
if r["index"] == i and r["pass"] == 0 and r["forced"]:
return valid_rows(r["windows"], truth), r
return None, None
def free_rows(q, run, i):
"""(rows, run record, path) of the port's free pass: rows valid on its own output path."""
for r in q.ports.get(run, []):
if r["index"] == i and r["pass"] == 1 and not r["forced"] and r["output"] is not None:
prompt = q.paths[f"O{i}"][: q.meta[f"O{i}"]["n_prompt"]]
path = prompt + r["output"]
return valid_rows(r["windows"], path), r, path
return None, None, None
def port_vs_original(q, out, result, ref_run, head, row_line):
out.append("## B. Port vs Original, teacher-forced along the Original's pass-0 greedy tokens\n")
out.append("Reference rows: the Original's R1 reads (static tier, the port's configuration family); the port's rows are its own "
"verify-window top-16 at every position of the forced path (rows after a rejected draft token are not on the path and are skipped).\n")
out.append(head)
per = {}
for run in q.ports:
rows = []
for i in range(6):
fr, rec = forced_rows(q, run, i)
ref = q.path_rows(ref_run, f"O{i}", [])
if fr is None or ref is None:
continue
lo, hi = gen_rng(q, f"O{i}")
rr = [dict(r, case=f"O{i}") for r in compare(ref, fr, lo, hi)]
per[(run, i)] = rr
rows += rr
if rows:
s = summary(rows)
result["port_vs_orig_" + run] = s
out.append(row_line(f"{run} vs R1", s))
out.append("")
return per
def per_prompt(q, out, per, row_line, head):
out.append("### B2. Per prompt (forced pass; each port run vs R1)\n")
cols = head.split("\n")[0].split("| rows |")[1].strip("| ")
out.append("| port run | prompt | forced-pass completion | " + cols + " |")
out.append("|---|---|---|" + "---|" * (cols.count("|") + 1))
for (run, i), rows in sorted(per.items()):
s = summary(rows)
_, rec = forced_rows(q, run, i)
note = "; ".join(n.split("forced:")[1].strip() for n in rec["notes"] if "forced:" in n) or "-"
line = row_line(f"{run} p{i}", s).split("|")
out.append(f"| {run} | p{i} | {note} | " + "|".join(line[3:]))
out.append("")
def port_envelope(q, out, result, head, row_line):
out.append("## C. Port vs port (same forced path, different configuration)\n")
out.append(head)
runs = list(q.ports)
base = "P1-static" if "P1-static" in runs else (runs[0] if runs else None)
for run in runs:
if run == base:
continue
rows = []
for i in range(6):
a, _ = forced_rows(q, base, i)
b, _ = forced_rows(q, run, i)
if a is None or b is None:
continue
lo, hi = gen_rng(q, f"O{i}")
rows += [dict(r, case=f"O{i}") for r in compare(a, b, lo, hi)]
if rows:
s = summary(rows)
result["port_env_" + run] = s
out.append(row_line(f"{run} vs {base}", s))
out.append("")
def divergence(q, out, ref_run):
out.append("## D. Where the port's free run leaves the Original's pass-0 tokens\n")
out.append("t* = first generated token that differs. Both engines' rows at t* are conditioned on the same text (the common prefix): "
"the Original's R1 read of its own path and the port's free-pass row. margin = top1 - top2 logprob of that engine's row.\n")
out.append("| port run | prompt | t* | Original token (lp; port's lp and rank) | port token (lp; Original's lp and rank) | Original margin | port margin | reading |")
out.append("|---|---|---|---|---|---|---|---|")
for run in q.ports:
for i in range(6):
fr, rec, path = free_rows(q, run, i)
if fr is None:
continue
n_p = q.meta[f"O{i}"]["n_prompt"]
orig = q.paths[f"O{i}"][n_p:]
mine = path[n_p:]
t = next((k for k in range(min(len(orig), len(mine))) if orig[k] != mine[k]), None)
if t is None:
out.append(f"| {run} | p{i} | none | identical for {min(len(orig), len(mine))} tokens | lengths {len(orig)}/{len(mine)} | | | "
f"{'same length' if len(orig) == len(mine) else 'LENGTH DIFFERS'} |")
continue
pos = n_p - 1 + t
o = q.path_rows(ref_run, f"O{i}", [])
if o is None or pos not in o or pos not in fr:
out.append(f"| {run} | p{i} | {t} | row missing | | | | |")
continue
ro, rp = o[pos], fr[pos]
ot, pt = orig[t], mine[t]
out.append(f"| {run} | p{i} | {t} | {ot} ({fmt(ro.lp(ot))}; port {fmt(rp.lp(ot))}, rank {rp.rank(ot) or '>16'}) | "
f"{pt} ({fmt(rp.lp(pt))}; Original {fmt(ro.lp(pt))}, rank {ro.rank(pt) or '>16'}) | {fmt(ro.margin)} | {fmt(rp.margin)} | "
f"{'near tie in both engines' if max(ro.margin, rp.margin) <= 0.5 else 'CHECK'} |")
out.append("")
def eos_section(q, out, ref_run):
out.append("## E2. Stop token (<|im_end|> 248046) at the end of the Original's paths\n")
out.append("| prompt | generated | Original R1: lp / rank of the stop token at the last row | port forced pass: lp / rank | forced pass produced |")
out.append("|---|---|---|---|---|")
for i in (2, 5):
c = f"O{i}"
last = len(q.paths[c]) - 2
o = q.path_rows(ref_run, c, [])
if o is None or last not in o:
continue
cells, stops = [], []
for run in q.ports:
fr, rec = forced_rows(q, run, i)
if fr and last in fr:
cells.append(f"{run}: {fmt(fr[last].lp(EOS))} / {fr[last].rank(EOS) or '>16'}")
if rec:
stops.append(f"{run}: " + ("; ".join(n.split('forced:')[1].strip() for n in rec['notes'] if 'forced:' in n) or "-"))
out.append(f"| p{i} | {len(q.paths[c]) - q.meta[c]['n_prompt']} | {fmt(o[last].lp(EOS))} / {o[last].rank(EOS) or '>16'} | "
f"{'; '.join(cells)} | {'; '.join(stops)} |")
out.append("")
def verdict(q, out, env, result):
arms = [v for k, v in env.items() if v["d_top1"]["max"] > 0 and "first reads" not in k]
if not arms:
return
t = {"d_top1_p99": max(a["d_top1"]["p99"] for a in arms), "d_top1_max": max(a["d_top1"]["max"] for a in arms),
"dmax_p99": max(a["dmax"]["p99"] for a in arms), "dmax_max": max(a["dmax"]["max"] for a in arms),
"flip_rate": max(a["flips"] / a["n"] for a in arms), "flip_margin": max((m for a in arms for m in a["flip_margins"]), default=0.0)}
result["tolerances"] = t
out.append("## V. Gate and verdict\n")
out.append("Tolerances = the largest value the Original shows against ITS OWN reference (R1) over the non-identical envelope arms of section A "
"(pcie_frac, near-empty tier, window width, repeated adaptive reads): "
f"d_top1 p99 <= {fmt(t['d_top1_p99'])}, d_top1 max <= {fmt(t['d_top1_max'])}, dmax16 p99 <= {fmt(t['dmax_p99'])}, "
f"dmax16 max <= {fmt(t['dmax_max'])}, argmax-flip rate <= {t['flip_rate'] * 100:.2f}%, Original margin at every flip <= {fmt(t['flip_margin'])}.\n")
out.append("| port arm | d_top1 p99 | d_top1 max | dmax16 p99 | dmax16 max | flip rate | max flip margin | result |")
out.append("|---|---|---|---|---|---|---|---|")
names = ["top1 p99", "top1 max", "dmax p99", "dmax max", "flip rate", "flip margin"]
for k, s in result.items():
if not k.startswith("port_vs_orig_"):
continue
fr = s["flips"] / s["n"]
fm = max(s["flip_margins"], default=0.0)
checks = [s["d_top1"]["p99"] <= t["d_top1_p99"], s["d_top1"]["max"] <= t["d_top1_max"], s["dmax"]["p99"] <= t["dmax_p99"],
s["dmax"]["max"] <= t["dmax_max"], fr <= t["flip_rate"], fm <= t["flip_margin"]]
res = "PASS" if all(checks) else "FAIL (" + ", ".join(n for n, c in zip(names, checks) if not c) + ")"
out.append(f"| {k[13:]} | {fmt(s['d_top1']['p99'])} | {fmt(s['d_top1']['max'])} | {fmt(s['dmax']['p99'])} | {fmt(s['dmax']['max'])} | "
f"{fr * 100:.2f}% | {fmt(fm)} | {res} |")
out.append("")
def batched_reference(q, out, result, head, row_line):
"""Port (forced pass) vs the Original's batched-prompt reads B<i> (first <=40 generated tokens of prompts 0..4)."""
rows_by_run = {}
for run in q.ports:
rows = []
for i in range(5):
b = q.path_rows(f"B{i}-batched", f"B{i}", [])
fr, _ = forced_rows(q, run, i)
if not b or fr is None:
continue
lo = q.meta[f"O{i}"]["n_prompt"] - 1
rows += [dict(r, case=f"O{i}") for r in compare(b, fr, lo, len(q.paths[f"B{i}"]) - 2)]
if rows:
rows_by_run[run] = rows
if not rows_by_run:
return
out.append("## B3. Port vs the Original with the prompt read the same (batched) way\n")
out.append("Original rows: the first <=40 generated tokens of prompts 0-4 read with the batched prompt path "
"(job 9963); the port's rows: its forced pass (batched prefill), same positions.\n")
out.append(head)
for run, rows in rows_by_run.items():
s = summary(rows)
result["port_vs_batched_" + run] = s
out.append(row_line(f"{run} vs Original (batched prompt)", s))
out.append("")
def parse_long_port(path, prompt):
"""{pos: Row} of the port's rows that lie on its own path (prompt + its output) in a long-context log: a row after a draft token that
was rejected is conditioned on text that is not on the path and is skipped."""
import re
from q_lib import parse_row, valid_rows
windows, win, output = [], None, None
for line in open(path, errors="replace"):
m = re.match(r"DBG logprobs window position=(\d+) inputs=\[([0-9, -]*)\]", line)
if m:
win = (int(m[1]), [int(x) for x in m[2].split(",") if x.strip()], [])
windows.append(win)
continue
m = re.match(r"long-smoke output ids \(\d+\): ([0-9,]*)", line)
if m and output is None:
output = [int(x) for x in m[1].split(",") if x]
continue
r = parse_row(line)
if r is not None and win is not None and len(win[2]) < len(win[1]):
win[2].append(r)
return valid_rows(windows, prompt + (output or []))
def long_section(q, out, result):
import glob
import os
from q_lib import orig_reads
chunks = [2048, 4096, 6144, 8192]
orig = {}
for c in chunks:
run = f"L-c{c}"
if run in q.reads:
reads = q.reads[run]
first = [v for k, v in reads.items() if k == "L16"]
if first:
orig[c] = first[0][2]
port = {}
for c in chunks:
p = os.path.join(q.d, "runs", f"PL-c{c}", "port.log")
if os.path.exists(p):
port[c] = parse_long_port(p, load_case(q.cases, "L16")[:16000])
if not orig and not port:
return
out.append("## L. 16,000-token prompt: logits at the three generated positions, by prefill chunk\n")
out.append("Rows 15999, 16000, 16001 predict generated tokens 0, 1, 2 (271, 248068, then 198 vs 271: the near tie). lp = log-probability; margin = lp(198) - lp(271).\n")
out.append("| chunk | engine | lp(271) @15999 | lp(248068) @16000 | lp(198) @16001 | lp(271) @16001 | margin 198-271 | argmax @16001 |")
out.append("|---|---|---|---|---|---|---|---|")
for c in chunks:
for name, src in (("Original", orig), ("port", port)):
if c not in src:
continue
r = src[c]
if not all(p in r for p in (15999, 16000, 16001)):
continue
a, b, d = r[15999], r[16000], r[16001]
l198, l271 = d.lp(198), d.lp(271)
out.append(f"| {c} | {name} | {fmt(a.lp(271))} | {fmt(b.lp(248068))} | {fmt(l198)} | {fmt(l271)} | "
f"{fmt(None if l198 is None or l271 is None else l198 - l271)} | {d.top1} |")
out.append("")
out.append("| chunk | port - Original @15999 (top1) | @16000 (top1) | @16001 lp(198) | @16001 lp(271) |\n|---|---|---|---|---|")
for c in chunks:
if c in orig and c in port and all(p in orig[c] and p in port[c] for p in (15999, 16000, 16001)):
o, p = orig[c], port[c]
out.append(f"| {c} | {fmt(p[15999].lp(271) - o[15999].lp(271))} | {fmt(p[16000].lp(248068) - o[16000].lp(248068))} | "
f"{fmt(p[16001].lp(198) - o[16001].lp(198))} | {fmt(p[16001].lp(271) - o[16001].lp(271))} |")
out.append("")
# chunk sensitivity of each engine: lp(198)-lp(271) spread over the chunk sizes
for name, src in (("Original", orig), ("port", port)):
vals = {c: src[c][16001].lp(198) - src[c][16001].lp(271) for c in chunks if c in src and 16001 in src[c]
and src[c][16001].lp(198) is not None and src[c][16001].lp(271) is not None}
if vals:
out.append(f"{name}: lp(198) - lp(271) at 16001 by chunk: " + ", ".join(f"{c}: {v:+.3f}" for c, v in sorted(vals.items()))
+ f" (spread {max(vals.values()) - min(vals.values()):.3f} nats)\n")
def pooled(q, out, result, ref_run="R1-static"):
"""Pooled comparison: all non-identical Original envelope arms vs all port arms (same reference rows, same positions)."""
from q_lib import compare
cases = [f"O{i}" for i in range(6)]
env_arms = [("R1-static", ["pcie_frac=0"], 0), ("R2-nearcpu", [], 0), ("R3-spec2", [], 0),
("R4-adaptive", ["pcie_frac=0.55"], 0), ("R4-adaptive", ["pcie_frac=0.55"], 1)]
env_rows, port_rows, pp_rows = [], [], []
for run, keys, k in env_arms:
for c in cases:
ref, oth = q.path_rows(ref_run, c, []), q.path_rows(run, c, keys, k)
if ref and oth:
lo, hi = q.meta[c]["n_prompt"] - 1, len(q.paths[c]) - 2
env_rows += [dict(r, case=c) for r in compare(ref, oth, lo, hi)]
base = "P1-static" if "P1-static" in q.ports else None
for run in q.ports:
for i in range(6):
fr, _ = forced_rows(q, run, i)
ref = q.path_rows(ref_run, f"O{i}", [])
if fr is None or ref is None:
continue
lo, hi = gen_rng(q, f"O{i}")
port_rows += [dict(r, case=f"O{i}") for r in compare(ref, fr, lo, hi)]
if base and run != base:
a, _ = forced_rows(q, base, i)
if a is not None:
pp_rows += [dict(r, case=f"O{i}") for r in compare(a, fr, lo, hi)]
if not env_rows or not port_rows:
return
out.append("## V2. Pooled over arms\n")
out.append("| pool | rows | d_top1 median | d_top1 p99 | d_top1 max | dmax16 p99 | flip rate | largest Original margin at a flip |\n|---|---|---|---|---|---|---|---|")
def line(label, rows):
s = summary(rows)
out.append(f"| {label} | {s['n']} | {fmt(s['d_top1']['median'])} | {fmt(s['d_top1']['p99'])} | {fmt(s['d_top1']['max'])} | {fmt(s['dmax']['p99'])} | "
f"{s['flips'] / s['n'] * 100:.2f}% | {fmt(max(s['flip_margins'], default=0.0))} |")
return s
result["pool_original"] = line("Original arms vs R1 (pcie 0, near-CPU tier, --spec 2, adaptive repeats 1-2)", env_rows)
result["pool_port"] = line(f"port arms vs R1 ({', '.join(q.ports)})", port_rows)
worst = max(port_rows, key=lambda r: r["d_top1"])
rest = [r for r in port_rows if not (r["case"] == worst["case"] and r["pos"] == worst["pos"])]
result["pool_port_wo_worst"] = line(f"same without the worst row ({worst['case']} position {worst['pos']}, d_top1 {worst['d_top1']:.2f}) in every arm", rest)
if pp_rows:
result["pool_port_port"] = line(f"port arms vs {base} (port's own envelope)", pp_rows)
out.append("")
def parse_long_multi(path):
"""[(prompt_tokens, windows, output)] of a port long-smoke log with several prompts."""
import re
from q_lib import parse_row
segs, cur, win = [], None, None
for line in open(path, errors="replace"):
m = re.match(r"long-smoke prompt tokens=(\d+)", line)
if m:
cur = {"n": int(m[1]), "windows": [], "output": None}
segs.append(cur)
win = None
continue
if cur is None:
continue
m = re.match(r"DBG logprobs window position=(\d+) inputs=\[([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"long-smoke output ids \(\d+\): ([0-9,]*)", line)
if m and cur["output"] is None:
cur["output"] = [int(x) for x in m[1].split(",") if x]
continue
r = parse_row(line)
if r is not None and win is not None and len(win[2]) < len(win[1]):
win[2].append(r)
return segs
def retrieval_section(q, out, result):
"""Teacher-forced comparison on the first <=120 tokens of the Original's 100k / 180k answers, and the divergence rows."""
import os
from q_lib import orig_reads
run = "RET-orig-read"
pf = os.path.join(q.d, "runs", "RET-port-forced", "port.log")
if not os.path.exists(os.path.join(q.d, "runs", run, "logpos")) or not os.path.exists(pf):
return
import re
reqs = [n for n in open(os.path.join(q.d, "runs", run, "reqs.txt")).read().split("\n") if n and n != "QUIT"]
from q_lib import load_orig_logpos
segs, _ = load_orig_logpos(os.path.join(q.d, "runs", run))
# only the answer reads log rows (the batched prompt reads do not): segments are 100k+answer, 180k+answer
orig = {100000: segs[0] if segs else None, 180000: segs[1] if len(segs) > 1 else None}
ports = {s["n"]: s for s in parse_long_multi(pf)}
out.append("## R. Long-context retrieval: teacher-forced along the Original's answers\n")
out.append("Original: prompt read batched (chunk 8192), the answer through the verify windows; port: forced pass, int8 KV streamed, chunk 8192. Rows from the last prompt token on.\n")
out.append("| prompt | answer tokens forced | rows compared | d_top1 med / p99 / max | dmax16 p99 / max | flips | Original margin at the flips | stop token lp/rank (Original; port) |")
out.append("|---|---|---|---|---|---|---|---|")
for n in (100000, 180000):
o, p = orig.get(n), ports.get(n)
if not o or not p:
continue
ans = [int(x) for x in open(os.path.join(q.d, "long-force", f"answer{n}.ids")).read().split(",")] if os.path.exists(os.path.join(q.d, "long-force", f"answer{n}.ids")) else []
# the path: prompt ids from the long-180k dir are not in cases; take them from the Original request line
line = [l for l in open(os.path.join(q.d, "runs", run, "reqs.txt")).read().split("\n") if l.startswith("GEN 1 ")][1 if n == 100000 else 3]
path = [int(x) for x in line[len("GEN 1 "):].split(",")]
rows = valid_rows(p["windows"], path)
lo, hi = n, len(path) - 2 # the resumed Original request logs from the first answer row's input (position n)
cmp_ = compare(o, rows, lo, hi)
if not cmp_:
continue
s = summary(cmp_)
result[f"retrieval_{n}"] = s
stop = len(path) - 2
eos = (o.get(stop), rows.get(stop))
cell = " ; ".join(f"{fmt(r.lp(path[-1])) if r else '-'} / {r.rank(path[-1]) if r else '-'}" for r in eos)
out.append(f"| {n} | {len(path) - n} | {s['n']} | {fmt(s['d_top1']['median'])} / {fmt(s['d_top1']['p99'])} / {fmt(s['d_top1']['max'])} | "
f"{fmt(s['dmax']['p99'])} / {fmt(s['dmax']['max'])} | {s['flips']} | {', '.join(map(str, s['flip_margins'])) or '-'} | {cell} |")
out.append("")