Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
Hy4 spec depth gate: deterministic decisions (per-request reset, static threshold mode), decision digest, FIRES gate_det in the paired driver, CPU determinism tests
YanissAmzf198c41d6bb5
diff --git a/tools/hy4/depth_gate.py b/tools/hy4/depth_gate.pyindex 6d0747a..93ef479 100644--- a/tools/hy4/depth_gate.py+++ b/tools/hy4/depth_gate.py@@ -9,10 +9,18 @@ P3(s) = P(acc >= kb + ext | s) with s = product of the base confidences (probabiextra_ms = verify(1 + kb + ext) - verify(1 + kb) + ext * step_ms + gap_ms (gap_ms = the host sync between the base and the tail graph)P3 is learnt online per s-bin from the rounds that extended (prior: s * prior_q, weight prior_n); every PROBE-th round extends whatever the bin says, so a binthat stopped extending can still be re-measured (no selection bias: the probe rounds are not chosen by s).++Determinism (S7b): the decision must depend only on the logits of THIS request. Three modes (HY4_SPEC2_MODE):+ static (default): extend iff s >= theta (HY4_SPEC2_THETA, default 0.6, from the pol_conf replay under the -2 % tau rule). No state at all.+ learn: the online rule above, reset() at every request start (fresh bins, fresh rate, probe counter from 0).+ carry: the online rule with NO reset (the job 17 behaviour: state of the previous requests changes the decisions, so text differs between identical reps). Kept as a negative control.+Lifetime counters (life_rounds / life_ext) survive reset(): the server log differences them per request. `digest` = crc32 of the decision bits of the current request."""import os+import zlibNBIN = 10+THETA = 0.6def _table(s):@@ -24,19 +32,30 @@ def _table(s):class DepthGate:- def __init__(self, verify_ms, step_ms=3.0, gap_ms=0.3, kb=2, ext=1, prior_n=6.0, prior_q=0.5, probe=16, alpha=0.02, tok0=2.3):+ def __init__(self, verify_ms, step_ms=3.0, gap_ms=0.3, kb=2, ext=1, prior_n=6.0, prior_q=0.5, probe=16, alpha=0.02, tok0=2.3, mode="learn", theta=THETA):+ assert mode in ("static", "learn", "carry"), modeself.vt, self.step_ms, self.gap_ms, self.kb, self.ext = dict(verify_ms), step_ms, gap_ms, kb, ext- self.prior_n, self.prior_q, self.probe, self.alpha = prior_n, prior_q, probe, alpha+ self.prior_n, self.prior_q, self.probe, self.alpha, self.tok0 = prior_n, prior_q, probe, alpha, tok0+ self.mode, self.theta = mode, theta+ self.life_rounds = self.life_ext = 0 # lifetime counters (never reset): the server log differences them per request+ self.reset(force=True)++ def reset(self, force=False):+ """start of a request: drop every adaptive state so the decisions depend on this request only (carry mode keeps the old behaviour)"""+ if self.mode == "carry" and not force:+ returnself.hits = [[0.0, 0.0] for _ in range(NBIN)] # per s-bin: [extension accepted, extension rounds]self.n_round = self.n_ext = 0- self.tok_m = tok0 # running mean tokens per round / ms per round (the rate is their ratio)+ self.tok_m = self.tok0 # running mean tokens per round / ms per round (the rate is their ratio)self.ms_m = self.round_ms(False)+ self.dig = 0@classmethoddef from_env(cls, kb, ext):t = _table(os.environ.get("HY4_ROW_MS", "1:61.8,2:76.7,3:90.3,4:104.0,5:117.3,6:130.6,7:143.8,8:157.0")) # b2 arm C 4K graph replay, T3 / T5+ interpolated (spec2 job measures them)return cls(t, float(os.environ.get("HY4_SPEC2_STEP_MS", "3.0")), float(os.environ.get("HY4_SPEC2_GAP_MS", "0.3")), kb, ext,- float(os.environ.get("HY4_SPEC2_PRIOR_N", "6")), float(os.environ.get("HY4_SPEC2_PRIOR_Q", "0.5")), int(os.environ.get("HY4_SPEC2_PROBE", "16")))+ float(os.environ.get("HY4_SPEC2_PRIOR_N", "6")), float(os.environ.get("HY4_SPEC2_PRIOR_Q", "0.5")), int(os.environ.get("HY4_SPEC2_PROBE", "16")),+ mode=os.environ.get("HY4_SPEC2_MODE", "static"), theta=float(os.environ.get("HY4_SPEC2_THETA", str(THETA))))def verify_ms(self, T):if T in self.vt:@@ -69,15 +88,27 @@ class DepthGate:def decide(self, confs):"""confs: confidences of the kb base drafts -> (extend?, bin)"""self.n_round += 1+ self.life_rounds += 1b = self.sbin(confs)- go = self.p_ext(b) * 1.0 > (self.tok_m / self.ms_m) * self.extra_ms()- if self.probe and self.n_round % self.probe == 0:- go = True+ s = 1.0+ for c in confs:+ s *= min(1.0, max(0.0, c))+ if self.mode == "static":+ go = s >= self.theta+ else:+ go = self.p_ext(b) * 1.0 > (self.tok_m / self.ms_m) * self.extra_ms()+ if self.probe and self.n_round % self.probe == 0:+ go = True+ self.life_ext += go+ self.dig = zlib.crc32(b"\x01" if go else b"\x00", self.dig)return go, bdef update(self, b, extended, acc):"""acc = accepted drafts of this round (clamped to the drafts verified by the caller)"""tokens = 1 + acc+ if self.mode == "static":+ self.n_ext += extended+ returnif extended:self.n_ext += 1self.hits[b][1] += 1.0@@ -87,7 +118,7 @@ class DepthGate:self.ms_m += self.alpha * (self.round_ms(extended) - self.ms_m)def stats(self):- return {"rounds": self.n_round, "ext_rounds": self.n_ext, "rate_tok_s": round(1000 * self.tok_m / self.ms_m, 2),+ return {"rounds": self.life_rounds, "ext_rounds": self.life_ext, "req_rounds": self.n_round, "req_ext": self.n_ext, "mode": self.mode, "digest": f"{self.dig:08x}", "rate_tok_s": round(1000 * self.tok_m / self.ms_m, 2),"bins": [[round(a, 1), round(n, 1)] for a, n in self.hits]}diff --git a/tools/hy4/engine.py b/tools/hy4/engine.pyindex a6378fc..f3cec0a 100644--- a/tools/hy4/engine.py+++ b/tools/hy4/engine.py@@ -313,6 +313,7 @@ class Hy4Engine:kd0 = self.gate_kb if self.gate is not None else k # drafts read from the first draft graphif self.gate is not None:from depth_gate import draft_with_gate+ self.gate.reset() # decisions depend on this request only (HY4_SPEC2_MODE=carry keeps the old carried state: negative control)pc = time.perf_countertm = [0.0, 0.0, 0.0]ng = Nonediff --git a/tools/hy4/step/spec2_arms.py b/tools/hy4/step/spec2_arms.pyindex e850a5a..e5b76b0 100644--- a/tools/hy4/step/spec2_arms.py+++ b/tools/hy4/step/spec2_arms.py@@ -1,7 +1,8 @@"""spec2_arms.py: ONE staged runner job for the S7 draft-depth A/B (perf/hy4-strix-spec2). Runner driver: cwd = tree, env = lane env + XENV, GPU locks held by the runner.Question: tau and ms per round on the 6 head_tau prompts (code / prose / chat x 2, 256 tok, greedy, spec) for- A = deployed b2 arm C (k = 3) B = A with --num-draft 2 (plain shallow chain: the free control) C = A + HY4_SPEC2_GATE=1 (k = 2 base graph + confidence-gated tail step)-order SP2_ORDER (default ABCA: the second A is the drift control, reported as A2). Phase 0: graph-replay ms per verify round at T = 1..6 (4K, arm C flags) = the missing T3 / T5 / T6 of the cost model.+ A = deployed b2 arm C (k = 3) B = A with --num-draft 2 (plain shallow chain: the free control) C = A + HY4_SPEC2_GATE=1 (k = 2 base graph + confidence-gated tail step), state carried across requests (job 17, NOT deterministic)+ O = gate with the online rule, reset per request N = gate with a static threshold HY4_SPEC2_THETA (SP2_THETA, default 0.6) on s = c1 * c2 (no state) [S7b, perf/hy4-strix-spec3]+order SP2_ORDER (default AONN: N twice = the reproducibility proof; reported as N and N2). FIRES gate_det <n> per gate arm = prompts whose two reps (or the warm-up) differ in text md5 / gate digest; must be 0 for O, N; N vs N2 must match on every point. Phase 0: graph-replay ms per verify round at T = 1..6 (4K, arm C flags) = the missing T3 / T5 / T6 of the cost model.Metric per class: tok/s, tau, ms per round = 1000 * tau / tok/s, paired delta vs A (mean of both A runs). Gate rule (s7_model.py): C ships when it is >= B on code by 2 % and not below B on chat / prose by more than 1 %;B ships alone when C does not beat it; neither when both lose to A on code by more than 2 %.env: OD_PORT OD_NAME GGUF N1119 B2_H B2_DIR B2_GM B2_CO B2_PASSES SP2_ORDER SP2_REPS (default 2) SP2_LEVERS (default 1)@@ -17,7 +18,12 @@ COMMON = {"EXL3_GM_BUILD_DIR": GM, "HY4_GM_EXT": f"{GM}/exl3_gm_ext.so", "MOE_DEARM_C = {"HY4_HEAD_Q8": "1", "HY4_GRAPH_FORK": "1", "HY4_RG_TUNE": "1", "HY4_BG_V2": "1", "HY4_DENSE_V2": "1", "HY4_MOE_V2": "1","HY4_DRAFT_MOE_TILES": "1", "HY4_DRAFT_MLA_BG": "1", "HY4_DRAFT_IX_GV": "1","HY4_DRAFT_VOCAB": "0", "HY4_DRAFT_VOCAB_REQ": "0", "HY4_DRAFT_TOPK": "0", "HY4_NGRAM_REPLACE": "0", "HY4_SPEC2_GATE": "0", "HY4_REQ_ROUNDLOG": "1"}-ARMS = {"A": ({}, "3"), "B": ({}, "2"), "C": ({"HY4_SPEC2_GATE": "1", "HY4_SPEC2_KB": "2"}, "3")} # arm -> (extra env, --num-draft)+GATE = {"HY4_SPEC2_GATE": "1", "HY4_SPEC2_KB": "2"}+ARMS = {"A": ({}, "3"), "B": ({}, "2"),+ "C": ({**GATE, "HY4_SPEC2_MODE": "carry"}, "3"), # job 17 gate: adaptive state carried across requests (the non-deterministic one)+ "O": ({**GATE, "HY4_SPEC2_MODE": "learn"}, "3"), # old online rule, reset at every request (isolates the reset)+ "N": ({**GATE, "HY4_SPEC2_MODE": "static", "HY4_SPEC2_THETA": E.get("SP2_THETA", "0.6")}, "3")} # static threshold on s = c1 * c2, no state (S7b)+GATE_LETTERS = "CON"; DET_LETTERS = "ON" # DET_LETTERS: arms whose gate_det must be 0 (C is the carried-state negative control)def log(*a): print(time.strftime("%T"), *a, flush=True)def stop(srv):@@ -38,16 +44,41 @@ def row_ms_env(levers):t = {int(k.split("_T")[1]): v["median"] for k, v in levers["round_ms"].items() if k.startswith("4096_T")}return ",".join(f"{T}:{t[T]:.2f}" for T in sorted(t)) if len(t) >= 3 else None+def det_mismatch(pts, reqs):+ """FIRES gate_det: prompts whose two identical reps differ (text md5, or the gate decision digest when the server logged one). reqs[0] = the discarded warm-up (same request as the+ first prompt rep 0: its digest must also match). Returns (mismatches, prompts compared)."""+ by, bad = {}, 0+ for k, p in pts.items(): by.setdefault(k.rsplit("#", 1)[0], []).append(k)+ dig = {k: q.get("digest") for k, q in zip(pts, (reqs or [])[1:])}+ for lab, ks in by.items():+ ks = sorted(ks)+ if len(ks) < 2: continue+ if len({pts[k]["md5"] for k in ks}) > 1 or len({dig.get(k) for k in ks}) > 1: bad += 1+ if reqs and reqs[0].get("digest") and dig:+ first = next(iter(pts))+ if reqs[0]["digest"] != dig.get(first): bad += 1+ return bad, len(by)++def cross_mismatch(a, b):+ """same prompt + rep in two boots of the same arm: md5 and digest must be identical"""+ bad = 0+ da = {k: q.get("digest") for k, q in zip(a["points"], (a.get("reqs") or [])[1:])}+ db = {k: q.get("digest") for k, q in zip(b["points"], (b.get("reqs") or [])[1:])}+ for k, p in a["points"].items():+ q = b["points"].get(k)+ if q is None or p["md5"] != q["md5"] or da.get(k) != db.get(k): bad += 1+ return bad+def gate_lines(path):"""per request (server log line 'req N: ...'): rounds, tau, ext rounds of the gate when present (the gate stats are cumulative over the server's life: differenced per request)"""out, prev = [], (0, 0)for l in open(path, errors="replace"):m = re.search(r"^req (\d+): .*rounds (\d+) tau ([0-9.]+) hist (\[[^\]]*\])", l)if m:- g = re.search(r"gate \{'rounds': (\d+), 'ext_rounds': (\d+)", l)+ g = re.search(r"gate \{'rounds': (\d+), 'ext_rounds': (\d+)", l); dg = re.search(r"'digest': '([0-9a-f]+)'", l)cur = (int(g.group(1)), int(g.group(2))) if g else Noneout.append({"req": int(m.group(1)), "rounds": int(m.group(2)), "tau": float(m.group(3)), "hist": json.loads(m.group(4)),- "gate_rounds": cur and cur[0] - prev[0], "ext_rounds": cur and cur[1] - prev[1]})+ "gate_rounds": cur and cur[0] - prev[0], "ext_rounds": cur and cur[1] - prev[1], "digest": dg.group(1) if dg else None})prev = cur or prevreturn out@@ -65,7 +96,7 @@ def fires_check(letter, path):why = []if letter == "A" and (d2 or gs or gr): why.append("arm A shows firings")if letter == "B" and d2 == 0: why.append("FIRES depth2 = 0")- if letter == "C" and (d2 == 0 or gs == 0 or gr == 0): why.append(f"gate lever not firing (depth2 {d2}, skipped {gs}, run {gr})")+ if letter in GATE_LETTERS and (d2 == 0 or gs == 0 or gr == 0): why.append(f"gate lever not firing (depth2 {d2}, skipped {gs}, run {gr})")if not f and letter != "A": why.append("no fires counter in the server log")why += [f"fallback: {x}" for x in fb]return not why, why@@ -82,7 +113,7 @@ def class_means(pts):return rdef main():- res = {"levers": None, "arms": {}, "order": E.get("SP2_ORDER", "ABCA")}+ res = {"levers": None, "arms": {}, "order": E.get("SP2_ORDER", "AONN")}def save(): json.dump(res, open(f"{OUT}/{name}.spec2.json", "w"), indent=1)if E.get("SP2_LEVERS", "1") == "1":lg = f"{OUT}/{name}.levers.log"@@ -134,6 +165,11 @@ def main():res["arms"][key]["reqs"] = gate_lines(sl)res["arms"][key]["precapture"] = precapture_line(sl)ok, why = fires_check(letter, sl)+ nbad, nprm = det_mismatch(res["arms"][key]["points"], res["arms"][key]["reqs"])+ log(f"FIRES gate_det {nbad} (arm {key}: {nbad} mismatches over {nprm} prompts x 2 reps + warm-up)")+ res["arms"][key]["gate_det"] = nbad+ if nbad and letter in DET_LETTERS: ok, why = False, why + [f"gate_det {nbad} > 0: gate decisions / text not reproducible"]+ if nbad and letter == "A": ok, why = False, why + [f"arm A not reproducible ({nbad})"]res["arms"][key]["fires_ok"], res["arms"][key]["fires_why"] = ok, whyif not ok: log(f"FIRES FAIL arm {key}: {why}")for q, c in zip(res["arms"][key]["reqs"][1:], [p["cls"] for p in res["arms"][key]["points"].values()]): # request 1 = the discarded warm-up@@ -141,6 +177,14 @@ def main():save()# ---- tablearms = res["arms"]+ for l in dict.fromkeys(res["order"]): # repeat boots of the same arm (N, N2): identical md5 + digest per prompt and rep+ ks = [k for k, a in arms.items() if a["letter"] == l]+ for k2 in ks[1:]:+ nb = cross_mismatch(arms[ks[0]], arms[k2])+ log(f"FIRES gate_det {nb} (arm {ks[0]} vs repeat boot {k2}: {nb} of {len(arms[ks[0]]['points'])} points differ)")+ arms[k2]["gate_det_cross"] = nb+ if nb and l != "C":+ arms[k2]["fires_ok"] = False; arms[k2]["fires_why"] = arms[k2].get("fires_why", []) + [f"cross-boot gate_det {nb} > 0"]ref = [a for k, a in arms.items() if a["letter"] == "A"]print("\nSPEC2 TABLE: per class, mean of the head_tau prompts x reps: tok/s | tau | ms per round; delta tok/s vs A (mean of the A runs)")for cls in ("code", "prose", "chat"):@@ -159,21 +203,22 @@ def main():def mean_cls(letter, cls):v = [a["classes"][cls]["tps"] for a in arms.values() if a["letter"] == letter and cls in a["classes"]]return statistics.mean(v) if v else None+ LETTERS = list(dict.fromkeys(res["order"]))for cls in ("code", "prose", "chat"):- t = {l: mean_cls(l, cls) for l in "ABC"}+ t = {l: mean_cls(l, cls) for l in LETTERS}if all(t.values()):- print(f"SPEC2_VERDICT {cls}: A {t['A']:.2f} B(k=2) {t['B']:.2f} C(gate) {t['C']:.2f} tok/s B vs A {100 * (t['B'] / t['A'] - 1):+.1f} % C vs A {100 * (t['C'] / t['A'] - 1):+.1f} % C vs B {100 * (t['C'] / t['B'] - 1):+.1f} %")+ print(f"SPEC2_VERDICT {cls}: " + " ".join(f"{l} {t[l]:.2f}" + ("" if l == "A" else f" ({100 * (t[l] / t['A'] - 1):+.1f} % vs A)") for l in LETTERS) + " tok/s")print("\nSPEC2 TAU per class (6 head_tau prompts x reps), gate: tau must not drop > 2 % vs A")for cls in ("code", "prose", "chat"):ta = [a["classes"][cls]["tau"] for a in arms.values() if a["letter"] == "A" and cls in a["classes"]]row = f"{cls:<6}" + (f" A {statistics.mean(ta):.3f}" if ta else "")- for l in "BC":+ for l in LETTERS[1:]:tl = [a["classes"][cls]["tau"] for a in arms.values() if a["letter"] == l and cls in a["classes"]]if tl and ta:m = statistics.mean(tl); row += f" | {l} {m:.3f} {100 * (m / statistics.mean(ta) - 1):+.1f} % {'OK' if m >= 0.98 * statistics.mean(ta) else 'FAIL (> 2 % drop)'}"print(row)bad = [k for k, a in arms.items() if not a.get("fires_ok", False)]- missing = [l for l in "ABC" if not any(a["letter"] == l for a in arms.values())]+ missing = [l for l in dict.fromkeys(res["order"]) if not any(a["letter"] == l for a in arms.values())]log("SPEC2_DONE", name, f"{time.time() - t0:.0f}s", "FIRES_FAIL " + ",".join(bad) if bad else "fires ok", "MISSING_ARMS " + ",".join(missing) if missing else "")if bad or missing: sys.exit(1)diff --git a/tools/hy4/test_depth_gate.py b/tools/hy4/test_depth_gate.pyindex 57d3712..da1f2a3 100644--- a/tools/hy4/test_depth_gate.py+++ b/tools/hy4/test_depth_gate.py@@ -86,11 +86,15 @@ def generate(policy, p_ok, n_new=400, seed=1, kfix=3, gate=None):out, rounds, ms = [y], 0, 0.0kb = gate.kb if gate else kfixmg = FakeMG(gr, kb, gate.ext if gate else 0, p_ok, rng)+ mg.decisions = []+ if gate:+ gate.reset() # engine.generate: the gate state is per requestwhile len(out) < n_new:j = gr.n - 1dd = mg.run(y, j).tolist()if gate:d, gext, gb = draft_with_gate(gate, mg, dd, kb, j)+ mg.decisions.append(bool(gext))else:d, gext, gb = dd[:kb], False, Nonetoks = [y] + d@@ -129,6 +133,50 @@ def truth(n_new):return out+def determinism():+ """S7b: the same request twice on ONE gate object (a server serving two identical reps). static and learn (reset per request) must repeat decisions, digest and text exactly;+ carry (the job 17 behaviour, no reset) is the NEGATIVE CONTROL: it must diverge on at least one of the scenarios, else this test proves nothing. Returns the number of mismatching repeats."""+ bad = 0+ for mode in ("static", "learn"):+ for p_ok in (0.55, 0.75, 0.93):+ for seed in (1, 2):+ g = DepthGate(ROW, 3.0, 0.3, 2, 1, mode=mode, theta=0.6)+ r1 = generate("gate", p_ok, n_new=300, seed=seed, gate=g)+ st1 = g.stats()+ # a different request in between (state of an unrelated prompt must not leak)+ generate("gate", 0.9 - p_ok / 3, n_new=200, seed=seed + 50, gate=g)+ r2 = generate("gate", p_ok, n_new=300, seed=seed, gate=g)+ st2 = g.stats()+ same = r1[0] == r2[0] and r1[4].decisions == r2[4].decisions and st1["digest"] == st2["digest"] and st1["req_rounds"] == st2["req_rounds"]+ bad += not same+ g2 = DepthGate(ROW, 3.0, 0.3, 2, 1, mode=mode, theta=0.6)+ r3 = generate("gate", p_ok, n_new=300, seed=seed, gate=g2)+ bad += not (r3[4].decisions == r1[4].decisions) # fresh object = same decisions (no hidden global state)+ # the decision of the static gate is a pure function of the confidences+ g = DepthGate(ROW, 3.0, 0.3, 2, 1, mode="static", theta=0.6)+ for c in ([0.9, 0.9], [0.5, 0.5], [0.8, 0.75], [0.99, 0.2]):+ outs = {g.decide(c)[0] for _ in range(5)}+ bad += len(outs) != 1+ assert outs == {c[0] * c[1] >= 0.6}, (c, outs)+ # lifetime counters survive reset, per-request ones do not+ g = DepthGate(ROW, 3.0, 0.3, 2, 1, mode="learn")+ generate("gate", 0.8, n_new=200, gate=g)+ life = g.stats()["rounds"]+ g.reset()+ assert g.stats()["rounds"] == life and g.stats()["req_rounds"] == 0+ # negative control+ diverged = 0+ for p_ok in (0.55, 0.75, 0.93):+ g = DepthGate(ROW, 3.0, 0.3, 2, 1, mode="carry")+ r1 = generate("gate", p_ok, n_new=300, seed=1, gate=g)+ r2 = generate("gate", p_ok, n_new=300, seed=1, gate=g)+ diverged += r1[4].decisions != r2[4].decisions+ assert r1[0] == r2[0] # text is exact in the fake (exact verify); on the real engine row count T changes the logits+ print(f"CONTROL carry_diverges {diverged}/3 scenarios")+ assert diverged >= 1, "negative control: the carried gate must diverge on identical requests"+ return bad++def main():ref = truth(400)for p_ok in (0.55, 0.9):@@ -162,7 +210,10 @@ def main():print(f"{name}: ext rate {mg.tail_calls / r:.2f} gate {1000 * len(o) / ms:.2f} tok/s fixed k2 {1000 * rates[2]:.2f} k3 {1000 * rates[3]:.2f}")assert len(o) / ms >= 0.97 * min(rates.values())assert res["chat-like"][0] < res["code-like"][0] - 0.2, res+ det_mismatch = determinism()print("test_depth_gate OK")+ print(f"FIRES gate_det {det_mismatch}")+ assert det_mismatch == 0if __name__ == "__main__":diff --git a/tools/hy4/test_spec2_driver.py b/tools/hy4/test_spec2_driver.pynew file mode 100644index 0000000..29ec6e5--- /dev/null+++ b/tools/hy4/test_spec2_driver.py@@ -0,0 +1,56 @@+"""Offline exec-check of step/spec2_arms.py main() (no GPU, no server): python3 tools/hy4/test_spec2_driver.py <head_tau.passes>+Stubs the server (Popen, health, chat) with a fake engine that writes the real server-log line format using tools/hy4/depth_gate.DepthGate (modes static / learn / carry),+so the whole job path runs: boot loop, per-request log parsing, FIRES gate_det (per arm + N vs N2), tables, verdict, exit code. Expected: arms N, N2, O gate_det 0 and rc 0;+arm C (carry) gate_det > 0 (negative control) -> run with SP2_ORDER=ACN to see the C failure path."""+import hashlib, io, json, os, random, runpy, sys, tempfile, types+HERE = os.path.dirname(os.path.abspath(__file__)); sys.path.insert(0, HERE)+from depth_gate import DepthGate+passes = sys.argv[1]; order = os.environ.get("SP2_ORDER", "AONN")+tmp = tempfile.mkdtemp(prefix="sp2chk_")+os.environ.update(OD_NAME="chk", OD_PORT="8999", N1119=tmp, B2_H=tmp, B2_DIR=tmp, B2_PASSES=passes, SP2_LEVERS="0", SP2_ORDER=order, OD_TMAX="3300", GGUF="x.gguf")+import subprocess, urllib.request, time+state = {}+class FakeProc:+ pid = 0+ def __init__(self, cmd, env=None, stdout=None, **kw):+ self.env, self.log = env, stdout+ mode = env.get("HY4_SPEC2_MODE") if env.get("HY4_SPEC2_GATE") == "1" else None+ self.g = DepthGate({1: 61.8, 2: 76.7, 3: 90.9, 4: 104.0, 5: 113.3, 6: 128.5}, 3.0, 0.3, 2, 1, mode=mode, theta=float(env.get("HY4_SPEC2_THETA", "0.6"))) if mode else None+ self.n, self.fires = 0, {"rounds": 0, "depth2": 0, "gate_skip": 0, "gate_run": 0}+ state["srv"] = self+ def poll(self): return None+ def request(self, body):+ self.n += 1+ label = json.dumps(body["messages"])[:40]+ seed = int(hashlib.md5(label.encode()).hexdigest()[:6], 16)+ rng = random.Random(seed)+ rounds, tau, h, ext = 110, 2.3, [30, 30, 30, 20, 0, 0, 0, 0, 0], 0+ if self.g:+ self.g.reset()+ for _ in range(rounds):+ c = [rng.random() ** 0.5, rng.random() ** 0.5]; go, b = self.g.decide(c); self.g.update(b, go, min(rng.randrange(4), 3 if go else 2))+ self.fires["rounds"] += 1; self.fires["depth2"] += 1; self.fires["gate_run" if go else "gate_skip"] += 1+ st = self.g.stats(); gate = f" | gate {st} | fires {self.fires}"+ md5 = hashlib.md5((label + st["digest"]).encode()).hexdigest() # fake text depends on the gate decisions (as the real text does through the row count T)+ else:+ gate = ""; md5 = hashlib.md5(label.encode()).hexdigest()+ self.log.write(f"req {self.n}: prompt 3310 tok prefill 4.1 s (800 tok/s) | decode 255 tok 11.0 s = 23.0 tok/s spec=True rounds {rounds} tau {tau} hist {h} | length{gate}\n"); self.log.flush()+ return md5+subprocess.Popen = FakeProc+class R:+ def __init__(s, b): s.b = b+ def read(s): return s.b+urllib.request.urlopen = lambda *a, **k: R(b"{}")+time.sleep = lambda *_: None+sys.argv = ["spec2_arms.py"]+src = open(os.path.join(HERE, "step", "spec2_arms.py")).read().replace('if __name__ == "__main__":\n main()', "")+g = {"__name__": "spec2_arms"}; exec(compile(src, "spec2_arms.py", "exec"), g)+def chat(body):+ md5 = state["srv"].request(body)+ return {"tps": 23.0, "tau": 2.3, "n": 255, "prompt_n": 3310, "md5": md5[:12]}+g["chat"] = chat; g["stop"] = lambda s: None+try:+ g["main"]()+ print("RC 0")+except SystemExit as e:+ print("RC", e.code)