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 online depth gate: arm O (learn) default mode, per-round depth histogram and changed-depth counter, CPU test, scrubbed driver defaults
YanissAmzef9616a729c4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ffb4616..d0cfa73 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,11 @@# Changelog+## Unreleased 1.9.3++- Hy4-flash: online speculative draft-depth gate, `HY4_SPEC2_GATE=1` (default off), mode `HY4_SPEC2_MODE=learn` (default, the measured S7 arm O), KB 2, THETA 0.6 for the `static` mode.+ Base draft graph of 2 steps plus a confidence-gated third step. Fires counter per request: depth chosen per round and rounds where the gate changed the depth.+ Also: context-bucket graphs (`HY4_GRAPH_BUCKET_REL`, default 0, the gate's tail graph uses the same bucket helper). See `doc/env_vars.md`.+## 1.9.2Hy4-flash server hotfix: tool calling, a quiet exit when the client leaves, request-parser fixes, Strix install fixes, docs.diff --git a/doc/env_vars.md b/doc/env_vars.mdindex 22740e3..a663d18 100644--- a/doc/env_vars.md+++ b/doc/env_vars.md@@ -1063,6 +1063,19 @@ weights. `on` (also `1`, `preset`, `true`, `yes`) loads the preset bundled in thspec. Unset, empty, `0`, `off`, `false`, `no` and `none`: no edit is installed. A malformed spec or a missing file stopsthe load. The preset is in `presets/hy4-uncensor/`. See [hy4.md](hy4.md).+#### `HY4_SPEC2_GATE` (default `0`, off)++Hy4-flash server only. `1` turns on the online draft-depth gate: the base draft graph runs `HY4_SPEC2_KB` steps (default `2`), and a tail graph+runs one more step (plus its verify row) only when the gate says it pays. `--num-draft` must equal `HY4_SPEC2_KB + 1` (the shipped 3). It is exclusive with+`HY4_DRAFT_POLICY`, and the gate turns `HY4_DRAFT_CONF` on by itself. Speculation stays lossless: the gate only changes how many drafts are verified.+`HY4_SPEC2_MODE` picks the rule: `learn` (default, the measured S7 arm O: an online rule that learns the chance that the extension is accepted per confidence bin,+reset at every request, so a repeated request repeats its decisions), `static` (extend when the product of the two base confidences is at least+`HY4_SPEC2_THETA`, default `0.6`, no state), `carry` (the `learn` rule without the per-request reset, a negative control only). Other knobs of the learn rule:+`HY4_SPEC2_STEP_MS`, `HY4_SPEC2_GAP_MS`, `HY4_SPEC2_PRIOR_N`, `HY4_SPEC2_PRIOR_Q`, `HY4_SPEC2_PROBE` (every N-th round extends whatever the bin says, default 16), `HY4_ROW_MS`+(verify ms per row count). Fires counter: each request prints `FIRES gate mode=... depth_hist={2: n, 3: m} changed=a/b req_depth_hist=... req_changed=a/b`+(depth chosen per round; `changed` = rounds where the gate cut the chain below the shipped depth; 0 means the gate did not fire) and `fires {...}` (rounds, depth2, gate_skip, gate_run).+Rollback: unset the flag. See `tools/hy4/depth_gate.py`.+#### Hy4-flash 1.9.1 levers (all on by default; `=0` restores 1.9.0)Hy4-flash server only. `tools/hy4/serve.py` sets these in `SHIPPED_ENV` without overriding a value you set, so `HY4_<FLAG>=0 python tools/hy4/serve.py ...` is the rollback of one lever to the 1.9.0 behaviour. The levers are independent of each other. Guide: [hy4.md](hy4.md).diff --git a/tests/test_hy4_depth_gate.py b/tests/test_hy4_depth_gate.pynew file mode 100644index 0000000..d1eda34--- /dev/null+++ b/tests/test_hy4_depth_gate.py@@ -0,0 +1,105 @@+"""CPU test of the HY4_SPEC2_GATE online depth gate (S7 arm O): synthetic acceptance stream into DepthGate, no GPU, no torch, no model.+Asserts the depth decisions, the per-round depth histogram and the 'rounds where the gate changed the depth' counter (0 = the arm did not fire)."""+import os+import sys++sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "tools", "hy4"))+from depth_gate import DepthGate, MODE_DEFAULT # noqa: E402++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}+HI, LO = [0.99, 0.99], [0.3, 0.3] # base confidences: bin 9 (s = 0.98) and bin 0 (s = 0.09)+++def _gate(mode="learn", **kw):+ return DepthGate(ROW, 3.0, 0.3, 2, 1, mode=mode, **kw)+++def run(g, stream):+ """stream: list of (confs, ext_accepted). Mimics the engine: decide, then update with the accepted drafts of the round."""+ depths = []+ for confs, ext_ok in stream:+ go, b = g.decide(confs)+ depths.append(2 + go)+ acc = (3 if ext_ok else 2) if go else 2 # base chain always right here; the extension only counts when it ran+ g.update(b, go, acc)+ return depths+++def test_arm_o_is_the_default_mode():+ assert MODE_DEFAULT == "learn"+ os.environ.pop("HY4_SPEC2_MODE", None)+ assert DepthGate.from_env(2, 1).mode == "learn"+ os.environ["HY4_SPEC2_MODE"] = "static"+ try:+ assert DepthGate.from_env(2, 1).mode == "static"+ finally:+ del os.environ["HY4_SPEC2_MODE"]+++def test_confident_and_unconfident_rounds():+ g = _gate()+ g.reset()+ assert run(g, [(HI, True)] * 5) == [3] * 5 # prior of bin 9 (0.475) beats the break-even (about 0.41)+ g.reset()+ assert run(g, [(LO, False)] * 15) == [2] * 15 # prior of bin 0 (0.025) is far below it+ st = g.stats()+ assert st["req_depth_hist"] == {2: 15} and st["req_changed"] == 15+ assert st["depth_hist"] == {2: 15, 3: 5} and st["changed"] == 15 and st["rounds"] == 20+++def test_probe_round_extends_whatever_the_bin_says():+ g = _gate()+ g.reset()+ depths = run(g, [(LO, False)] * 33)+ assert [i + 1 for i, d in enumerate(depths) if d == 3] == [16, 32] # every 16th round (HY4_SPEC2_PROBE)+++def test_gate_learns_to_stop_a_confident_but_wrong_bin():+ g = _gate(probe=0)+ g.reset()+ depths = run(g, [(HI, False)] * 40) # confidence says yes, the extension is never accepted+ assert depths[0] == 3 and depths[-1] == 2+ first_cut = depths.index(2)+ assert 0 < first_cut < 20 and all(d == 2 for d in depths[first_cut:])+ assert g.stats()["req_changed"] == 40 - first_cut+++def test_per_request_reset_and_lifetime_counters():+ g = _gate()+ s1 = [(HI, True), (LO, False), (HI, False)] * 7+ g.reset()+ d1 = run(g, s1)+ st1 = g.stats()+ run(g, [(LO, False)] * 9) # an unrelated request in between+ g.reset()+ d2 = run(g, s1)+ st2 = g.stats()+ assert d1 == d2 and st1["digest"] == st2["digest"] # same request, same decisions (no carried state)+ assert st2["req_rounds"] == len(s1) and st2["req_depth_hist"] == st1["req_depth_hist"] and st2["req_changed"] == st1["req_changed"]+ assert st2["rounds"] == 2 * len(s1) + 9 and sum(st2["depth_hist"].values()) == st2["rounds"] # lifetime survives reset+++def test_carry_mode_is_the_negative_control():+ g = _gate("carry")+ g.reset()+ s = [(HI, False)] * 25+ d1 = run(g, s)+ g.reset() # no-op in carry mode+ d2 = run(g, s)+ assert d1 != d2+++def test_static_mode_threshold():+ g = _gate("static", theta=0.6)+ assert run(g, [([0.9, 0.9], True), ([0.5, 0.5], True), ([0.8, 0.75], True), ([0.99, 0.2], True)]) == [3, 2, 3, 2]+ assert g.stats()["changed"] == 2+++def test_fires_line_zero_means_not_fired():+ g = _gate()+ g.reset()+ run(g, [(HI, True)] * 4)+ line = g.fires_line()+ assert line.startswith("FIRES gate mode=learn") and "changed=0/4" in line and "depth_hist={3: 4}" in line+ run(g, [(LO, False)] * 2)+ assert "changed=2/6" in g.fires_line() and "req_changed=2/6" in g.fires_line()diff --git a/tools/hy4/depth_gate.py b/tools/hy4/depth_gate.pyindex 93ef479..0d7f854 100644--- a/tools/hy4/depth_gate.py+++ b/tools/hy4/depth_gate.py@@ -21,6 +21,7 @@ import zlibNBIN = 10THETA = 0.6+MODE_DEFAULT = "learn" # S7 arm O: the online rule with a reset at every request. static (a pure threshold, no state) and carry (no reset, negative control) are the other modesdef _table(s):@@ -38,6 +39,8 @@ class DepthGate:self.prior_n, self.prior_q, self.probe, self.alpha, self.tok0 = prior_n, prior_q, probe, alpha, tok0self.mode, self.theta = mode, thetaself.life_rounds = self.life_ext = 0 # lifetime counters (never reset): the server log differences them per request+ self.life_hist = {} # lifetime histogram of the chosen draft depth {depth: rounds}+ self.life_changed = 0 # lifetime rounds where the gate CHANGED the depth: it cut the chain below the shipped depth kb + extself.reset(force=True)def reset(self, force=False):@@ -49,13 +52,15 @@ class DepthGate: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+ self.req_hist = {} # same two counters, this request only+ self.req_changed = 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")),- mode=os.environ.get("HY4_SPEC2_MODE", "static"), theta=float(os.environ.get("HY4_SPEC2_THETA", str(THETA))))+ mode=os.environ.get("HY4_SPEC2_MODE", MODE_DEFAULT), theta=float(os.environ.get("HY4_SPEC2_THETA", str(THETA))))def verify_ms(self, T):if T in self.vt:@@ -100,6 +105,12 @@ class DepthGate:if self.probe and self.n_round % self.probe == 0:go = Trueself.life_ext += go+ depth = self.kb + (self.ext if go else 0)+ self.life_hist[depth] = self.life_hist.get(depth, 0) + 1+ self.req_hist[depth] = self.req_hist.get(depth, 0) + 1+ if not go: # the shipped depth is kb + ext: a cut round is a round where the gate changed the depth+ self.life_changed += 1+ self.req_changed += 1self.dig = zlib.crc32(b"\x01" if go else b"\x00", self.dig)return go, b@@ -118,9 +129,14 @@ class DepthGate:self.ms_m += self.alpha * (self.round_ms(extended) - self.ms_m)def stats(self):- 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),+ 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}", "depth_hist": dict(sorted(self.life_hist.items())), "changed": self.life_changed, "req_depth_hist": dict(sorted(self.req_hist.items())), "req_changed": self.req_changed, "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 fires_line(self):+ """one line for the server log / an A/B driver: depth chosen per round (lifetime and this request) and the rounds where the gate changed the depth. changed = 0 means the arm did not fire."""+ return (f"FIRES gate mode={self.mode} depth_hist={dict(sorted(self.life_hist.items()))} changed={self.life_changed}/{self.life_rounds} "+ f"req_depth_hist={dict(sorted(self.req_hist.items()))} req_changed={self.req_changed}/{self.n_round}")+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).diff --git a/tools/hy4/serve.py b/tools/hy4/serve.pyindex c78cf62..364190a 100644--- a/tools/hy4/serve.py+++ b/tools/hy4/serve.py@@ -270,10 +270,12 @@ def build_app(st: State):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" | gate {stats['gate']}" if stats.get("gate") else "") + (f" | fires {stats['fires']}" if stats.get("fires") else "")+ + (f" | gate {stats['gate']}" if stats.get("gate") else "") + (f" | fires {stats['fires']}" if stats.get("fires") and (stats.get("gate") or os.environ.get("HY4_REQ_ROUNDLOG", "0") == "1") else "")+ (f" | round_ms {[round(x, 1) for x in stats['round_ms']]} gap_ms {[round(x, 1) for x in stats['gap_ms']]} busy_ms {stats['busy_ms']:.1f} ngram {stats['ngram']}"if os.environ.get("HY4_REQ_ROUNDLOG", "0") == "1" and "round_ms" in stats and "ngram" in stats else ""),flush=True)+ if stats.get("gate") and st.engine.gate is not None:+ print(st.engine.gate.fires_line(), flush=True)yield ("end", stats, finish, n_gen)def timings(stats):diff --git a/tools/hy4/step/spec2_arms.py b/tools/hy4/step/spec2_arms.pyindex e5b76b0..3550cdb 100644--- a/tools/hy4/step/spec2_arms.py+++ b/tools/hy4/step/spec2_arms.py@@ -5,11 +5,11 @@ Question: tau and ms per round on the 6 head_tau prompts (code / prose / chat xorder 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)-Output: table on stdout + <N1119>/out/<OD_NAME>.spec2.json. ~50 min GPU: TMAX 3300."""+env: OD_PORT OD_NAME GGUF SP2_WORK B2_H B2_DIR B2_GM B2_CO B2_PASSES SP2_ORDER SP2_REPS (default 2) SP2_LEVERS (default 1)+Output: table on stdout + <SP2_WORK>/out/<OD_NAME>.spec2.json. ~50 min GPU: TMAX 3300."""import ast, hashlib, json, os, re, signal, statistics, subprocess, sys, time, urllib.requestE = os.environ; tree = os.getcwd(); t0 = time.time()-H = E.get("B2_H", "/home/kamel"); N = E.get("N1119", f"{H}/scratch/n1119")+H = E.get("B2_H", os.path.expanduser("~")); N = E.get("SP2_WORK", f"{H}/spec2_work")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)diff --git a/tools/hy4/test_spec2_driver.py b/tools/hy4/test_spec2_driver.pyindex 29ec6e5..5a9d75a 100644--- a/tools/hy4/test_spec2_driver.py+++ b/tools/hy4/test_spec2_driver.py@@ -7,7 +7,7 @@ HERE = os.path.dirname(os.path.abspath(__file__)); sys.path.insert(0, HERE)from depth_gate import DepthGatepasses = 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")+os.environ.update(OD_NAME="chk", OD_PORT="8999", SP2_WORK=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, timestate = {}class FakeProc: