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 (HY4_SPEC2_GATE, default off): k = 2 base draft graph + confidence-gated tail step, CPU fake-engine test, paired A/B driver
YanissAmz88a648fafb27
diff --git a/exllamav3/loader/mtp_gate.py b/exllamav3/loader/mtp_gate.pynew file mode 100644index 0000000..c61f166--- /dev/null+++ b/exllamav3/loader/mtp_gate.py@@ -0,0 +1,81 @@+"""HY4_SPEC2_GATE: the draft chain split in two graphs. Base = the first kb steps (the usual MTPGraph, k = kb) and it also leaves its last token / state in static buffers;+tail = `ext` more steps that continue from those buffers. The host reads the base output (tokens + confidences, it needs them for the verify anyway) and launches the tail only+when DepthGate says the extra draft step + verify row pay (tools/hy4/depth_gate.py). Head KV rows are written by absolute position (pos + i), so a skipped tail leaves nothing+to undo: the rows past the accepted ones are overwritten by the next round exactly as with a shorter chain."""+import torch++from . import graph_bucket as _gb+from .mtp_head import MTPGraph, CONF, CONF_ONE+++def _conf(lg):+ l32 = lg.float()+ return (torch.exp(l32.max() - torch.logsumexp(l32, 0)) * CONF_ONE).long().reshape(1)+++class MTPGraphGate(MTPGraph):+ def __init__(self, mt, kb, ext=1):+ assert CONF, "MTPGraphGate needs HY4_DRAFT_CONF=1 (the engine sets it before the import)"+ super().__init__(mt, kb)+ self.ext = ext+ self.st_tok = torch.zeros(1, dtype=torch.long, device=mt.dev)+ self.st_h = torch.zeros(1, mt.fw.D, device=mt.dev)+ self.tails = {}++ def body(self, N):+ mt = self.mt+ outs, confs, tok, h, pos = [], [], self.inp[0:1], self.h0, self.inp[1:2]+ for i in range(self.k):+ y, lg = mt.step(tok, h, pos + i if i else pos, N)+ tok = mt.pick(lg)+ outs.append(tok)+ confs.append(_conf(lg))+ h = y+ self.st_tok.copy_(tok)+ self.st_h.copy_(h)+ return torch.cat(outs + confs)++ def tail_body(self, N):+ mt = self.mt+ outs, confs, tok, h, pos = [], [], self.st_tok, self.st_h, self.inp[1:2]+ for i in range(self.ext):+ y, lg = mt.step(tok, h, pos + (self.k + i), N)+ tok = mt.pick(lg)+ outs.append(tok)+ confs.append(_conf(lg))+ h = y+ return torch.cat(outs + confs)++ def _tail_graph(self, N):+ g = self.tails.get(N)+ if g is not None:+ return g+ s = torch.cuda.Stream()+ s.wait_stream(torch.cuda.current_stream())+ with torch.cuda.stream(s):+ for _ in range(2):+ self.tail_body(N)+ torch.cuda.current_stream().wait_stream(s)+ torch.cuda.synchronize()+ cg = torch.cuda.CUDAGraph()+ with torch.cuda.graph(cg, pool=self.pool):+ out = self.tail_body(N)+ g = self.tails[N] = (cg, out)+ return g++ def precapture(self, ns=None):+ built = super().precapture(ns)+ mt = self.mt+ for N in (sorted(set(ns)) if ns is not None else _gb.buckets(mt.cap, self.BUCKET)):+ if N not in self.tails:+ self._tail_graph(N)+ built += 1+ return built++ def run_tail(self, j):+ """continue the base chain of the round whose head position is j (the base graph replayed last): device [ext tokens + ext confidences]"""+ mt = self.mt+ N = _gb.bucket(j + self.k + self.ext + 1, mt.cap, self.BUCKET)+ cg, out = self._tail_graph(N)+ cg.replay()+ return outdiff --git a/tools/hy4/depth_gate.py b/tools/hy4/depth_gate.pynew file mode 100644index 0000000..6d0747a--- /dev/null+++ b/tools/hy4/depth_gate.py@@ -0,0 +1,101 @@+"""Draft-depth gate for the Hy4 spec loop (S7, perf/hy4-strix-spec2). Pure Python, no torch.++Idea: the base draft graph runs kb steps (default 2); a tail graph runs `ext` more steps (default 1) from the base chain's last state. After the base graph the+host knows the kb tokens and their confidences (max softmax of the draft head). The gate decides whether the tail step + its verify row are worth their price.++Chain model: the extension row is accepted only if all kb base drafts were accepted AND the extension draft is right. Its marginal tokens are+P3(s) = P(acc >= kb + ext | s) with s = product of the base confidences (probability that the base chain is right if the head were calibrated). Extend iff+ P3(s) * (tokens gained) > rate * extra_ms rate = recent tokens per ms of this gate's own rounds (running means, same unit as the cost table)+ extra_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 bin+that stopped extending can still be re-measured (no selection bias: the probe rounds are not chosen by s).+"""+import os++NBIN = 10+++def _table(s):+ t = {}+ for kv in s.split(","):+ a, b = kv.split(":")+ t[int(a)] = float(b)+ return t+++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):+ self.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.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.ms_m = self.round_ms(False)++ @classmethod+ def 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")))++ def verify_ms(self, T):+ if T in self.vt:+ return self.vt[T]+ ks = sorted(self.vt)+ lo = max([x for x in ks if x < T], default=ks[0])+ hi = min([x for x in ks if x > T], default=ks[-1])+ if lo == hi:+ return self.vt[lo] + (T - lo) * (self.vt[ks[-1]] - self.vt[ks[-2]]) / max(1, ks[-1] - ks[-2])+ return self.vt[lo] + (self.vt[hi] - self.vt[lo]) * (T - lo) / (hi - lo)++ def round_ms(self, extended):+ n = self.ext if extended else 0+ return self.verify_ms(1 + self.kb + n) + self.step_ms * (self.kb + n) + (self.gap_ms if extended else 0.0)++ @staticmethod+ def sbin(confs):+ s = 1.0+ for c in confs:+ s *= min(1.0, max(0.0, c))+ return min(NBIN - 1, int(s * NBIN))++ def p_ext(self, b):+ a, n = self.hits[b]+ return (a + self.prior_n * self.prior_q * (b + 0.5) / NBIN) / (n + self.prior_n)++ def extra_ms(self):+ return self.round_ms(True) - self.round_ms(False)++ def decide(self, confs):+ """confs: confidences of the kb base drafts -> (extend?, bin)"""+ self.n_round += 1+ b = 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+ return go, b++ def update(self, b, extended, acc):+ """acc = accepted drafts of this round (clamped to the drafts verified by the caller)"""+ tokens = 1 + acc+ if extended:+ self.n_ext += 1+ self.hits[b][1] += 1.0+ if acc >= self.kb + self.ext:+ self.hits[b][0] += 1.0+ self.tok_m += self.alpha * (tokens - self.tok_m)+ 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),+ "bins": [[round(a, 1), round(n, 1)] for a, n in self.hits]}+++def draft_with_gate(gate, mg, out, kb, j):+ """out = host list of the base graph [kb tokens + kb confidences (fixed point 2^-20)]; j = head position of the round. Returns (drafts, extended, gate bin).+ The tail graph (mg.run_tail) is launched only when the gate says so: one extra draft step + one extra verify row."""+ d, confs = list(out[:kb]), [c / 1048576.0 for c in out[kb:2 * kb]]+ go, b = gate.decide(confs)+ if go:+ d += list(mg.run_tail(j).tolist()[:gate.ext])+ return d, go, bdiff --git a/tools/hy4/engine.py b/tools/hy4/engine.pyindex 99c352e..9dd9832 100644--- a/tools/hy4/engine.py+++ b/tools/hy4/engine.py@@ -64,6 +64,14 @@ class Hy4Engine:from draft_policy import CostPolicyos.environ["HY4_DRAFT_CONF"] = "1" # the draft graph appends the confidences (read at the import of mtp_head, i.e. in load())self.policy = CostPolicy.from_env()+ self.gate = None # HY4_SPEC2_GATE=1: draft kb steps, then a tail step only when the confidence gate says it pays (tools/hy4/depth_gate.py); single session only+ if os.environ.get("HY4_SPEC2_GATE", "0") == "1":+ from depth_gate import DepthGate+ assert self.policy is None, "HY4_SPEC2_GATE and HY4_DRAFT_POLICY are exclusive"+ self.gate_kb = int(os.environ.get("HY4_SPEC2_KB", "2"))+ assert 1 <= self.gate_kb and self.k == self.gate_kb + 1, "HY4_SPEC2_GATE: num-draft must be HY4_SPEC2_KB + 1 (one tail step)"+ os.environ["HY4_DRAFT_CONF"] = "1" # the draft graphs append the confidences (read at the import of mtp_head, i.e. in load())+ self.gate = DepthGate.from_env(self.gate_kb, self.k - self.gate_kb)self.ready = Falseself.meta = Noneself.last_stats: dict = {}@@ -124,6 +132,9 @@ class Hy4Engine:return self.SG.GraphDecoder(M)def _mtp_graph(self):+ if self.gate is not None:+ import importlib+ return importlib.import_module(f"{self.SG.__name__.rsplit('.', 1)[0]}.mtp_gate").MTPGraphGate(self.MT, self.gate_kb, self.k - self.gate_kb)return self.MH.MTPGraph(self.MT, self.k)def _decode_flags(self):@@ -298,6 +309,9 @@ class Hy4Engine:tdec = time.perf_counter()if speculative:k = self.k+ kd0 = self.gate_kb if self.gate is not None else k # drafts read from the first draft graph+ if self.gate is not None:+ from depth_gate import draft_with_gatepc = time.perf_countertm = [0.0, 0.0, 0.0]ng = None@@ -339,13 +353,16 @@ class Hy4Engine:planned = Falseif td_prev is not None and not skip:gap[0] += lt[0] - td_prev+ gb = Noneif skip:d, ext = [], cltb = pc()else:d = dd.tolist()confs = None- if self.MH.CONF: # the draft graph appended the k confidences (fixed point 2^-20)+ if self.gate is not None:+ d, gext, gb = draft_with_gate(self.gate, self.MG, d, kd0, j)+ elif self.MH.CONF: # the draft graph appended the k confidences (fixed point 2^-20)confs = [c / 1048576.0 for c in d[k:]]d = d[:k]if self.policy is not None:@@ -353,7 +370,7 @@ class Hy4Engine:tb = pc()ext = []if ng is not None and not skip:- lim = min(self.ngram_ext, self.SG.TM - 1 - k)+ lim = min(self.ngram_ext, self.SG.TM - 1 - (len(d) if self.gate is not None else k))if self.ngram_gate:since += 1lim = lim if rate >= 0.6 else (2 if rate >= 0.4 else (lim if since >= 8 else 0))@@ -381,6 +398,8 @@ class Hy4Engine:while acc < nd and toks[acc + 1] == amh[acc]:acc += 1kk = len(toks) - 1 - len(ext) # drafted rows of this round (the policy may cut the chain below k)+ if gb is not None:+ self.gate.update(gb, gext, min(acc, kk))if skip:passelif self.policy is not None and confs is not None:@@ -422,6 +441,8 @@ class Hy4Engine:st["capture_s"] = GR.stats["capture_s"] - caps0if self.policy is not None:st["policy"] = self.policy.stats()+ if self.gate is not None:+ st["gate"] = self.gate.stats()st["ngram"] = {"ext": self.ngram_ext, "min": self.ngram_min, "fill": self.ngram_fill, "hit_rounds": n_hit, "ext_rows": n_ext, "ext_accepted": n_extacc, "long": self.ngram_long, "long_rounds": n_long}else:while out_n < max_new and not stop and not cancel():diff --git a/tools/hy4/serve.py b/tools/hy4/serve.pyindex 36a6b0d..16e976b 100644--- a/tools/hy4/serve.py+++ b/tools/hy4/serve.py@@ -269,7 +269,8 @@ def build_app(st: State):pf, dc = stats["prefill_s"], stats["decode_s"]print(f"req {st.served}: prompt {stats['prompt_tokens']} tok prefill {pf:.2f} s ({stats['prompt_tokens'] / pf:.0f} tok/s; trunk {stats.get('prefill_trunk_s', 0):.2f} s, "f"draft fill {stats.get('prime_s', 0):.2f} s {stats.get('prime_mode')}) | decode {stats['decode_tokens']} tok {dc:.2f} s = "- f"{stats['decode_tokens'] / dc if dc else 0:.2f} tok/s spec={stats['speculative']} rounds {stats['rounds']} tau {stats['tau']} hist {stats['accept_hist']} | {finish}",+ f"{stats['decode_tokens'] / dc if dc else 0:.2f} tok/s spec={stats['speculative']} rounds {stats['rounds']} tau {stats['tau']} hist {stats['accept_hist']} | {finish}"+ + (f" | gate {stats['gate']}" if stats.get("gate") else ""),flush=True)yield ("end", stats, finish, n_gen)diff --git a/tools/hy4/step/spec2_arms.py b/tools/hy4/step/spec2_arms.pynew file mode 100644index 0000000..ee9c370--- /dev/null+++ b/tools/hy4/step/spec2_arms.py@@ -0,0 +1,125 @@+"""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.+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)+Output: table on stdout + <N1119>/out/<OD_NAME>.spec2.json. ~50 min GPU: TMAX 3300."""+import hashlib, json, os, re, signal, statistics, subprocess, sys, time, urllib.request+E = os.environ; tree = os.getcwd(); t0 = time.time()+H = E.get("B2_H", "/home/kamel"); N = E.get("N1119", f"{H}/scratch/n1119")+name, port = E["OD_NAME"], E["OD_PORT"]; tmax = int(E.get("OD_TMAX", "3300"))+GGUF = E.get("GGUF", f"{H}/models/hy4-flash-gguf/Hy4-flash-Q3_K-00001-of-00002.gguf")+B2 = E.get("B2_DIR", f"{H}/scratch/b2"); OUT = f"{N}/out"; os.makedirs(OUT, exist_ok=True)+GM = E.get("B2_GM", f"{B2}/gm_build"); CO = E.get("B2_CO", f"{B2}/moe_dec.co")+COMMON = {"EXL3_GM_BUILD_DIR": GM, "HY4_GM_EXT": f"{GM}/exl3_gm_ext.so", "MOE_DEC_CO": CO, "PCTXS": "4096", "PTS": "1,2,3,4,5,6", "REPS": "3", "LV_CTX": "16384"}+ARM_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)+def log(*a): print(time.strftime("%T"), *a, flush=True)++def stop(srv):+ try: os.killpg(srv.pid, signal.SIGTERM)+ except ProcessLookupError: pass+ time.sleep(8)+ try: os.killpg(srv.pid, signal.SIGKILL)+ except ProcessLookupError: pass++def chat(body):+ req = urllib.request.Request(f"http://127.0.0.1:{port}/v1/chat/completions", json.dumps(body).encode(), {"Content-Type": "application/json", "X-Kyojin-Bench": "1"})+ r = json.load(urllib.request.urlopen(req, timeout=900)); tm = r.get("timings") or {}; txt = r["choices"][0]["message"].get("content") or ""+ return {"tps": tm.get("predicted_per_second"), "tau": tm.get("tau"), "n": tm.get("predicted_n"), "prompt_n": tm.get("prompt_n"), "md5": hashlib.md5(txt.encode()).hexdigest()[:12]}++def gate_lines(path):+ """per request (server log line 'req N: ...'): rounds, tau, ext rounds of the gate when present"""+ out = []+ 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)+ out.append({"req": int(m.group(1)), "rounds": int(m.group(2)), "tau": float(m.group(3)), "hist": json.loads(m.group(4)), "gate_rounds": g and int(g.group(1)), "ext_rounds": g and int(g.group(2))})+ return out++def class_means(pts):+ r = {}+ for cls in ("code", "prose", "chat"):+ v = [p for p in pts.values() if p["cls"] == cls and p["tau"] and p["tps"]]+ if v:+ r[cls] = {"tau": statistics.mean(p["tau"] for p in v), "tps": statistics.mean(p["tps"] for p in v), "round_ms": statistics.mean(1000 * p["tau"] / p["tps"] for p in v)}+ return r++def main():+ res = {"levers": None, "arms": {}, "order": E.get("SP2_ORDER", "ABCA")}+ 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"+ try:+ subprocess.run([sys.executable, "-u", f"{tree}/tools/hy4/step/b2_levers_arm.py"], cwd=tree, env={**E, **COMMON, **ARM_C}, stdout=open(lg, "w"), stderr=subprocess.STDOUT, timeout=1000)+ except subprocess.TimeoutExpired:+ log("SP2 levers TIMEOUT")+ line = next((l for l in open(lg, errors="replace").read().splitlines() if l.startswith("LEVERS_RESULT ")), None)+ if line:+ res["levers"] = json.loads(line.split(" ", 1)[1]); log("SP2 replay ms", {k: v["median"] for k, v in res["levers"]["round_ms"].items()})+ else:+ log("SP2 levers: NO RESULT")+ save()+ passes = [p.split("|", 3) for p in open(E.get("B2_PASSES", f"{B2}/head_tau.passes")).read().strip().split("\n")]+ seen = {}+ for letter in res["order"]:+ seen[letter] = seen.get(letter, 0) + 1+ key = letter if seen[letter] == 1 else f"{letter}{seen[letter]}"+ if time.time() - t0 > tmax - 600: log("SP2 skipped (deadline)", key); continue+ extra, nd = ARMS[letter]+ env = {**E, **COMMON, **ARM_C, **extra, "HY4_PRECAPTURE": "all"}+ sl = f"{OUT}/{name}.arm_{key}.server.log"+ srv = subprocess.Popen([sys.executable, "-u", f"{tree}/tools/hy4/serve.py", "--model", GGUF, "--port", port, "-c", "12288", "--model-id", "Hy4-Kyojin", "--num-draft", nd], env=env,+ stdout=open(sl, "w"), stderr=subprocess.STDOUT, start_new_session=True)+ ok, ts = False, time.time()+ while time.time() - ts < 900 and srv.poll() is None:+ try: urllib.request.urlopen(f"http://127.0.0.1:{port}/health", timeout=3); ok = True; break+ except Exception: time.sleep(4)+ log("SP2 boot", key, {**extra, "num_draft": nd}, "ready", ok, f"load_s {time.time() - ts:.0f}")+ try:+ if ok:+ pts = {}+ for i, (label, mode, ex, rest) in enumerate(passes):+ for rep in range(int(E.get("SP2_REPS", "2"))):+ if time.time() - t0 > tmax - 60: log("SP2 skipped (deadline)", label); break+ body = {"model": "Hy4-Kyojin", "max_tokens": 256, "temperature": 0, "stream": False, "cache_prompt": False, "speculative": True,+ "chat_template_kwargs": {"enable_thinking": False, "reasoning_effort": "no_think"}, **json.loads(ex)}+ if i == 0 and rep == 0: chat(body) # warm-up (graphs, first-touch pages), discarded+ r = chat(body); cls = label.split("headtau_")[1][:-3].rstrip("0123456789")+ pts[f"{label}#{rep}"] = {"cls": cls, **r}+ log(f"SP2 {key} {label}#{rep}: {r['tps'] and round(r['tps'], 2)} tok/s tau {r['tau']} round {r['tau'] and r['tps'] and round(1000 * r['tau'] / r['tps'], 1)} ms md5 {r['md5']}")+ res["arms"][key] = {"letter": letter, "num_draft": nd, "env": extra, "points": pts, "classes": class_means(pts)}+ finally:+ stop(srv)+ res["arms"].get(key, {})["reqs"] = gate_lines(sl)+ save()+ # ---- table+ arms = res["arms"]+ 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"):+ base = statistics.mean(a["classes"][cls]["tps"] for a in ref if cls in a["classes"]) if ref else None+ for k, a in arms.items():+ c = a["classes"].get(cls)+ if c:+ ext = [q["ext_rounds"] / q["gate_rounds"] for q in a.get("reqs", []) if q.get("gate_rounds")]+ print(f"{cls:<6} arm {k:<3} (num-draft {a['num_draft']}{' gate' if a['env'] else ''}): {c['tps']:.2f} tok/s tau {c['tau']:.3f} round {c['round_ms']:.1f} ms"+ + (f" | d vs A {100 * (c['tps'] / base - 1):+.1f} %" if base else "") + (f" | gate ext rate {statistics.mean(ext):.2f}" if ext else ""))+ if res["levers"]:+ print("\nSPEC2 replay ms per verify round (4K, arm C flags):", {k: v["median"] for k, v in res["levers"]["round_ms"].items()})+ 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+ for cls in ("code", "prose", "chat"):+ t = {l: mean_cls(l, cls) for l in "ABC"}+ 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} %")+ log("SPEC2_DONE", name, f"{time.time() - t0:.0f}s")++if __name__ == "__main__":+ main()diff --git a/tools/hy4/test_depth_gate.py b/tools/hy4/test_depth_gate.pynew file mode 100644index 0000000..57d3712--- /dev/null+++ b/tools/hy4/test_depth_gate.py@@ -0,0 +1,169 @@+"""CPU test of the HY4_SPEC2_GATE logic with a fake engine (pure Python, no torch / GPU): python3 tools/hy4/test_depth_gate.py+Fake trunk = deterministic next-token function f; fake draft graphs = f with noise, confidence correlated with correctness. The round loop copies the engine's+accept / rewind code (engine.generate). Checks: (1) the emitted stream equals the greedy stream of f for ANY gate decision (fixed depth 2, 3, random, DepthGate),+(2) the tail graph is launched only when the gate extends and at head position j + kb, (3) fw.n / tokens stay consistent after every rewind, rows <= TM,+(4) the gate learns: chat-like source (low confidence) -> few extensions, code-like -> many, and its tokens / ms beats the worse fixed depth."""+import os, random, sys+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from depth_gate import DepthGate, draft_with_gate++V, TM = 1000, 8+f = lambda a, b: (a * 31 + b * 17 + 7) % V+ROW = {1: 61.8, 2: 76.7, 3: 90.3, 4: 104.0, 5: 117.3, 6: 130.6, 7: 143.8, 8: 157.0}+++class FakeGR: # the verify graph decoder: rows by position, rewind = a length+ def __init__(self, ids):+ self.tokens, self.n = list(ids), len(ids)++ def step_rows(self, toks):+ assert 1 <= len(toks) <= TM+ start = self.n+ self.tokens.extend(toks)+ self.n += len(toks)+ assert len(self.tokens) == self.n+ return [self._nxt(start + i) for i in range(len(toks))]++ def _nxt(self, pos): # argmax after row at `pos`: f of the two latest tokens of the sequence+ return f(self.tokens[pos], self.tokens[pos - 1])++ def rewind(self, n):+ assert n <= self.n+ del self.tokens[n:]+ self.n = n+++class Out:+ def __init__(self, v):+ self.v = v++ def tolist(self):+ return list(self.v)+++class FakeMG: # base graph (kb steps) + tail graph; head rows are written by absolute position+ def __init__(self, gr, kb, ext, p_ok, rng, conf_noise=0.15):+ self.gr, self.k, self.ext, self.p_ok, self.rng, self.cn = gr, kb, ext, p_ok, rng, conf_noise+ self.last, self.j, self.tail_calls, self.tail_pos = None, None, 0, []++ def _step(self, a, b):+ ok = self.rng.random() < self.p_ok+ t = f(a, b) if ok else (f(a, b) + 1 + self.rng.randrange(V - 1)) % V+ conf = min(1.0, max(0.0, (0.9 if ok else 0.35) + self.rng.uniform(-self.cn, self.cn)))+ return t, conf++ def run(self, y, j):+ seq = self.gr.tokens[:self.gr.n] # the trunk sequence up to and including y+ assert seq[-1] == y and j == self.gr.n - 1+ toks, confs, a, b = [], [], y, seq[-2]+ for i in range(self.k):+ t, c = self._step(a, b)+ toks.append(t), confs.append(int(c * 1048576))+ a, b = t, a+ self.last, self.j = (a, b), j+ return Out(toks + confs)++ def run_tail(self, j):+ assert self.j == j, "tail launched for another round than the base graph"+ self.tail_calls += 1+ self.tail_pos.append(j + self.k)+ toks, confs, a, b = [], [], *self.last+ for i in range(self.ext):+ t, c = self._step(a, b)+ toks.append(t), confs.append(int(c * 1048576))+ a, b = t, a+ return Out(toks + confs)+++def generate(policy, p_ok, n_new=400, seed=1, kfix=3, gate=None):+ """policy: 'fixed' (kfix drafts, no gate) or 'gate'. Returns (emitted tokens, ms, rounds, gr, mg)"""+ rng = random.Random(seed)+ ids = [5, 9, 11]+ gr = FakeGR(ids)+ y = f(ids[-1], ids[-2])+ gr.tokens.append(y)+ gr.n += 1 # y emitted, sits at position n - 1 (the engine: fw.n counts it after the first step; here the same relation j = n - 1)+ out, rounds, ms = [y], 0, 0.0+ kb = gate.kb if gate else kfix+ mg = FakeMG(gr, kb, gate.ext if gate else 0, p_ok, rng)+ while len(out) < n_new:+ j = gr.n - 1+ dd = mg.run(y, j).tolist()+ if gate:+ d, gext, gb = draft_with_gate(gate, mg, dd, kb, j)+ else:+ d, gext, gb = dd[:kb], False, None+ toks = [y] + d+ gr.rewind(gr.n - 1) # row 0 = y is re-verified at its own position, like step_rows(toks) from fw.n - 1 + 1+ start = gr.n+ amh = gr.step_rows(toks)+ acc = 0+ nd = len(toks) - 1+ while acc < nd and toks[acc + 1] == amh[acc]:+ acc += 1+ new = toks[1:acc + 1] + [amh[acc]]+ gr.rewind(start + 1 + acc) # keep y and the accepted drafts; the next y is amh[acc] appended below+ y = amh[acc]+ gr.tokens.append(y)+ gr.n += 1+ assert len(gr.tokens) == gr.n and gr.tokens[start:start + 1] == [toks[0]]+ if gate:+ gate.update(gb, gext, min(acc, len(d)))+ ms += gate.round_ms(gext)+ else:+ ms += ROW[1 + kb] + 3.0 * kb+ out.extend(new)+ rounds += 1+ return out[:n_new], ms, rounds, gr, mg+++def truth(n_new):+ s = [5, 9, 11]+ y = f(s[-1], s[-2])+ s.append(y)+ out = [y]+ while len(out) < n_new:+ y = f(s[-1], s[-2])+ s.append(y)+ out.append(y)+ return out+++def main():+ ref = truth(400)+ for p_ok in (0.55, 0.9):+ for kfix in (1, 2, 3):+ o, ms, r, gr, mg = generate("fixed", p_ok, kfix=kfix)+ assert o == ref, ("fixed", kfix, p_ok)+ for seed in (1, 2, 3):+ g = DepthGate(ROW, 3.0, 0.3, 2, 1, probe=4)+ o, ms, r, gr, mg = generate("gate", p_ok, seed=seed, gate=g)+ assert o == ref, ("gate", p_ok, seed)+ assert mg.tail_calls == g.n_ext, (mg.tail_calls, g.n_ext)+ assert all(isinstance(x, int) for x in mg.tail_pos)+ # adversarial: a gate that flips a coin every round (any decision sequence must keep the stream exact)+ class Coin(DepthGate):+ def decide(self, confs):+ self.n_round += 1+ return random.random() < 0.5, 0+ def update(self, b, extended, acc):+ self.n_ext += extended+ random.seed(7)+ g = Coin(ROW, 3.0, 0.3, 2, 1)+ o, ms, r, gr, mg = generate("gate", p_ok, gate=g)+ assert o == ref and mg.tail_calls == g.n_ext+ # the gate learns: low-acceptance source extends rarely, high-acceptance source often; gate tok/ms >= the worse fixed depth+ res = {}+ for name, p in (("chat-like", 0.62), ("code-like", 0.93)):+ g = DepthGate(ROW, 3.0, 0.3, 2, 1)+ o, ms, r, gr, mg = generate("gate", p, n_new=3000, gate=g)+ rates = {k: (lambda r: len(r[0]) / r[1])(generate("fixed", p, n_new=3000, kfix=k)) for k in (2, 3)}+ res[name] = (mg.tail_calls / r, len(o) / ms, rates)+ 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+ print("test_depth_gate OK")+++if __name__ == "__main__":+ main()