Files
Pavlo RatushnyiandClaude Sonnet 5.5 5e4c9c9530 models: all model paths point into the work folder (models/leleka-gates, models/deepseek-v41-flash)
Rewrite the 5090 server model paths in 30 repo files (scripts, tools, docs) from the old
locations (/home/para/leleka-gates, $HOME/leleka-gates, /data/models) to
/home/para/work/leleka/models/..., add the AGENTS.md workspace rule and the move record
docs/experiments/models-move.md. Not merged: the smoke test is pending.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-29 19:12:29 +01:00

167 lines
7.0 KiB
Python

"""usage:
num_lad_tools.py extract JOBLOG CASEDIR -> CASEDIR/c<i>.ids (prompt) and c<i>.port (port greedy output)
num_lad_tools.py serve CASEDIR OUTDIR [nokar] [cpu|cpuorder] -> teacher-forced Original serve (patched binary), residual + ladder dumps in OUTDIR
num_lad_tools.py cmp JOBLOG CASEDIR PORTDIR ORIGDIR [case]
"""
import os, re, sys, math, array, subprocess
H = os.path.expanduser("~")
W = 4 * 2560
def extract(joblog, casedir):
os.makedirs(casedir, exist_ok=True)
for l in open(joblog, errors="replace"):
m = re.match(r"DBG corpus (\d+) prompt_ids \(\d+\): ([0-9,]+)", l)
if m:
open(f"{casedir}/c{m[1]}.ids", "w").write(m[2])
m = re.match(r"DBG corpus (\d+) output \((\d+) tokens, rounds \d+\): ([0-9 ]+)", l)
if m:
open(f"{casedir}/c{m[1]}.port", "w").write(m[3])
print(sorted(os.listdir(casedir)))
def serve(casedir, outdir, nokar=False, cpu_experts=False, cpu_order=False):
A = "/home/para/work/leleka/models/leleka-gates/assets"
exe = H + "/work/numerics-orig/build/strata"
cases = sorted({f.split(".")[0] for f in os.listdir(casedir)})
env = dict(os.environ)
env["LD_LIBRARY_PATH"] = H + "/cuda-toolkits/13.2.2/lib64:" + H + "/cuda-toolkits/cublas-12.9.1.4/lib"
env["STRATA_LOGPOS_TOPK"] = "8"
env["STRATA_LOGPOS"] = outdir + "/serve.logpos"
env["STRATA_NUM_RESID_DIR"] = outdir
env["STRATA_NUM_LADDER"] = "1"
os.makedirs(outdir, exist_ok=True)
args = [exe, "--serve", "--pack", A + "/data/iq3_s", "--native", A + "/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf",
"--ple-gguf", A + "/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf"]
if not nokar:
args += ["--ple-kar", A + "/qwen-iq3-s-l2-v4.kar", "--ple-kar-level", "2"]
args += ["--spec", "4", "--spec-min-p", "0.0", "--mtp", A + "/data/mtp-rt", "--expert-profile", H + "/work/gpu-runs/baseline/profile.bin",
*([] if cpu_experts else ["--expert-cache", "2048", "--expert-cache-per-layer"]), "--vram-reserve-mib", "700", "--max-context", "4096", "--kv", "int8",
"--prefill", "256", "--short-read", "4096", "--prompt-cache", "0"]
if cpu_order:
args += ["--expert-cache-cpu-order"]
p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=open(outdir + "/serve.err", "wb"), env=env, text=True, bufsize=1)
while True:
l = p.stdout.readline()
if not l:
print("engine died before READY"); sys.exit(1)
if l.startswith("READY"):
break
for c in cases:
ids = open(f"{casedir}/{c}.ids").read().strip()
port = open(f"{casedir}/{c}.port").read().split()
full = ids + "," + ",".join(port)
# one window numbering per case: remember where this case starts in the err log
open(outdir + "/serve.err", "ab").write(f"CASE {c}\n".encode())
p.stdin.write(f"GEN 1 {full}\n"); p.stdin.flush()
while True:
l = p.stdout.readline()
if not l or l.startswith("DONE") or l.startswith("ERR"):
print(c, l.strip(), flush=True); break
p.stdin.close()
try:
p.wait(timeout=30)
except Exception:
p.kill()
def rd(path):
a = array.array("f")
with open(path, "rb") as f:
a.frombytes(f.read())
return a
def windows_port(joblog, case):
log = open(joblog, errors="replace").read().split("\n")
s = [i for i, l in enumerate(log) if l.startswith(f"DBG corpus {case} prompt_ids")][0]
e = [i for i, l in enumerate(log) if l.startswith(f"DBG corpus {case} output")][0]
out = []
for l in log[s:e]:
m = re.match(r"DBG residual window seq=(\d+) first=(\d+) rows=(\d+) inputs=\[([0-9, ]+)\]", l)
if m:
out.append((int(m[2]), [int(x) for x in m[4].split(",")], int(m[1])))
return out
def windows_orig(errlog, case):
# cases are served in sorted order, each from position 0: a window at pos0 0 starts the next case
index = -1
out = []
want = int(case[1:])
for l in open(errlog, errors="replace"):
m = re.match(r"NUMRESID seq=(\d+) pos0=(\d+) T=(\d+) tokens=([0-9,]+)", l)
if not m:
continue
if int(m[2]) == 0:
index += 1
if index == want:
out.append((int(m[2]), [int(x) for x in m[4].split(",")], int(m[1])))
return out
def valid_rows(wins, truth):
out = {}
for wi, (p0, toks, _) in enumerate(wins):
for k in range(len(toks)):
if p0 + k < len(truth) and toks[: k + 1] == truth[p0 : p0 + k + 1]:
out.setdefault(p0 + k, (wi, k))
else:
break
return out
def cmp(joblog, casedir, portdir, origdir, only=None):
cases = sorted({f.split(".")[0] for f in os.listdir(casedir)})
cache = {}
def frames(path, T):
if path not in cache:
cache[path] = rd(path)
return cache[path]
allrel = {} # frame -> list of relL2
final = []
for c in cases:
if only and c != only:
continue
idx = c[1:]
truth = [int(x) for x in open(f"{casedir}/{c}.ids").read().strip().split(",")] + [int(x) for x in open(f"{casedir}/{c}.port").read().split()]
pw = windows_port(joblog, idx)
ow = windows_orig(origdir + "/serve.err", c)
pv, ov = valid_rows(pw, truth), valid_rows(ow, truth)
common = sorted(set(pv) & set(ov))
print(f"case {c}: port windows {len(pw)} orig windows {len(ow)} valid rows port {len(pv)} orig {len(ov)} common {len(common)}")
for pos in common:
(pwi, pk), (owi, ok) = pv[pos], ov[pos]
pl = f"{portdir}/l_win{pw[pwi][2]:05d}_pos{pw[pwi][0]}.f32"
ol = f"{origdir}/l_win{ow[owi][2]:05d}_pos{ow[owi][0]}.f32"
if not (os.path.exists(pl) and os.path.exists(ol)):
continue
pT, oT = len(pw[pwi][1]), len(ow[owi][1])
a, b = frames(pl, pT), frames(ol, oT)
for fr in range(96):
x = a[(fr * pT + pk) * W : (fr * pT + pk + 1) * W]
y = b[(fr * oT + ok) * W : (fr * oT + ok + 1) * W]
num = sum((u - v) ** 2 for u, v in zip(x, y))
den = sum(v * v for v in y)
allrel.setdefault((c, fr), []).append(math.sqrt(num / den) if den else float("nan"))
print("frame(layer.half): median relL2 over matched rows, per case")
for fr in range(96):
row = []
for c in cases:
v = sorted(allrel.get((c, fr), []))
row.append("%s=%.2e(n=%d)" % (c, v[len(v) // 2], len(v)) if v else "%s=-" % c)
print("%2d.%d %s" % (fr // 2, fr % 2, " ".join(row)))
if __name__ == "__main__":
cmd = sys.argv[1]
if cmd == "extract":
extract(sys.argv[2], sys.argv[3])
elif cmd == "serve":
serve(sys.argv[2], sys.argv[3], "nokar" in sys.argv[4:], "cpu" in sys.argv[4:], "cpuorder" in sys.argv[4:])
elif cmd == "cmp":
cmp(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5], sys.argv[6] if len(sys.argv) > 6 else None)