From d62603a956c8a4ad9750e9d22592d90e0ea9604a Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 4 Nov 2026 11:45:44 +0100 Subject: [PATCH 01/31] quality-245k: teacher-forced equivalence tooling (Original driver, port replay job, analysis, Codex long-context job) Scripts only, nothing runs in serving: q245_prep/orig/orig_job/window/freeze/port/analyze/pad/codex_job; cell.py gains --agents-md / --config-extra. Co-Authored-By: Claude Sonnet 5.5 --- scripts/e2e/codex/delta/cell.py | 9 ++ scripts/quality/q245_analyze.py | 256 ++++++++++++++++++++++++++++++ scripts/quality/q245_codex_job.sh | 182 +++++++++++++++++++++ scripts/quality/q245_freeze.sh | 14 ++ scripts/quality/q245_orig.py | 199 +++++++++++++++++++++++ scripts/quality/q245_orig_job.sh | 45 ++++++ scripts/quality/q245_pad.py | 38 +++++ scripts/quality/q245_port.sh | 64 ++++++++ scripts/quality/q245_prep.py | 92 +++++++++++ scripts/quality/q245_window.sh | 30 ++++ 10 files changed, 929 insertions(+) create mode 100644 scripts/quality/q245_analyze.py create mode 100644 scripts/quality/q245_codex_job.sh create mode 100644 scripts/quality/q245_freeze.sh create mode 100644 scripts/quality/q245_orig.py create mode 100644 scripts/quality/q245_orig_job.sh create mode 100644 scripts/quality/q245_pad.py create mode 100644 scripts/quality/q245_port.sh create mode 100644 scripts/quality/q245_prep.py create mode 100644 scripts/quality/q245_window.sh diff --git a/scripts/e2e/codex/delta/cell.py b/scripts/e2e/codex/delta/cell.py index 34c0276a..c2676e92 100644 --- a/scripts/e2e/codex/delta/cell.py +++ b/scripts/e2e/codex/delta/cell.py @@ -92,6 +92,8 @@ def main(): ap.add_argument("--engine-log", default="") ap.add_argument("--stack-meta", default="") ap.add_argument("--fix-date", default="2026-10-30", help="the Codex puts into the prompt is rewritten to this date by the proxy for every variant") + ap.add_argument("--agents-md", default="", help="a file copied to $CODEX_HOME/AGENTS.md: Codex puts it into the first request as a user message (the long-context pad of the 245k study; no 32 KiB cap for this location)") + ap.add_argument("--config-extra", default="", help="text appended to config.toml (e.g. model_auto_compact_token_limit)") ap.add_argument("--active-dir", default="", help="directory in which the workspace lives while Codex runs (moved into the cell afterwards)") a = ap.parse_args() @@ -145,7 +147,13 @@ def main(): os.makedirs(chome, mode=0o700) tmpl = open(os.path.join(HERE, "..", "config.toml.tmpl"), encoding="utf-8").read() cfg = tmpl.replace("@MODEL@", "qwen-local").replace("@BASE_URL@", "http://127.0.0.1:%d" % port).replace("@EFFORT@", a.effort) + if a.config_extra: + nl = chr(10) + marker = nl + "[sandbox_workspace_write]" + cfg = cfg.replace(marker, nl + a.config_extra.replace("|", nl) + nl + marker, 1) open(os.path.join(chome, "config.toml"), "w", encoding="utf-8").write(cfg) + if a.agents_md: + shutil.copyfile(a.agents_md, os.path.join(chome, "AGENTS.md")) # --- logging proxy pdir = os.path.join(cell, "proxy") @@ -265,6 +273,7 @@ def main(): "prompt_sha256": taskfile.sha256_text(prompt), "seed_digest": seed_digest, "codex_bin": a.codex_bin, "codex_sha256": a.codex_sha256, "upstream": a.upstream, "upstream_model": a.upstream_model, "engine_log_start_offset": elog_start, "active_workspace": os.path.join(active, "ws") if a.active_dir else final_ws, "tasks_manifest_sha256": taskfile.sha256_file(os.path.join(a.tasks_root, "MANIFEST.sha256")), + "agents_md": {"path": a.agents_md, "sha256": taskfile.sha256_file(a.agents_md), "bytes": os.path.getsize(a.agents_md)} if a.agents_md else None, "config_extra": a.config_extra, "final_message_tail": final_msg["text"][-800:], "stack": stack} tmp = os.path.join(cell, "cell.json.part") json.dump(info, open(tmp, "w"), indent=1) diff --git a/scripts/quality/q245_analyze.py b/scripts/quality/q245_analyze.py new file mode 100644 index 00000000..7f64ec1d --- /dev/null +++ b/scripts/quality/q245_analyze.py @@ -0,0 +1,256 @@ +#!/usr/bin/env python3 +"""Analysis of the 245k equivalence test (docs/quality-gate.md, "245k equivalence"). Offline; no runtime use. + +Inputs + --data DIR q245_prep output (p.ids, r_.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 /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}") + 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 + checks = { + "d_top1_p99": s["d_top1"]["p99"] <= tol["d_top1_p99"], + "d_top1_max": s["d_top1"]["max"] <= tol["d_top1_max"], + "flip_rate": s["flip_rate"] <= tol["flip_rate"], + "dnll_abs_mean": s["dnll_abs_mean"] <= tol["dnll_abs_mean"], + "dnll_mean": abs(s["dnll_mean"]) <= max(tol["dnll_mean_abs"], 2 * s["dnll_se"]), + "top5": s["top5"] >= tol["top5_min"], + } + verdict = "PASS" if all(checks.values()) else "FAIL(" + ",".join(k for k, v in checks.items() if not v) + ")" + print(f"JUDGE {p}: {verdict} " + " ".join(f"{k}={'ok' if v else 'OUT'}" for k, v in checks.items())) + results[p]["verdict"] = verdict + if a.json: + json.dump(results, open(a.json, "w"), indent=1, default=lambda x: None) + + +if __name__ == "__main__": + main() diff --git a/scripts/quality/q245_codex_job.sh b/scripts/quality/q245_codex_job.sh new file mode 100644 index 00000000..cb1483fa --- /dev/null +++ b/scripts/quality/q245_codex_job.sh @@ -0,0 +1,182 @@ +#!/usr/bin/env bash +# 245k study, tool-call integrity (STRA-328): the real Codex CLI at long context (a ~160k-token AGENTS.md pad in CODEX_HOME + the frozen task set), +# against the port with prefix_cache_tail=reply (shipped), the port with the tail off, and the Original (vanilla Strata 0.2.6). Test tooling, never in serving. +# +# QC_MODE=ours HOLDER JOB (inherits the sealed KAR memfd): unpacks the release package, `leleka up --foreground --kar-fd` once per arm in QC_ARMS +# ("reply off"; reply = the profile's shipped tail, off = `--prefix-cache-tail off`), cells in each, SIGTERM. +# QC_MODE=vanilla holder-free window payload (started by q245_window.sh with Q_PAYLOAD=q245_codex_job.sh): vanilla launcher, both lossy defaults off +# (STRATA_ROUTE_TAIL_SKIP=0, STRATA_PREFILL_CPU_SHARE=0), cells, `launch --stop`. +# QC_TASKS ("fixbug-ledger debuglog-sched") QC_REPS ("1 2 3") QC_PAD (default $Q/inputs/codex/pad.md) QC_RUN (output dir) QC_TAG (cell label suffix) +# QC_CAPTURE=1 (ours): LELEKA_CAPTURE_DIR=$RUN/capture- (prompt and generated token ids of every request, for the teacher-forced scoring) +# QC_TARBALL (ours, default the final release package) QC_WALL (cell wall limit s, default 1800) QC_ROUNDS (round cap, default 150) +# One cell = cell.py of the codex-lossy-delta study (logging proxy, temperature 0 injected for every variant, task acceptance) + the pad. Cell order alternates +# the tasks inside each repetition. Output: $RUN//-r/ (cell.json, proxy/, acceptance.log, codex-events.jsonl ...), $RUN//stack/. +set -uo pipefail +MODE=${QC_MODE:?QC_MODE ours|vanilla} +Q=/data/leleka-e2e/quality-245k +CLD=/data/leleka-e2e/codex-lossy-delta +TASKS_ROOT=$CLD/tasks +CODEX=/home/para/work/codex-e2e/bin/codex +LOCK=/data/leleka-e2e/gpu.lock +G=$HOME/work/gpu-runs +A=/home/para/work/leleka/models/leleka-gates/assets +CUBLAS=$HOME/cuda-toolkits/cublas-12.9.1.4/lib +PAD=${QC_PAD:-$Q/inputs/codex/pad.md} +TASKS=${QC_TASKS:-"fixbug-ledger debuglog-sched"} +REPS=${QC_REPS:-"1 2 3"} +RUN=${QC_RUN:-$Q/runs/codex-$MODE-$(date -u +%Y%m%dT%H%M%SZ)} +WALL=${QC_WALL:-1800}; ROUNDS=${QC_ROUNDS:-150} +CONFIG_EXTRA='model_auto_compact_token_limit = 100000000' +mkdir -p "$RUN" +exec > >(tee -a "$RUN/job.log") 2>&1 +log() { echo "[q245-codex $MODE $(date -u +%T)] $*"; } +note() { echo "[$(date -u +%FT%TZ)] [DEV quality-245k] $*" >>/data/leleka-e2e/decode/notes.md; } + +# ---- guards --------------------------------------------------------------------------------------------------------------------------------- +( cd / && sha256sum --quiet -c "$Q/inputs/codex/MANIFEST.sha256" ) || { echo "codex inputs differ from MANIFEST.sha256"; exit 3; } +python3 -I "$Q/codex/delta/taskfile.py" check "$TASKS_ROOT" >"$RUN/tasks-check.txt" 2>&1 || { echo "task files differ from their manifest"; cat "$RUN/tasks-check.txt"; exit 3; } +[ -x "$CODEX" ] || { echo "no codex binary"; exit 3; } +[ -f "$PAD" ] || { echo "no pad $PAD"; exit 3; } +STANDALONE=0; FD=${LELEKA_STRA169_KAR_FD:-} +if [ "$MODE" = ours ]; then + readlink "/proc/self/fd/$FD" 2>/dev/null | grep -q '^/memfd:' || { echo "ours mode needs the holder's sealed memfd"; exit 3; } + [ -d "$G/MODEL.lock" ] || { echo "MODEL.lock is not held"; exit 3; } +else + mkdir "$G/MODEL.lock" 2>/dev/null || { echo "MODEL.lock is held (holder still up?)"; exit 3; }; STANDALONE=1 +fi +got=0 +for _ in $(seq 1 4320); do + if mkdir "$LOCK" 2>/dev/null; then echo "quality-245k codex $MODE $(date -u +%FT%TZ) $RUN" >"$LOCK/owner"; got=1; break; fi + sleep 5 +done +[ $got = 1 ] || { echo "GPU lock held by: $(cat $LOCK/owner 2>/dev/null)"; [ $STANDALONE = 1 ] && rmdir "$G/MODEL.lock"; exit 3; } +SUP_PID= +stop_stack() { + if [ -n "$SUP_PID" ] && kill -0 "$SUP_PID" 2>/dev/null; then kill -TERM "$SUP_PID" 2>/dev/null; for _ in $(seq 1 120); do kill -0 "$SUP_PID" 2>/dev/null || break; sleep 2; done; fi + SUP_PID= +} +cleanup() { + stop_stack + pkill -KILL -f "$RUN/prefix/bin/" 2>/dev/null + if [ "$MODE" = vanilla ]; then ( cd "$HOME/work/vanilla-strata/control" && ./bin/strata launch --stop >/dev/null 2>&1 ); fi + sleep 3 + rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null + [ $STANDALONE = 1 ] && rmdir "$G/MODEL.lock" 2>/dev/null + note "codex job $MODE ended: $RUN" +} +trap cleanup EXIT +note "codex job $MODE started: $RUN tasks=[$TASKS] reps=[$REPS] pad=$(wc -c <"$PAD") bytes; holds gpu.lock" +if [ -n "$(nvidia-smi --query-compute-apps=pid --format=csv,noheader 2>/dev/null)" ]; then echo "something uses the GPU"; exit 3; fi +if pgrep -u "$USER" -x 'leleka-inference|strata-next|leleka-daemon' >/dev/null; then echo "a stack process exists"; exit 3; fi +for p in 18766 18080 8081 8090; do ss -ltn "sport = :$p" 2>/dev/null | grep -q LISTEN && { echo "port $p in use"; exit 3; }; done +export LD_LIBRARY_PATH=$CUBLAS:$HOME/cuda-toolkits/13.2.2/lib64:${LD_LIBRARY_PATH:-} +{ date -u +%FT%TZ; uname -r; nvidia-smi --query-gpu=name,driver_version,power.limit --format=csv,noheader; free -g | sed -n 2p; uptime; $CODEX --version; sha256sum "$CODEX" "$PAD"; } | tee "$RUN/host.txt" + +smoke_check() { # same arguments as run_cells: one smoke-mini cell; the first request must carry the pad (>= 120k input tokens) + local arm=$1 var=$2 url=$3 model=$4 elog=$5 key=$6 CELL=$RUN/$arm/smoke-mini-r0 n + mkdir -p "$RUN/$arm" + E2E_API_KEY=${key:-none} CLD_CODEX=$CODEX timeout 1500 python3 -I "$Q/codex/delta/cell.py" --cell-dir "$CELL" --variant "$var" --task smoke-mini --rep 0 --tasks-root "$TASKS_ROOT" --upstream "$url" --upstream-model "$model" --codex-bin "$CODEX" --wall-limit 900 --max-rounds 60 --engine-log "$elog" --active-dir "$RUN/active-$arm" --agents-md "$PAD" --config-extra "$CONFIG_EXTRA" >"$CELL.out" 2>&1 + n=$(python3 -I -c " +import json,sys +r=[json.loads(l) for l in open('$CELL/proxy/rounds.jsonl')] +r=[x for x in r if str(x.get('path','')).endswith('/responses')] +print((r[0].get('resp') or {}).get('input_tokens') or 0 if r else 0, len(r))" 2>/dev/null) + log "smoke $arm: first request input tokens / requests: $n; $(tail -1 "$CELL.out" | cut -c1-160)" + [ "${n%% *}" -ge 120000 ] 2>/dev/null +} + +run_cells() { # $1 arm label, $2 variant label, $3 upstream url, $4 upstream model, $5 engine log, $6 api key ('' = none) + local arm=$1 var=$2 url=$3 model=$4 elog=$5 key=$6 rep task t1 rc + mkdir -p "$RUN/$arm" + for rep in $REPS; do + for task in $TASKS; do + CELL=$RUN/$arm/$task-r$rep + t1=$(date +%s) + E2E_API_KEY=${key:-none} CLD_CODEX=$CODEX timeout $((WALL + 900)) python3 -I "$Q/codex/delta/cell.py" --cell-dir "$CELL" --variant "$var" --task "$task" --rep "$rep" \ + --tasks-root "$TASKS_ROOT" --upstream "$url" --upstream-model "$model" --codex-bin "$CODEX" --wall-limit "$WALL" --max-rounds "$ROUNDS" \ + --engine-log "$elog" --active-dir "$RUN/active-$arm" --agents-md "$PAD" --config-extra "$CONFIG_EXTRA" >"$CELL.out" 2>&1; rc=$? + log "cell $arm $task r$rep rc=$rc $(( $(date +%s) - t1 )) s: $(tail -1 "$CELL.out" | cut -c1-200)" + python3 -I - "$CELL" <<'PY' +import json, os, sys +d = sys.argv[1] +try: + c = json.load(open(os.path.join(d, "cell.json"))) + r = [json.loads(l) for l in open(os.path.join(d, "proxy", "rounds.jsonl"))] + rounds = [x for x in r if str(x.get("path", "")).endswith("/responses")] + print(" accepted=%s termination=%s wall=%.0fs requests=%d first_input_tokens=%s last_input_tokens=%s" % ( + c.get("accepted"), c.get("termination"), c.get("wall_s", 0), len(rounds), + (rounds[0].get("resp") or {}).get("input_tokens") if rounds else None, (rounds[-1].get("resp") or {}).get("input_tokens") if rounds else None)) +except Exception as e: + print(" (no summary: %s)" % e) +PY + done + done +} + +if [ "$MODE" = ours ]; then + # ---- the release package, unpacked once; one `leleka up --foreground` per arm -------------------------------------------------------------- + TARBALL=${QC_TARBALL:-/data/leleka-e2e/release-5090/leleka-0.1.0-17e372944279-5090-linux-x86_64.tar.xz} + mkdir -p "$RUN/pkg" && tar -xJf "$TARBALL" -C "$RUN/pkg" --strip-components=1 || { echo "unpack failed"; exit 5; } + P=$RUN/pkg; BIN=$P/bin + ( cd "$P" && sha256sum --quiet -c SHA256SUMS && echo "SHA256SUMS ok" ); "$BIN/leleka" version | tee "$RUN/version.txt" + AS=$RUN/assets; mkdir -p "$AS/data" + ln -s "$A/model" "$AS/model"; ln -s "$A/tokenizer-assets" "$AS/tokenizer-assets"; ln -s "$A/qwen-iq3-s-l2-v4.kar" "$AS/qwen-iq3-s-l2-v4.kar" + cp "$A/qwen-iq3-s-l2-v4.kar.provenance.json" "$AS/qwen-iq3-s-l2-v4.kar.provenance.json" + cp -al "$A/data/iq3_s" "$AS/data/iq3_s"; cp -al "$A/data/mtp-rt" "$AS/data/mtp-rt" + ST=$RUN/state; PFX=$RUN/prefix + COMMON="--assets $AS --state-dir $ST --prefix $PFX --bin-src $BIN --cublas-dir $CUBLAS --trust-archive --kar-fd $FD" + timeout 3000 "$BIN/leleka" up --mode none $COMMON >"$RUN/up-prepare.txt" 2>&1; log "up --mode none rc=$?" + [ -f "$ST/leleka.json" ] || { echo "up did not prepare the state"; tail -20 "$RUN/up-prepare.txt"; exit 6; } + for ARM in ${QC_ARMS:-reply off}; do + FLAGS=""; [ "$ARM" = off ] && FLAGS="--prefix-cache-tail off" + CAPENV=""; [ "${QC_CAPTURE:-0}" = 1 ] && [ "$ARM" = reply ] && { mkdir -p "$RUN/capture-$ARM"; CAPENV="$RUN/capture-$ARM"; } + ST_ARM=$RUN/$ARM; mkdir -p "$ST_ARM/stack" + log "arm $ARM: leleka up --foreground $FLAGS capture=[$CAPENV]" + t0=$(date +%s) + env ${CAPENV:+LELEKA_CAPTURE_DIR=$CAPENV} setsid "$BIN/leleka" up --foreground $COMMON --timeout-s 1800 $FLAGS >"$ST_ARM/stack/up-foreground.txt" 2>&1 & + SUP_PID=$! + ready=0 + for _ in $(seq 1 700); do + if "$PFX/bin/leleka" status --state-dir "$ST" >/dev/null 2>&1; then ready=1; break; fi + kill -0 "$SUP_PID" 2>/dev/null || break + sleep 3 + done + if [ $ready != 1 ]; then log "arm $ARM NOT READY after $(( $(date +%s) - t0 )) s"; tail -20 "$ST_ARM/stack/up-foreground.txt" | cut -c1-240; stop_stack; continue; fi + log "arm $ARM ready after $(( $(date +%s) - t0 )) s" + "$PFX/bin/leleka" status --state-dir "$ST" >"$ST_ARM/stack/status.txt" 2>&1; "$PFX/bin/leleka" status --state-dir "$ST" --json >"$ST_ARM/stack/status.json" 2>&1 + "$PFX/bin/leleka" verify --quick --state-dir "$ST" --assets "$AS" >"$ST_ARM/stack/verify-quick.txt" 2>&1 + grep -iE "tail|prefix" "$ST_ARM/stack/status.txt" | head -5 | cut -c1-200 + KEY=$(cat "$ST/api-key") + smoke_check "$ARM" "Q-$ARM" http://127.0.0.1:8081 qwen-iq3 "$ST/logs/engine.log" "$KEY" || { log "arm $ARM: the pad did not reach the engine (or the smoke cell failed): skipping the arm"; stop_stack; continue; } + run_cells "$ARM" "Q-$ARM" http://127.0.0.1:8081 qwen-iq3 "$ST/logs/engine.log" "$KEY" + cp "$ST/logs/engine.log" "$ST_ARM/stack/engine.log" 2>/dev/null; cp "$ST/logs/requests.log" "$ST_ARM/stack/requests.log" 2>/dev/null + "$PFX/bin/leleka" verify --quick --state-dir "$ST" --assets "$AS" >"$ST_ARM/stack/verify-quick-end.txt" 2>&1 + stop_stack + log "arm $ARM stack stopped" + sleep 20 + done +else + # ---- vanilla Strata 0.2.6 (launcher + engine 0.1.50), both lossy defaults off, state redirected into the run directory ----------------------------- + ARM=vanilla; ST_ARM=$RUN/$ARM; mkdir -p "$ST_ARM/stack" + export XDG_CONFIG_HOME=$ST_ARM/stack/xdg-config XDG_STATE_HOME=$ST_ARM/stack/xdg-state + mkdir -p "$XDG_CONFIG_HOME/strata" "$XDG_STATE_HOME"; cp ~/.config/strata/settings.json "$XDG_CONFIG_HOME/strata/" + export STRATA_ROUTE_TAIL_SKIP=0 STRATA_PREFILL_CPU_SHARE=0 + unset STRATA_DECODE_TIMING STRATA_VERIFY_PROFILE + S=$HOME/work/vanilla-strata/control/bin/strata + { sha256sum "$HOME/.local/share/strata/components/engine/0.1.50-linux-x86_64-cuda-cuda13/strata"; cat "$HOME/work/vanilla-strata/control/VERSION" "$HOME/work/vanilla-strata/control/COMMIT" 2>/dev/null; env | grep -E '^STRATA_' | sort; } >"$ST_ARM/stack/env.txt" + cd "$HOME/work/vanilla-strata/control" + t0=$(date +%s) + timeout 2400 "$S" launch --model iq3_s --family qwen --model-path "$A/model" --context 256k --kv int8 --vision off --parallel 1 --tune skip --access local --port 8090 --no-api-key --no-tui --yes >"$ST_ARM/stack/launch.out" 2>&1 + log "vanilla launch rc=$? ready after $(( $(date +%s) - t0 )) s" + if curl -fs http://127.0.0.1:8090/v1/models >"$ST_ARM/stack/models.json"; then + MODEL=$(python3 -c "import json;print(json.load(open('$ST_ARM/stack/models.json'))['data'][0]['id'])") + smoke_check "$ARM" "Q-vanilla" http://127.0.0.1:8090 "$MODEL" "$XDG_STATE_HOME/strata/launch/iq3_s-256k.engine.log" "" || log "vanilla: smoke cell failed or the pad was not in the first request: continuing anyway" + run_cells "$ARM" "Q-vanilla" http://127.0.0.1:8090 "$MODEL" "$XDG_STATE_HOME/strata/launch/iq3_s-256k.engine.log" "" + cp "$XDG_STATE_HOME/strata/launch/iq3_s-256k.engine.log" "$ST_ARM/stack/engine.log" 2>/dev/null + else + log "vanilla did not become ready" + fi + "$S" launch --stop >>"$ST_ARM/stack/launch.out" 2>&1 + sleep 8 +fi +log "done" diff --git a/scripts/quality/q245_freeze.sh b/scripts/quality/q245_freeze.sh new file mode 100644 index 00000000..1bf7a747 --- /dev/null +++ b/scripts/quality/q245_freeze.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# Freeze the inputs of the 245k equivalence test (rnr5090): build the two-source capture dir (cap-both = all prompts with the port's recorded replies, then all +# prompts with the Original's own free replies), write MANIFEST.sha256 (data, the job scripts, test binary; absolute paths, checked by every port job with `cd / && sha256sum -c`) +# and make the data read-only. Run once, after the Original's free pass has written r_orig.ids. No hard delete: nothing is removed. +set -euo pipefail +Q=/data/leleka-e2e/quality-245k +cd "$Q/inputs" +for k in 1 2 3 4 5; do [ -s data/r_orig$k.ids ] || { echo "missing data/r_orig$k.ids (run the Original's free pass first)"; exit 3; }; done +chmod -R u+w data 2>/dev/null || true +python3 -I "$Q/tools/q245_prep.py" mkcap data port,orig both +{ find "$Q/inputs/data" -type f | sort | xargs sha256sum; sha256sum "$Q"/tools/q245_port.sh "$Q"/tools/q245_orig.py "$Q"/tools/q245_orig_job.sh "$Q"/bin/*; sha256sum "$Q"/inputs/night5-source.sha256; } > MANIFEST.sha256.new +mv MANIFEST.sha256.new MANIFEST.sha256 +chmod -R a-w data +echo "frozen: $(wc -l < MANIFEST.sha256) files in $Q/inputs/MANIFEST.sha256" diff --git a/scripts/quality/q245_orig.py b/scripts/quality/q245_orig.py new file mode 100644 index 00000000..7c06f37b --- /dev/null +++ b/scripts/quality/q245_orig.py @@ -0,0 +1,199 @@ +#!/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 ...] `); the log-probability rows of the verify windows (STRATA_LOGPOS, top-16) are cut per +request by file offset into /plan.json. + + pass F (--free) for every prompt k (descending depth): `GEN 300 `, the Original's own greedy reply -> /r_orig.ids + pass R (--sources a,b) for every prompt k (descending): `GEN 1 `, 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): + self.out = out + 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("<>") + 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 == "<>": + 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 == "<>": + 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 /r_.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("--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} + eng = Engine(a.out, a.prefill, a.extra_flag, a.engine, dict(e.split("=", 1) for e in a.env)) + 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() diff --git a/scripts/quality/q245_orig_job.sh b/scripts/quality/q245_orig_job.sh new file mode 100644 index 00000000..ec0f70a3 --- /dev/null +++ b/scripts/quality/q245_orig_job.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# 245k equivalence test, Original side: a holder-free window payload (rnr5090). The Original (vanilla Strata 0.2.6 engine 0.1.50, the pin's code) needs the +# host RAM the lab holder's sealed archive occupies, so it never runs beside the holder (docs/quality-gate.md, "245k equivalence"). +# +# stub ~/work/gpu-runs/holder2/jobs/.sh: +# eval "exec ${LELEKA_STRA169_KAR_FD:-9}>&-" +# touch "$HOME/work/gpu-runs/holder2/jobs/STOP" +# Q_RUNS="|;..." setsid nohup bash /data/leleka-e2e/quality-245k/tools/q245_window.sh