Skip to content

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.

Hy4 multi-session: speculation only while <= HY4_MU_SPEC_MAXB (2) sessions decode; graph-replay A/B driver for the gm MoE / row tiles flags

YanissAmz2801168b62c9
diff --git a/tests/test_hy4_mu_sched.py b/tests/test_hy4_mu_sched.py
index f18ce71..513ec99 100644
--- a/tests/test_hy4_mu_sched.py
+++ b/tests/test_hy4_mu_sched.py
@@ -47,7 +47,10 @@ class FakeEng:
out[s] = [s.y]
return out
- spec_round = plain_round
+ def spec_round(self, sess):
+ out = self.plain_round(sess)
+ self.log[-1] = ("spec", self.log[-1][1])
+ return out
def run(reqs, eng, chunk=4, spec=False):
@@ -85,7 +88,7 @@ def test_prefill_chunk_is_interleaved_with_decode_rounds():
b.done.wait(10)
a.done.wait(10)
sch.shutdown()
- seq = [x[0] for x in eng.log if x[0] in ("pf", "dec")]
+ seq = [("dec" if x[0] == "spec" else x[0]) for x in eng.log if x[0] in ("pf", "dec", "spec")]
i0 = seq.index("pf", 1) # b's chunks (a's single chunk comes first)
run_pf = 0
longest = 0
@@ -107,3 +110,12 @@ def test_cancel_context_and_error():
bad = ME.Request(list(range(4)), 5)
run([bad], FakeEng(boom=True))
assert bad.error and "boom" in bad.error
+
+
+def test_speculation_only_while_few_sessions_decode():
+ eng = FakeEng(slots=4)
+ reqs = [ME.Request(list(range(4)), 30) for _ in range(4)]
+ run(reqs, eng, spec=True)
+ kinds = {(x[0], len(x[1])) for x in eng.log if x[0] in ("spec", "dec")}
+ assert all(not (k == "spec" and n > 2) for k, n in kinds) and ("spec", 1) in kinds or ("spec", 2) in kinds
+ assert any(k == "dec" and n >= 3 for k, n in kinds)
diff --git a/tools/hy4/mu_ab.py b/tools/hy4/mu_ab.py
new file mode 100644
index 0000000..6ab0b3b
--- /dev/null
+++ b/tools/hy4/mu_ab.py
@@ -0,0 +1,124 @@
+"""mu_ab.py: ONE load, graph-replay A/B of the batched step at T = 1 / 2 / 4 / 8 rows (rows of different sessions), flags toggled at run time between arms
+(captured graphs are dropped on every toggle): stock vs HY4_GM_MOE + HY4_ROW_TILES (cherry-picked from perf/hy4-strix-spec 961625969). ABAB order, median of 3 x 12 replays.
+Also eager synchronised class timers (routed experts class) and the arg-max agreement of the two arms."""
+import json
+import os
+import statistics
+import sys
+import time
+
+tree = os.getcwd()
+sys.path.insert(0, os.path.join(tree, "tools", "hy4"))
+import serve # noqa: E402
+
+CTX = 4096
+serve.apply_env(CTX)
+import torch # noqa: E402
+import serve_core as C # noqa: E402
+from mu_engine import MuEngine # noqa: E402
+
+GGUF = "/path/to/models/hy4-flash-gguf/Hy4-flash-Q3_K-00001-of-00002.gguf"
+PROMPTS = ["Explain in a few short paragraphs why the sky is blue and why sunsets are red.",
+ "Ecris une courte histoire sur un chat qui apprend a naviguer sur un petit bateau.",
+ "Write a Python function that merges two sorted lists, then explain its complexity.",
+ "List five practical tips to keep a sourdough starter healthy, with one sentence of reason each."]
+e = MuEngine(tree, GGUF, ctx=CTX, k=3, slots=4)
+e.load(print)
+V = C.Vocab(e.meta)
+GR, fw, hf = e.GR, e.M, e.hf
+import importlib # noqa: E402
+BG = importlib.import_module("exllamav3.loader.mla_bgemv")
+HB = importlib.import_module("exllamav3.loader.head_bf16")
+print("flags available: GM_MOE", hasattr(hf, "GM_MOE"), "ROW_TILES bgemv", hasattr(BG, "ROW_TILES"), "head", hasattr(HB, "ROW_TILES"), flush=True)
+sess = []
+e.phase("prefill")
+for i in range(4):
+ s = GR.new_session(i)
+ ids = V.encode(V.template.render([{"role": "user", "content": PROMPTS[i]}], None, True, reasoning_effort="no_think"))
+ e.prefill_begin(s, ids, 1024)
+ while not e.prefill_step(s):
+ pass
+ sess.append(s)
+e.phase("decode")
+
+
+def set_arm(on):
+ hf.GM_MOE = on
+ BG.ROW_TILES = on
+ HB.ROW_TILES = on
+ GR.clear()
+ fw.stats["gm_moe_calls"] = 0
+
+
+def rows_for(T):
+ if T <= 4:
+ return [(sess[i], [sess[i].y]) for i in range(T)]
+ return [(sess[i], [sess[i].y, sess[i].y]) for i in range(4)]
+
+
+def replay_ms(T, reps=12):
+ rows = rows_for(T)
+ n0 = [s.n for s, _ in rows]
+ for _ in range(3): # capture + warm
+ GR.step_slots(rows)
+ for (s, _), n in zip(rows, n0):
+ GR.rewind(s, n)
+ torch.cuda.synchronize()
+ ms = []
+ for _ in range(3):
+ t0 = time.perf_counter()
+ for _ in range(reps):
+ _lg, am, _x, _h = GR.step_slots(rows)
+ for (s, _), n in zip(rows, n0):
+ GR.rewind(s, n)
+ torch.cuda.synchronize()
+ ms.append((time.perf_counter() - t0) / reps * 1000)
+ _lg, am, _x, _h = GR.step_slots(rows)
+ toks = am.reshape(-1).tolist()
+ for (s, _), n in zip(rows, n0):
+ GR.rewind(s, n)
+ return statistics.median(ms), toks
+
+
+def eager_ms(T):
+ rows = rows_for(T)
+ gs = GR.gs
+ tk, ps, bs = [], [], []
+ for s, toks in rows:
+ s.tokens.extend(toks)
+ tk += toks
+ ps += list(range(s.n, s.n + len(toks)))
+ bs += [s.slot * GR.cap] * len(toks)
+ Tn = len(tk)
+ gs.T, gs.Nb = Tn, 512
+ GR.hin[0, :Tn] = torch.tensor(tk)
+ GR.hin[1, :Tn] = torch.tensor(ps)
+ GR.hin[2, :Tn] = torch.tensor(bs)
+ gs.inp.copy_(GR.hin)
+ fw._gs = gs
+ try:
+ for _ in range(2):
+ fw.tm.on = True
+ fw.tm.reset()
+ GR.body()
+ torch.cuda.synchronize()
+ fw.tm.on = False
+ finally:
+ fw._gs = None
+ for s, toks in rows:
+ del s.tokens[s.n:]
+ return fw.tm.acc.get("routed experts", 0) * 1000, sum(fw.tm.acc.values()) * 1000
+
+
+res, toks_by = {}, {}
+for arm in ("stock", "gm+tiles", "stock", "gm+tiles"):
+ set_arm(arm != "stock")
+ for T in (1, 2, 4, 8):
+ ms, toks = replay_ms(T)
+ ex, tot = eager_ms(T)
+ res.setdefault(arm, {}).setdefault(T, []).append((round(ms, 2), round(ex, 1), round(tot, 1)))
+ toks_by.setdefault((arm, T), toks)
+ print("AB", arm, "T", T, "graph ms/step", round(ms, 2), "eager experts ms", round(ex, 1), "eager total", round(tot, 1), "gm_moe_calls", fw.stats.get("gm_moe_calls"), flush=True)
+agree = {T: toks_by[("stock", T)] == toks_by[("gm+tiles", T)] for T in (1, 2, 4, 8)}
+print("AB argmax agree stock vs gm+tiles", agree, flush=True)
+print("AB_DONE", json.dumps({a: {str(T): v for T, v in d.items()} for a, d in res.items()}), flush=True)
diff --git a/tools/hy4/mu_engine.py b/tools/hy4/mu_engine.py
index 794b03a..9968844 100644
--- a/tools/hy4/mu_engine.py
+++ b/tools/hy4/mu_engine.py
@@ -209,9 +209,11 @@ class Request:
class MuScheduler(threading.Thread):
"""admit -> prefill chunk (oldest prefilling) -> one decode round of all decoding sessions -> repeat"""
- def __init__(self, eng: MuEngine, chunk: int = 1024, spec: bool = True):
+ def __init__(self, eng: MuEngine, chunk: int = 1024, spec: bool = True, spec_max_b: int | None = None):
super().__init__(daemon=True)
self.eng, self.chunk, self.spec = eng, chunk, spec
+ # cost policy (box A/B 19/11): a verify row costs about what a new session's row costs (+7.7 ms), so speculation only pays while rows are shared among few sessions
+ self.spec_max_b = int(os.environ.get("HY4_MU_SPEC_MAXB", "2")) if spec_max_b is None else spec_max_b
self.cv = threading.Condition()
self.pending: deque = deque()
self.free = list(range(eng.slots))
@@ -293,7 +295,7 @@ class MuScheduler(threading.Thread):
if self.dec:
sess = [r.sess for r in self.dec]
t0 = pc()
- spec = self.spec and all(r.speculative for r in self.dec)
+ spec = self.spec and len(self.dec) <= self.spec_max_b and all(r.speculative for r in self.dec)
out = eng.spec_round(sess) if spec else eng.plain_round(sess)
t1 = pc()
self.stats["rounds"] += 1