okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-own-4h 041591f1d into f-own-int5993c50a5

main
28.5 KiB522 linesraw
1#!/usr/bin/env python3
2"""force_check.py: the token-forcing check (round 0217), after SpecPilot (arXiv 2611.02501, Li et al., Apache-2.0, "token forcing").
3
4A candidate engine/build/setting is judged on a FIXED text: the engine scores prompt + continuation teacher-forced (every position's head logits come
5out of the verify windows with the head in FP32: STRATA_LOGPOS / STRATA_LOGPOS_TOPK, the prompt cache off), and the checker counts where the scorer's
6argmax is not the forced token.  Nothing here depends on a drafter; it serves any class N change (Q5_0 experts, tree verify, a new kernel ...).
7
8  force_check.py gen   CFG SET.json --corpus held.jsonl [--kinds code,json] [--per-kind 4] [--offset 8] [--new 300] [--env K=V ...]
9        one engine with CFG's normal decode flags; greedy continuations of the corpus prompts (rows with "ids") -> SET.json
10  force_check.py score CFG SET.json OUT.tsv [--path decode|prompt] [--env K=V ...] [--arg "--flag v" ...]
11        --path decode (default): one engine with CFG's own flags (drafter, spec windows, adaptive tiers ...), prompt cache off; every request decodes the
12        forced continuation: the verify windows take the forced token in place of the argmax (STRATA_FOLLOW), so drafts are accepted when they match it,
13        and the FP32 head logits of every valid row come out (STRATA_FOLLOW_LOGPOS, top-2).  --path prompt: the whole text is read as a prompt through the
14        windows (STRATA_LOGPOS, --short-read), no decode features.  OUT.tsv.meta.json = per item line ranges.
15        --env STRATA_FORCE_FAULT=7:0.3 is the test fault (adds 0.3 to every 7th token's logit in the scored rows).
16  force_check.py check --stock A.tsv B.tsv [...] --cand C.tsv [--delta D] [--json out.json]
17        the two rules of the paper against the stock arms (>= 2 stock arms: the noise): exit 0 pass, 1 reject, 2 inconclusive
18  force_check.py selftest      the statistics on synthetic rows (no engine)
19
20  THE GATE FOR A CHANGE OF THE PROMPT ARITHMETIC (a prompt kernel, an expert format's prompt path; owner 11-10), a neutral writer:
21  force_check.py cut   IDS.txt CORPUS.jsonl [--sizes 4096,8192,20000] [--n 16]
22        prompt cuts of one long id file (N windows per size at fixed offsets) -> a corpus
23  force_check.py gen-neutral SET.json --corpus CORPUS.jsonl --writer /path/llama-server --writer-model SHARD1.gguf [--writer-args "-ngl 99 --cpu-moe"]
24                             [--writer-lib DIR ...] [--per-kind 16] [--new 128]
25        the continuations written by a program that is NEITHER arm: llama.cpp's llama-server on the same GGUF, greedy, the prompt passed as token ids
26        (the ids `score` feeds the engine), the generated ids read back (return_tokens) -> SET.json marked "writer": "neutral"
27  force_check.py gate  CFG SET.json OUTDIR --cand-env K=V [--cand-env ...] [--env K=V ...] [--arg "..."]
28        scores the neutral set through stock twice (stockA, stockB) and the candidate twice (candA, candB), --path decode, then:
29        PASS = each candidate arm against the two stock arms PASSES the rate rule and the event rule (check below); REJECT if any arm is rejected;
30        otherwise INCONCLUSIVE.  The reversed direction (each stock arm against the candidate arms) is reported in gate.json, not required.
31        Exit 0 pass, 1 reject, 2 inconclusive.  Size: 48 prompts (16 each at 4K / 8K / 20K) x 128 tokens = ~6,000 scored tokens an arm.
32        Why (11-10, UD-IQ4_XS-v31 on an R9700 and an RTX A6000, IQ3_XXS on the R9700): with the STOCK engine writing the text, the
33        rule measures the distance from the writer, not quality: (1) the FP16 prompt path, the reference of the KL gates, failed it on stock's
34        text by more than the kernel under test (+1.66 points, 90% CI [+1.17, +2.15], against the kernel's +1.14 [+0.62, +1.69], 12 prompts);
35        (2) with the CANDIDATE writing the text the stock engine failed by the same margin (+1.69 [+0.52, +2.93] and +1.56, REJECT, while the
36        candidate passed against stock); (3) with llama.cpp writing, the candidate passed in every pairing (R9700 v31 -0.39 [-0.85, +0.07] and
37        -0.33; R9700 IQ3_XXS -0.16 [-0.75, +0.42] twice; A6000 v31 48 prompts +0.21 [-0.05, +0.49] and +0.16), stock vs candidate reversed
38        PASS or INCONCLUSIVE.  Stock A and stock B are never byte-identical through the decode windows.
39  The stock-written form (gen with the stock engine, score, check) stays as a DIAGNOSTIC: it measures how far a candidate's arithmetic is
40  from the engine that wrote the text, and is not the gate for prompt-arithmetic changes.
41
42An "arm" = one scored TSV.  Which engine produced the continuation and which scored it is the caller's choice:
43  - a change of the prompt arithmetic (a prompt kernel, an expert format's prompt path): `gate` on a `gen-neutral` set (above);
44  - a change of the decode path (tree verify, a drafter): `gen` with the candidate, `score` with the STOCK scorer (the paper's way).
45Stock arms = the same procedure with the stock build, at least twice (a second `gen`, or a second `score`).
46
47Rules (paper):  mismatch = the scorer's argmax is not the forced token; margin = log p(argmax) - log p(forced token).
48  rate rule : candidate mismatch rate within +0.5 points of stock at 95% (one-sided bootstrap over requests, paired on the same positions).
49              REJECT if the 95% lower bound of (cand - stock) > 0.5 points; PASS if the 95% upper bound <= 0.5 points; else INCONCLUSIVE (more tokens).
50  event rule: delta = the largest margin among stock's first departures per request, rounded UP to a multiple of 1/8; a large-margin event is a
51              mismatch with margin > 2 delta.  REJECT if the candidate has more events than stock by an exact one-sided binomial test (p < 0.05,
52              exposure-weighted).  (The paper also audits events stock reproduces on its own paths; that audit is not done here, events are counted raw.)
53"""
54import argparse, json, math, os, random, signal, subprocess, sys, pathlib
55
56SCORER_DROP_VALUE = {"--draft", "--draft-model", "--draft-fallback", "--mtp-draft-vocab", "--spec", "--draft-conf", "--draft-cap", "--mtp", "--spec-min-p",
57                     "--prompt-cache", "--max-context", "--prefill", "--short-read", "--prompt-cache-every", "--conversation-cache-mib", "--suffix-draft"}
58SCORER_DROP_FLAG = {"--serve", "--vision"}
59
60
61def mem_available_gb():
62    try:
63        for line in open("/proc/meminfo"):
64            if line.startswith("MemAvailable:"):
65                return int(line.split()[1]) / 1048576
66    except OSError:
67        pass
68    return float("inf")
69
70
71# ------------------------------------------------------------------------------------------------ engine
72class Engine:
73    def __init__(self, cfg, args, env_extra, log):
74        env = dict(os.environ)
75        for k in list(env):
76            if k.startswith("STRATA_"):
77                env.pop(k)
78        env.update(cfg.get("env", {}))
79        env.update(env_extra)
80        if cfg.get("lib_dirs"):
81            env["LD_LIBRARY_PATH"] = ":".join(cfg["lib_dirs"] + [env.get("LD_LIBRARY_PATH", "")])
82        self.errf = open(log, "wb")
83        self.p = subprocess.Popen([cfg["exe"], "--serve"] + args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self.errf, text=True,
84                                  cwd=cfg.get("cwd"), env=env, bufsize=1, start_new_session=True)
85
86    def ready(self):
87        for line in self.p.stdout:
88            if line.startswith("READY"):
89                return True
90        return False
91
92    def gen(self, ids, n):
93        self.p.stdin.write("GEN %d %s\n" % (n, ",".join(map(str, ids))))
94        self.p.stdin.flush()
95        toks = []
96        for line in self.p.stdout:
97            if line.startswith("T "):
98                toks.append(int(line.split()[1]))
99            elif line.startswith("DONE"):
100                return toks, line.split()
101            elif line.startswith("ERR"):
102                raise SystemExit("engine: " + line.strip())
103        raise SystemExit("the engine closed its output")
104
105    def close(self):
106        try:
107            self.p.stdin.write("QUIT\n")
108            self.p.stdin.flush()
109            self.p.wait(timeout=300)
110        except Exception:
111            try:
112                os.killpg(self.p.pid, signal.SIGKILL)   # only our own session
113            except Exception:
114                self.p.kill()
115        self.errf.close()
116
117
118def fresh_profile(cfg, args, tag):
119    """cfg "profile_src": a fresh copy of the expert profile per engine start (the engine may rewrite it) -> args with the copy's path"""
120    src = cfg.get("profile_src")
121    if not src or "--expert-profile" not in args:
122        return args
123    import shutil
124    dst = os.path.abspath(tag) + ".profile.bin"
125    shutil.copyfile(src, dst)
126    args = list(args)
127    args[args.index("--expert-profile") + 1] = dst
128    return args
129
130
131def scorer_args(cfg, total_tokens, extra):
132    base, out, i = list(cfg["args"]), [], 0
133    while i < len(base):
134        x = base[i]
135        if x in SCORER_DROP_FLAG:
136            i += 1
137        elif x in SCORER_DROP_VALUE:
138            i += 2
139        else:
140            out.append(x)
141            i += 1
142    return out + ["--prompt-cache", "0", "--max-context", str(total_tokens + 512), "--short-read", str(total_tokens + 64), "--prefill", "512"] + extra
143
144
145def kv_env(lst):
146    d = {}
147    for kv in lst or []:
148        k, _, v = kv.partition("=")
149        d[k] = v
150    return d
151
152
153# ------------------------------------------------------------------------------------------------ gen / score
154def cmd_gen(a):
155    cfg = json.load(open(a.config, encoding="utf-8-sig"))
156    rows = [json.loads(l) for l in open(a.corpus) if l.strip()]
157    rows = [r for r in rows if r.get("split", "held") == "held"]
158    kinds = a.kinds.split(",") if a.kinds else sorted({r["kind"] for r in rows})
159    sel = []
160    for k in kinds:
161        sel += [r for r in rows if r["kind"] == k][a.offset:a.offset + a.per_kind]
162    if mem_available_gb() < a.min_free_gb:
163        raise SystemExit("only %.0f GB available (< %d): not starting an engine" % (mem_available_gb(), a.min_free_gb))
164    eng = Engine(cfg, fresh_profile(cfg, list(cfg["args"]), a.out), kv_env(a.env), a.out + ".engine.log")
165    items = []
166    try:
167        if not eng.ready():
168            raise SystemExit("the engine ended before READY, see %s.engine.log" % a.out)
169        for r in sel:
170            toks, f = eng.gen(r["ids"], a.new)
171            items.append({"id": r["id"], "kind": r["kind"], "prompt": r["ids"], "cont": toks})
172            print("%s: %d prompt, %d forced tokens" % (r["id"], len(r["ids"]), len(toks)), flush=True)
173    finally:
174        eng.close()
175    json.dump({"config": a.config, "env": a.env or [], "items": items}, open(a.out, "w"))
176    return 0
177
178
179def cmd_score(a):
180    cfg = json.load(open(a.config, encoding="utf-8-sig"))
181    st = json.load(open(a.set))
182    items = st["items"]
183    total = max(len(i["prompt"]) + len(i["cont"]) for i in items)
184    out = pathlib.Path(a.out).resolve()
185    if out.exists():
186        out.unlink()
187    env = kv_env(a.env)
188    extra = [x for s in (a.arg or []) for x in s.split()]
189    if a.path == "decode":
190        # the real decode/verify windows (drafter, spec windows, adaptive tiers, whatever the config has) with the forced continuation standing in
191        # for the argmax (STRATA_FOLLOW, one line per request in decode order); rows come from STRATA_FOLLOW_LOGPOS
192        follow = str(out) + ".follow.txt"
193        with open(follow, "w") as ff:
194            for it in items:
195                ff.write(",".join(map(str, it["cont"])) + chr(10))
196        env.update({"STRATA_FOLLOW": follow, "STRATA_FOLLOW_LOGPOS": str(out), "STRATA_LOGPOS_TOPK": "2"})
197        args = list(cfg["args"])
198        if "--prompt-cache" in args:
199            i = args.index("--prompt-cache")
200            del args[i:i + 2]
201        args += ["--prompt-cache", "0"] + extra
202    else:
203        env.update({"STRATA_LOGPOS": str(out), "STRATA_LOGPOS_TOPK": "2", "STRATA_ROUTE_TAIL_SKIP": env.get("STRATA_ROUTE_TAIL_SKIP", "0")})
204        args = scorer_args(cfg, total, extra)
205    if mem_available_gb() < a.min_free_gb:
206        raise SystemExit("only %.0f GB available (< %d): not starting an engine" % (mem_available_gb(), a.min_free_gb))
207    args = fresh_profile(cfg, args, str(out))
208    eng = Engine(cfg, args, env, str(out) + ".engine.log")
209
210    def nlines():
211        return sum(1 for _ in open(out)) if out.exists() else 0
212    meta = []
213    try:
214        if not eng.ready():
215            raise SystemExit("the engine ended before READY, see %s.engine.log" % out)
216        for it in items:
217            ids = it["prompt"] + it["cont"]
218            n0 = nlines()
219            if a.path == "decode":
220                toks, f = eng.gen(it["prompt"], len(it["cont"]))
221                if toks != it["cont"]:
222                    print("%s: WARNING the engine emitted %d tokens, %d differ from the forced continuation" % (
223                        it["id"], len(toks), sum(1 for x, y in zip(toks, it["cont"]) if x != y) + abs(len(toks) - len(it["cont"]))), flush=True)
224            else:
225                toks, f = eng.gen(ids, 1)
226            n1 = nlines()
227            if n1 - n0 < len(it["cont"]) // 2:
228                raise SystemExit("%s: only %d positions scored (the prompt took the batched path? raise --short-read; decode path: STRATA_FOLLOW not in this build?)" % (it["id"], n1 - n0))
229            meta.append({"id": it["id"], "kind": it["kind"], "first_line": n0, "end_line": n1, "prompt_len": len(it["prompt"]), "ids": ids})
230            print("%s: %d positions" % (it["id"], n1 - n0), flush=True)
231    finally:
232        eng.close()
233    json.dump({"set": a.set, "config": a.config, "path": a.path, "env": a.env or [], "args": args, "items": meta}, open(str(out) + ".meta.json", "w"))
234    return 0
235
236
237# ------------------------------------------------------------------------------------------------ check
238def load_arm(tsv):
239    """-> {request id: [(is_mismatch, margin, top2_margin), ...]} over the continuation positions"""
240    meta = json.load(open(tsv + ".meta.json"))
241    lines = open(tsv).read().splitlines()
242    out = {}
243    for it in meta["items"]:
244        ids, P = it["ids"], it["prompt_len"]
245        rows = []
246        for ln in lines[it["first_line"]:it["end_line"]]:
247            f = ln.split("\t")
248            pos, tgt = int(f[0]), int(f[1])
249            if pos < P - 1 or pos + 1 >= len(ids):
250                continue
251            if ids[pos + 1] != tgt:
252                raise SystemExit("%s: line for position %d scores token %d, the set has %d" % (it["id"], pos, tgt, ids[pos + 1]))
253            lp_t, am, lp_am = float(f[2]), int(f[3]), float(f[4])
254            lp2 = None
255            for x in f[8:10]:
256                i, _, v = x.partition(":")
257                if int(i) != am:
258                    lp2 = float(v)
259                    break
260            rows.append((am != tgt, max(0.0, lp_am - lp_t), (lp_am - lp2) if lp2 is not None else float("nan")))
261        out[it["id"]] = rows
262    return out
263
264
265def ceil8(x):
266    return max(0.125, math.ceil(x * 8.0 - 1e-12) / 8.0)
267
268
269def binom_tail_ge(k, n, p):
270    return sum(math.comb(n, i) * p ** i * (1 - p) ** (n - i) for i in range(k, n + 1))
271
272
273def check(stock, cand, delta=None, seed=1, boots=4000):
274    """stock: list of arms, cand: one arm (each {request: rows}); the requests are the same. -> dict"""
275    ids = [i for i in cand if all(i in s for s in stock)]
276    # delta: largest margin at stock's first departure per request (every stock arm), rounded up to 1/8
277    if delta is None:
278        firsts = []
279        for s in stock:
280            for i in ids:
281                for mm, mg, _ in s[i]:
282                    if mm:
283                        firsts.append(mg)
284                        break
285        delta = ceil8(max(firsts)) if firsts else 0.125
286
287    def counts(arm):
288        return [(len(arm[i]), sum(1 for r in arm[i] if r[0]), sum(1 for r in arm[i] if r[0] and r[1] > 2 * delta)) for i in ids]
289    sc = [counts(s) for s in stock]
290    cc = counts(cand)
291    n_s = [sum(c[0] for c in a) for a in sc]
292    n_c = sum(c[0] for c in cc)
293
294    def rate(cs):
295        return 100.0 * sum(c[1] for c in cs) / max(1, sum(c[0] for c in cs))
296    r_stock = [rate(a) for a in sc]
297    r_cand = rate(cc)
298    r_s = sum(r_stock) / len(r_stock)
299    rng = random.Random(seed)
300    diffs = []
301    for _ in range(boots):
302        pick = [rng.randrange(len(ids)) for _ in ids]
303        dn = sum(cc[j][0] for j in pick)
304        dc = 100.0 * sum(cc[j][1] for j in pick) / max(1, dn)
305        ds = sum(100.0 * sum(a[j][1] for j in pick) / max(1, sum(a[j][0] for j in pick)) for a in sc) / len(sc)
306        diffs.append(dc - ds)
307    diffs.sort()
308    lo, hi = diffs[int(0.05 * boots)], diffs[int(0.95 * boots) - 1]
309    if lo > 0.5:
310        rate_v = "REJECT"
311    elif hi <= 0.5:
312        rate_v = "PASS"
313    else:
314        rate_v = "INCONCLUSIVE"
315    ev_c = sum(c[2] for c in cc)
316    ev_s = sum(sum(c[2] for c in a) for a in sc)
317    N_s = sum(n_s)
318    p0 = n_c / (n_c + N_s)
319    n = ev_c + ev_s
320    p = binom_tail_ge(ev_c, n, p0) if n > 0 else 1.0
321    event_v = "REJECT" if p < 0.05 else "PASS"
322    # stock-vs-stock spread (the noise): per-arm rates and large-margin events
323    return {"requests": len(ids), "tokens_cand": n_c, "tokens_stock_arms": n_s, "delta": delta, "mismatch_rate_stock_arms_pct": [round(x, 3) for x in r_stock],
324            "mismatch_rate_cand_pct": round(r_cand, 3), "diff_pts": round(r_cand - r_s, 3), "diff_ci90_pts": [round(lo, 3), round(hi, 3)],
325            "rate_rule": rate_v, "events_cand": ev_c, "events_stock_arms": [sum(c[2] for c in a) for a in sc], "events_p": round(p, 5),
326            "event_rule": event_v, "verdict": "REJECT" if "REJECT" in (rate_v, event_v) else ("PASS" if rate_v == "PASS" else "INCONCLUSIVE")}
327
328
329def cmd_check(a):
330    stock = [load_arm(t) for t in a.stock]
331    cand = load_arm(a.cand)
332    if len(stock) < 2:
333        print("warning: one stock arm only: the noise between stock runs is not measured", file=sys.stderr)
334    r = check(stock, cand, a.delta)
335    print(json.dumps(r, indent=1))
336    if a.json:
337        json.dump(r, open(a.json, "w"), indent=1)
338    return {"PASS": 0, "REJECT": 1, "INCONCLUSIVE": 2}[r["verdict"]]
339
340
341def cmd_selftest(a):
342    rng = random.Random(7)
343
344    def arm(p_mis, p_big, nreq=60, n=300):
345        d = {}
346        for q in range(nreq):
347            rows = []
348            for _ in range(n):
349                if rng.random() < p_mis:
350                    big = rng.random() < p_big
351                    rows.append((True, rng.uniform(1.0, 3.0) if big else rng.uniform(0.0, 0.4), 1.0))
352                else:
353                    rows.append((False, 0.0, 2.0))
354            d["r%d" % q] = rows
355        return d
356    s1, s2, s3 = arm(0.007, 0.0), arm(0.007, 0.0), arm(0.007, 0.0)
357    ok = check([s1, s2], s3)
358    bad = check([s1, s2], arm(0.02, 0.0))
359    ev = check([s1, s2], arm(0.0075, 0.5))
360    print("stock vs stock:", ok["verdict"], ok["diff_pts"], ok["diff_ci90_pts"], "events p", ok["events_p"])
361    print("rate +1.3 pts:", bad["verdict"], bad["diff_pts"], bad["diff_ci90_pts"])
362    print("more large-margin events:", ev["verdict"], ev["events_cand"], ev["events_stock_arms"], ev["events_p"])
363    assert ok["verdict"] != "REJECT" and bad["verdict"] == "REJECT" and ev["event_rule"] == "REJECT", "selftest failed"
364    print("selftest ok")
365    return 0
366
367
368# ------------------------------------------------------------------------------------------------ the neutral writer (the gate, owner 11-10)
369def cmd_cut(a):
370    """prompt cuts of one long id file (comma-separated token ids): N windows of each size at fixed offsets (the cuts kl_ab.py and the
371    11-10 gate runs used: offset = (i * 7919 + size) mod (len - size - 1)) -> a corpus for gen / gen-neutral"""
372    big = [int(x) for x in open(a.ids).read().strip().split(",") if x.strip()]
373    n = 0
374    with open(a.out, "w") as f:
375        for size in [int(s) for s in a.sizes.split(",") if s]:
376            if size >= len(big):
377                raise SystemExit("cut: the id file has %d ids, a cut of %d does not fit" % (len(big), size))
378            for i in range(a.n):
379                off = (i * 7919 + size) % max(1, len(big) - size - 1)
380                f.write(json.dumps({"id": "p%d-%d" % (size, i), "kind": "p%d" % size, "split": "held", "ids": big[off: off + size]}) + "\n")
381                n += 1
382    print("cut: %d prompts -> %s" % (n, a.out))
383    return 0
384
385
386def http_json(url, obj=None, timeout=60.0):
387    import urllib.request
388    data = None if obj is None else json.dumps(obj).encode()
389    req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"} if data else {})
390    return json.loads(urllib.request.urlopen(req, timeout=timeout).read())
391
392
393def cmd_gen_neutral(a):
394    """greedy continuations written by a NEUTRAL program (neither arm): llama.cpp's llama-server on the same GGUF.  The prompt goes in as token
395    ids (the ids `score` feeds the engine), temperature 0 / top_k 1, no prompt cache, the generated ids back with return_tokens."""
396    import shlex, time
397    rows = [json.loads(l) for l in open(a.corpus) if l.strip()]
398    rows = [r for r in rows if r.get("split", "held") == "held"]
399    kinds = a.kinds.split(",") if a.kinds else sorted({r["kind"] for r in rows})
400    sel = []
401    for k in kinds:
402        sel += [r for r in rows if r["kind"] == k][a.offset:a.offset + a.per_kind]
403    def split(s):   # (Windows: shlex's non-POSIX mode keeps the quotes around a token)
404        return [x[1:-1] if len(x) > 1 and x[0] == x[-1] == '"' else x for x in shlex.split(s, posix=os.name != "nt")]
405    cmd = split(a.writer) + ["-m", a.writer_model, "--port", str(a.writer_port), "--host", "127.0.0.1",
406                             "-c", str(a.writer_ctx), "-np", "1"] + split(a.writer_args or "")
407    env = dict(os.environ)
408    env.update(kv_env(a.writer_env))
409    if a.writer_lib:
410        k = "PATH" if os.name == "nt" else "LD_LIBRARY_PATH"
411        env[k] = os.pathsep.join(a.writer_lib + [env.get(k, "")])
412    log = open(a.out + ".writer.log", "w")
413    log.write("# " + " ".join(cmd) + "\n")
414    log.flush()
415    kw = {"creationflags": 0x00000200} if os.name == "nt" else {"start_new_session": True}
416    p = subprocess.Popen(cmd, stdout=log, stderr=subprocess.STDOUT, env=env, **kw)
417    url = "http://127.0.0.1:%d" % a.writer_port
418    items = []
419    try:
420        t0 = time.time()
421        while True:
422            if p.poll() is not None:
423                raise SystemExit("gen-neutral: the writer ended before it was ready, see %s.writer.log" % a.out)
424            try:
425                if http_json(url + "/health", timeout=5).get("status") == "ok":
426                    break
427            except Exception:
428                pass
429            if time.time() - t0 > a.writer_wait:
430                raise SystemExit("gen-neutral: the writer was not ready after %d s" % a.writer_wait)
431            time.sleep(1.0)
432        for r in sel:
433            res = http_json(url + "/completion", {"prompt": r["ids"], "n_predict": a.new, "temperature": 0.0, "top_k": 1, "cache_prompt": False,
434                                                  "return_tokens": True, "stream": False}, timeout=3600)
435            toks = [int(x) for x in res.get("tokens", [])]
436            if not toks:
437                raise SystemExit("gen-neutral: %s: the writer returned no token ids (a llama-server without return_tokens?)" % r["id"])
438            items.append({"id": r["id"], "kind": r["kind"], "prompt": r["ids"], "cont": toks})
439            print("%s: %d prompt, %d forced tokens (writer)" % (r["id"], len(r["ids"]), len(toks)), flush=True)
440    finally:
441        try:
442            if os.name == "nt":
443                p.terminate()
444            else:
445                os.killpg(p.pid, signal.SIGTERM)
446            p.wait(timeout=60)
447        except Exception:
448            try:
449                p.kill()
450            except Exception:
451                pass
452        log.close()
453    json.dump({"config": "writer: " + " ".join(cmd), "writer": "neutral", "env": [], "items": items}, open(a.out, "w"))
454    return 0
455
456
457def gate_report(stock, cand, delta=None):
458    """stock, cand: two (or more) scored arms each, on a NEUTRAL writer's text.  The gate: every candidate arm against the stock arms (check());
459    REJECT if any is REJECT, PASS if all PASS, else INCONCLUSIVE.  The reversed direction (every stock arm against the candidate arms) is
460    reported beside it, not required."""
461    fwd = [check(stock, c, delta) for c in cand]
462    rev = [check(cand, s, delta) for s in stock]
463    vs = [r["verdict"] for r in fwd]
464    verdict = "REJECT" if "REJECT" in vs else ("PASS" if all(v == "PASS" for v in vs) else "INCONCLUSIVE")
465    return {"verdict": verdict, "cand_vs_stock": fwd, "stock_vs_cand_reported": rev}
466
467
468def cmd_gate(a):
469    st = json.load(open(a.set))
470    if st.get("writer") != "neutral" and not a.allow_engine_writer:
471        raise SystemExit("gate: %s was not written by gen-neutral; the gate needs a neutral writer's text (an engine-written set measures the "
472                         "distance from that engine: use score + check as a diagnostic, or --allow-engine-writer)" % a.set)
473    os.makedirs(a.outdir, exist_ok=True)
474    arms = {"stockA": a.env or [], "stockB": a.env or [], "candA": (a.env or []) + a.cand_env, "candB": (a.env or []) + a.cand_env}
475    for name, env in arms.items():
476        out = os.path.join(a.outdir, name + ".tsv")
477        if os.path.exists(out) and os.path.exists(out + ".meta.json"):
478            print("%s: kept (%s exists)" % (name, out), flush=True)
479            continue
480        cmd_score(argparse.Namespace(config=a.config, set=a.set, out=out, path=a.path, env=env, arg=a.arg, min_free_gb=a.min_free_gb))
481    load = lambda n: load_arm(os.path.join(a.outdir, n + ".tsv"))
482    r = gate_report([load("stockA"), load("stockB")], [load("candA"), load("candB")], a.delta)
483    print(json.dumps(r, indent=1))
484    json.dump(r, open(os.path.join(a.outdir, "gate.json"), "w"), indent=1)
485    return {"PASS": 0, "REJECT": 1, "INCONCLUSIVE": 2}[r["verdict"]]
486
487
488def main():
489    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
490    sp = ap.add_subparsers(dest="cmd", required=True)
491    g = sp.add_parser("gen"); g.add_argument("config"); g.add_argument("out"); g.add_argument("--corpus", required=True)
492    g.add_argument("--kinds", default=""); g.add_argument("--per-kind", type=int, default=4); g.add_argument("--offset", type=int, default=8)
493    g.add_argument("--new", type=int, default=300); g.add_argument("--env", action="append"); g.add_argument("--min-free-gb", type=int, default=20)
494    s = sp.add_parser("score"); s.add_argument("config"); s.add_argument("set"); s.add_argument("out")
495    s.add_argument("--path", choices=["decode", "prompt"], default="decode", help="decode: the real verify windows with the forced tokens (STRATA_FOLLOW); prompt: the text read as a prompt (STRATA_LOGPOS)")
496    s.add_argument("--env", action="append"); s.add_argument("--arg", action="append"); s.add_argument("--min-free-gb", type=int, default=20)
497    c = sp.add_parser("check"); c.add_argument("--stock", nargs="+", required=True); c.add_argument("--cand", required=True)
498    c.add_argument("--delta", type=float); c.add_argument("--json")
499    sp.add_parser("selftest")
500    u = sp.add_parser("cut"); u.add_argument("ids"); u.add_argument("out"); u.add_argument("--sizes", default="4096,8192,20000")
501    u.add_argument("--n", type=int, default=16)
502    w = sp.add_parser("gen-neutral"); w.add_argument("out"); w.add_argument("--corpus", required=True)
503    w.add_argument("--writer", required=True, help="the writer's command line, e.g. /path/llama-server (its -m/--port/--host/-c/-np are added)")
504    w.add_argument("--writer-model", required=True, help="the GGUF the engine reads (shard 1 of a split set)")
505    w.add_argument("--writer-args", default="", help="more writer arguments, e.g. \"-ngl 99 --cpu-moe -fa on\"")
506    w.add_argument("--writer-env", action="append"); w.add_argument("--writer-lib", action="append", default=[])
507    w.add_argument("--writer-port", type=int, default=18471); w.add_argument("--writer-ctx", type=int, default=32768)
508    w.add_argument("--writer-wait", type=int, default=900)
509    w.add_argument("--kinds", default=""); w.add_argument("--per-kind", type=int, default=16); w.add_argument("--offset", type=int, default=0)
510    w.add_argument("--new", type=int, default=128)
511    t = sp.add_parser("gate"); t.add_argument("config"); t.add_argument("set"); t.add_argument("outdir")
512    t.add_argument("--cand-env", action="append", required=True, help="the candidate's setting(s), K=V")
513    t.add_argument("--env", action="append", help="settings of both arms"); t.add_argument("--arg", action="append")
514    t.add_argument("--path", choices=["decode", "prompt"], default="decode"); t.add_argument("--delta", type=float)
515    t.add_argument("--min-free-gb", type=int, default=20); t.add_argument("--allow-engine-writer", action="store_true")
516    a = ap.parse_args()
517    return {"gen": cmd_gen, "score": cmd_score, "check": cmd_check, "selftest": cmd_selftest, "cut": cmd_cut, "gen-neutral": cmd_gen_neutral,
518            "gate": cmd_gate}[a.cmd](a)
519
520
521if __name__ == "__main__":
522    sys.exit(main())