Files
leleka/scripts/quality/q245_orig.py
T

217 lines
11 KiB
Python

#!/usr/bin/env python3
"""Driver of the Original (vanilla Strata at the pin) for the 245k equivalence test (docs/quality-gate.md, "245k equivalence").
Runs on the 5090 server inside a holder-free window; offline measurement tool, nothing here is part of serving.
One engine process (`strata --serve`, the launch line of the vanilla launcher, both lossy defaults switched off) is fed request by request
over its stdin protocol (`GEN n [key=value ...] <ids>`); the log-probability rows of the verify windows (STRATA_LOGPOS, top-16) are cut per
request by file offset into <out>/plan.json.
pass F (--free) for every prompt k (descending depth): `GEN 300 <prompt k>`, the Original's own greedy reply -> <data>/r_orig<k>.ids
pass R (--sources a,b) for every prompt k (descending): `GEN 1 <prompt k + reply of source a>`, then the same with source b, ...
The prompt is read batched up to its last `<|im_start|>` (a checkpoint is stored there), the assistant header and the
reply go through the verify windows (--short-read), which is the only way the Original exposes log-probabilities.
The second source resumes from that checkpoint, so the prompt state is the same object for both sources.
--keys k=v[,k=v]: after the sources, the reads are repeated with these request keys (e.g. pcie_frac=0, an in-process
perturbation that is part of the Original's own envelope).
A decoy request (short unrelated prompt) separates the passes and the prompts so that no request resumes from another prompt's checkpoint
(descending depth already guarantees it for one-slot checkpoint caches; RESUME is recorded per request and checked).
usage: q245_orig.py --data DIR --out DIR [--free] [--sources port,orig] [--keys pcie_frac=0] [--prefill auto|N] [--tag NAME]
[--ks 5,4,3,2,1] [--max-new 300] [--engine PATH] [--extra-flag FLAG ...]
"""
import argparse, json, os, subprocess, sys, threading, time
ENGINE = os.path.expanduser("~/.local/share/strata/components/engine/0.1.50-linux-x86_64-cuda-cuda13/strata")
SHARDS = "/home/para/work/leleka/models/leleka-gates/assets/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-0000%d-of-00002.gguf"
PACK = os.path.expanduser("~/.local/share/strata/Strata-data/packs/iq3_s")
MTP = os.path.expanduser("~/.local/share/strata/Strata-data/mtp/rt")
PROFILE = os.path.expanduser("~/work/vanilla-strata/control/data/expert-profile.bin")
IM_START = 248045
def ids_file(path):
return [int(x) for x in open(path).read().strip().split(",") if x]
class Engine:
def __init__(self, out, prefill, extra, engine, env_extra, kind="vanilla", ple="gguf"):
self.out = out
if kind == "old":
# the reference build of the earlier gate (docs/quality-gate.md): Strata engine 0.1.35 + local patches, static tier, 2048 per-layer slots from the placeholder
# profile, the flags of scripts/quality/q-common.sh orig_serve; PLE from the GGUF shard 2 (--ple gguf) or from the KAR archive file, level 2 (--ple kar)
assets = "/home/para/work/leleka/models/leleka-gates/assets"
cmd = [engine, "--pack", assets + "/data/iq3_s", "--native", SHARDS % 1, "--ple-gguf", SHARDS % 2, "--serve", "--mtp", assets + "/data/mtp-rt", "--kv", "int8",
"--spec", "4", "--suffix-draft", "3", "--spec-min-p", "0.5", "--expert-profile", os.path.expanduser("~/work/gpu-runs/baseline/profile.bin"),
"--pcie-frac", "0.55", "--prefill", "8192" if prefill == "auto" else prefill, "--max-context", "262144", "--kv-resident", "20480",
"--prompt-cache", "1", "--prompt-cache-every", "0", "--prompt-cache-root", "0", "--short-read", "1024", "--expert-cache", "2048",
"--expert-cache-per-layer", "--adapt-every", "0"] + list(extra)
if ple == "kar":
cmd += ["--ple-kar", assets + "/qwen-iq3-s-l2-v4.kar", "--ple-kar-level", "2"]
else:
cmd = [engine, "--serve", "--pack", PACK, "--native", SHARDS % 1, "--ple-gguf", SHARDS % 2, "--expert-profile", PROFILE,
"--expert-cache", "auto", "--prefill", prefill, "--spec", "4", "--spec-min-p", "0.5", "--mtp", MTP,
"--max-context", "262144", "--kv", "int8", "--ple-io", "ram", "--kv-resident", "32768",
# the checkpoint of the last turn boundary is the only cache: one slot, no periodic checkpoints, no parked conversations
"--prompt-cache", "1", "--prompt-cache-every", "0", "--prompt-cache-root", "0", "--conversation-cache-mib", "0",
"--short-read", "1024"] + list(extra)
self.cmd = cmd
env = dict(os.environ)
env.update({"STRATA_ROUTE_TAIL_SKIP": "0", "STRATA_PREFILL_CPU_SHARE": "0", "STRATA_LOGPOS": os.path.join(out, "logpos"),
"STRATA_LOGPOS_TOPK": "16"})
env.update(env_extra)
self.env = env
open(os.path.join(out, "cmd.txt"), "w").write(" ".join(cmd) + "\n" + "\n".join(f"{k}={env[k]}" for k in sorted(env) if k.startswith("STRATA_")) + "\n")
self.err = open(os.path.join(out, "engine.err"), "wb")
self.proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self.err, env=env, bufsize=0)
self.lines = []
self.cv = threading.Condition()
threading.Thread(target=self._reader, daemon=True).start()
def _reader(self):
buf = b""
while True:
chunk = self.proc.stdout.read1(1 << 16) if hasattr(self.proc.stdout, "read1") else self.proc.stdout.read(1 << 16)
if not chunk:
break
buf += chunk
while b"\n" in buf:
line, buf = buf.split(b"\n", 1)
with self.cv:
self.lines.append(line.decode("utf-8", "replace"))
self.cv.notify_all()
with self.cv:
self.lines.append("<<EOF>>")
self.cv.notify_all()
def next_line(self, timeout):
end = time.time() + timeout
with self.cv:
while not self.lines:
left = end - time.time()
if left <= 0:
return None
self.cv.wait(left)
return self.lines.pop(0)
def wait_ready(self, timeout=1800):
end = time.time() + timeout
while time.time() < end:
line = self.next_line(5)
if line is None:
continue
if line.startswith("READY"):
return line
if line == "<<EOF>>":
raise RuntimeError("engine exited before READY; see engine.err")
raise RuntimeError("engine not ready in %d s" % timeout)
def request(self, line, timeout=3600):
self.proc.stdin.write((line + "\n").encode())
self.proc.stdin.flush()
toks, info, end = [], {}, time.time() + timeout
while time.time() < end:
l = self.next_line(30)
if l is None:
continue
if l == "<<EOF>>":
raise RuntimeError("engine died during a request; see engine.err")
if l.startswith("T "):
toks.append(int(l.split()[1]))
elif l.startswith("RESUME"):
info["resume"] = int(l.split()[1])
elif l.startswith("REUSED"):
info["reused"] = int(l.split()[1])
elif l.startswith("DONE"):
info["done"] = l
return toks, info
elif l.startswith("ERR"):
info["err"] = l
return toks, info
raise RuntimeError("request timed out")
def quit(self):
try:
self.proc.stdin.write(b"QUIT\n")
self.proc.stdin.flush()
except Exception:
pass
try:
self.proc.wait(120)
except Exception:
self.proc.kill()
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--data", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--free", action="store_true")
ap.add_argument("--sources", default="")
ap.add_argument("--keys", default="")
ap.add_argument("--prefill", default="auto")
ap.add_argument("--tag", default="orig")
ap.add_argument("--free-name", default="orig", help="the free replies are written to <data>/r_<free-name><k>.ids")
ap.add_argument("--ks", default="5,4,3,2,1")
ap.add_argument("--max-new", type=int, default=300)
ap.add_argument("--engine", default=ENGINE)
ap.add_argument("--kind", default="vanilla", choices=["vanilla", "old"])
ap.add_argument("--ple", default="gguf", choices=["gguf", "kar"])
ap.add_argument("--extra-flag", action="append", default=[])
ap.add_argument("--env", action="append", default=[], help="KEY=VALUE for the engine")
a = ap.parse_args()
os.makedirs(a.out, exist_ok=True)
ks = [int(x) for x in a.ks.split(",")]
sources = [s for s in a.sources.split(",") if s]
prompts = {k: ids_file(os.path.join(a.data, f"p{k}.ids")) for k in ks}
engine = a.engine
if a.kind == "old" and engine == ENGINE:
engine = "/home/para/work/leleka/models/leleka-gates/stra169-ladder/build-sm120/strata"
eng = Engine(a.out, a.prefill, a.extra_flag, engine, dict(e.split("=", 1) for e in a.env), a.kind, a.ple)
plan = {"tag": a.tag, "cmd": eng.cmd, "requests": []}
logpos = os.path.join(a.out, "logpos")
def size():
return os.path.getsize(logpos) if os.path.exists(logpos) else 0
def run(kind, k, source, keys, ids, gen):
before = size()
t0 = time.time()
toks, info = eng.request(f"GEN {gen} " + (" ".join(keys.split(",")) + " " if keys else "") + ",".join(map(str, ids)))
rec = {"kind": kind, "k": k, "source": source, "keys": keys, "n_ids": len(ids), "turn_at": max(i for i, t in enumerate(ids) if t == IM_START),
"off0": before, "off1": size(), "resume": info.get("resume"), "reused": info.get("reused"), "done": info.get("done"),
"err": info.get("err"), "wall_s": round(time.time() - t0, 1), "n_tokens": len(toks)}
plan["requests"].append(rec)
json.dump(plan, open(os.path.join(a.out, "plan.json"), "w"), indent=1)
print(json.dumps({x: rec[x] for x in ("kind", "k", "source", "keys", "n_ids", "resume", "wall_s", "n_tokens", "err")}), flush=True)
return toks
def decoy():
ids = [IM_START] + [1000 + (i * 7) % 5000 for i in range(1500)] + [IM_START, 872, 198, 4]
run("decoy", 0, "", "", ids, 1)
print("ready:", eng.wait_ready(), flush=True)
try:
if a.free:
decoy()
for k in ks:
toks = run("free", k, "", "", prompts[k], a.max_new)
open(os.path.join(a.data, f"r_{a.free_name}{k}.ids"), "w").write(",".join(map(str, toks)))
if sources:
decoy()
for k in ks:
for s in sources:
reply = ids_file(os.path.join(a.data, f"r_{s}{k}.ids"))
run("read", k, s, "", prompts[k] + reply, 1)
if a.keys:
for s in sources:
reply = ids_file(os.path.join(a.data, f"r_{s}{k}.ids"))
run("read", k, s, a.keys, prompts[k] + reply, 1)
finally:
eng.quit()
json.dump(plan, open(os.path.join(a.out, "plan.json"), "w"), indent=1)
print("done", flush=True)
if __name__ == "__main__":
main()