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: MuEngine / MuScheduler (chunked prefill interleaved with batched decode rounds, per-session MTP + n-gram + Engram state), A/B bench, design note

YanissAmz8d8dbffe327a
diff --git a/doc/HY4_MULTI_USER.md b/doc/HY4_MULTI_USER.md
new file mode 100644
index 0000000..22e4a71
--- /dev/null
+++ b/doc/HY4_MULTI_USER.md
@@ -0,0 +1,29 @@
+# Hy4 multi-session decode (perf/hy4-strix-mu, on perf/hy4-strix-int e834628)
+
+## Where a session enters the step (read 19/11)
+- `tools/hy4/serve.py` takes an asyncio lock around `Hy4Engine.generate`: ONE request at a time. `generate` calls `reset()` (zeroes every static buffer) then prefill then the decode loop.
+- `step_graph.GraphDecoder.step_rows(toks)` appends T consecutive tokens of ONE sequence to static buffers and replays a HIP graph keyed (bucket, T); T <= TM = 8.
+- Per-session state in the solo engine: K rows `_ns.State.kv[layer]` [cap, 576] fp32 (every trunk layer), indexer `pool` [cap/k, d] + `vgb` [cap, 2d] (+ eager `n`, `P`, `vg`),
+ `Hy4Forward.n / tokens / _x / _eng_pf`, GraphDecoder `expect_n` + Engram staging, MTP head `kbuf` + its indexer slabs, engine `y`, `hcur`, NGram, gate `rate / since`.
+- Row-wise already (no session state): embedding, hyper connections, norms, dense Q8_0 GEMV, router, expert kernels (union of the rows' experts), output head.
+
+## Design (generic: slots, not a Hy4 fork)
+- Every per-session buffer becomes a SLAB of one flat tensor: K `[S*cap, W]`, indexer `vgb [S*cap, 2d]`, `pool [S*cap/k, d]`. A session's own view is a contiguous slice, so the solo code
+ (eager prefill, MTP head, legacy graph) runs on a session unchanged after `MultiDecoder.bind(session)`.
+- A batched step carries per row (token, position, base = slot*cap) in the static graph input (device data): graphs are keyed (bucket, rows) only, any mix of sessions reuses them.
+- Ops that touch session state have slot variants in `loader/mu_slots.py`: MLA core (`mla_attend_slots`, Triton, row t reads keys base[t] + 0..pos[t]), K row write (`index_copy_` at base+pos),
+ indexer update + scoring (`indexer_forward_slots`: the existing pool Triton kernel on FLAT positions with the rope table tiled per slab; scoring gathers each row's own pool slab).
+ The solo ops are not edited; `hy4_forward.layer` / `mla_hy4.attend` get a 3-line `slots` branch that is dead in solo mode.
+- Host side per session: Engram row ids from its own token list, n-gram proposer, gate state, MTP draft chain graph keyed (slot, bucket).
+- Prefill of a new request runs eager in chunks (`MuScheduler`: one prefill chunk, then one decode round of the running sessions); the row prefetch list and `phase()` flags are global,
+ so one prefill is in flight at a time (the others queue).
+- Row budget: TM = 8 (mla_bgemv / router_gemv MAXT, gm R <= 8). Speculative rounds split it evenly: B = 1: 8 rows, B = 2: 4 (k = 3, no n-gram rows), B = 3-4: 2 (k = 1). Going past 8 rows needs the
+ spec agent's R-row kernels (ask main).
+
+## Memory
+Slab per session ~ n_layers * cap * 2304 B (K) + 13 indexer layers * cap * 1.3 KB + MTP head: about 0.11 MB per position, 0.95 GB at cap 8704, 1.8 GB at 16K. 4 slots at 16K = 7 GB next to ~72 GiB experts.
+
+## Tests
+- `tests/test_hy4_mu_slots.py` (CPU, Triton interpreter, and MU_DEV=cuda): indexer batched rows == solo per session (allow masks, vgb rows, pooled keys; past the all-causal bound), staggered
+ sessions, scrambled neighbours, sentinel slots never written (last slab, last position), MLA core reference == per-row solo reference, other slabs / future rows never read, Triton kernel == reference.
+- GPU (`tools/hy4/mu_bench.py`): solo legacy reference vs batched streams (first divergence index), logits of a row alone vs inside a 2-row step, aggregate / per-session tok/s, memory, ttft + gaps.
diff --git a/tests/test_hy4_mu_slots.py b/tests/test_hy4_mu_slots.py
index fe1e87c..917fa9d 100644
--- a/tests/test_hy4_mu_slots.py
+++ b/tests/test_hy4_mu_slots.py
@@ -11,6 +11,8 @@ import pytest
import torch
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+DEV = os.environ.get("MU_DEV", "cpu") # MU_DEV=cuda: the same tests on the GPU (compiled Triton kernels)
+torch.set_default_device(DEV)
def _load():
@@ -28,11 +30,11 @@ CAP, S = 64, 4
def make_ix(seed=0, cap=CAP):
- g = torch.Generator().manual_seed(seed)
+ g = torch.Generator(device=DEV).manual_seed(seed)
r = lambda *s: torch.randn(*s, generator=g) * 0.5
w = {"attn_k": r(D, E), "q_b": r(H * D, RQ), "value": r(D, D), "gate": r(D, D), "k_norm": 1 + r(D) * 0.1, "proj": r(H, E), "ape": r(K, D) * 0.1,
"pool_norm": 1 + r(D) * 0.1}
- return IXF.FusedKPoolIndexer(w, "cpu", n_head=H, head_dim=D, top_k=16, kpool=K, select_tail=True, rope_dim=8, rope_base=1e4, eps=1e-5, cap=cap)
+ return IXF.FusedKPoolIndexer(w, DEV, n_head=H, head_dim=D, top_k=16, kpool=K, select_tail=True, rope_dim=8, rope_base=1e4, eps=1e-5, cap=cap)
def solo_ix(w_from, cap=CAP):
@@ -48,7 +50,7 @@ def causal(pos, Nb):
def run_case(plan, scramble=False, poolk=False, seed=1):
"""plan: list of steps, each a list of (slot, T) rows; returns (ok flags) comparing the batched slab ops with solo ops per session"""
- g = torch.Generator().manual_seed(seed)
+ g = torch.Generator(device=DEV).manual_seed(seed)
ixb = make_ix(0)
SG.indexer_static_init(ixb, CAP)
sl = MS.IxSlabs(ixb, S, CAP)
@@ -126,7 +128,7 @@ def test_indexer_sentinel_slots_outside_the_batch_keep_their_values():
sl.vgb.fill_(7.0)
sl.pool.fill_(7.0)
ar = torch.arange(CAP)
- g = torch.Generator().manual_seed(5)
+ g = torch.Generator(device=DEV).manual_seed(5)
T = 8
for n0 in range(0, CAP, T): # slot S - 1 (the last slab) and slot 1 run to their last position
pos = torch.cat([torch.arange(n0, n0 + T)] * 2)
@@ -138,14 +140,14 @@ def test_indexer_sentinel_slots_outside_the_batch_keep_their_values():
def test_indexer_poolk_triton_interpreter_matches_torch_path():
- if os.environ.get("TRITON_INTERPRET") != "1":
+ if (os.environ.get("TRITON_INTERPRET") != "1" and DEV == "cpu"):
pytest.skip("needs TRITON_INTERPRET=1")
run_case(PLAN[:12], poolk=True)
# ------------------------------------------------------------------------------------------------ attention core
def attn_inputs(seed=3):
- g = torch.Generator().manual_seed(seed)
+ g = torch.Generator(device=DEV).manual_seed(seed)
R, P = 8, 4
kflat = torch.randn(S * CAP, R + P, generator=g)
return g, R, P, kflat
@@ -186,7 +188,7 @@ def test_mla_slots_other_slabs_and_future_rows_are_not_read():
assert torch.isfinite(b).all() and torch.equal(a, b)
[email protected](os.environ.get("TRITON_INTERPRET") != "1", reason="needs TRITON_INTERPRET=1")
[email protected]((os.environ.get("TRITON_INTERPRET") != "1" and DEV == "cpu"), reason="needs TRITON_INTERPRET=1")
@pytest.mark.parametrize("window", [0, 9])
def test_mla_slots_kernel_interpreter_equals_reference(window):
g, R, P, kflat = attn_inputs()
diff --git a/tools/hy4/mu_bench.py b/tools/hy4/mu_bench.py
new file mode 100644
index 0000000..c41fc76
--- /dev/null
+++ b/tools/hy4/mu_bench.py
@@ -0,0 +1,233 @@
+"""mu_bench.py: multi-session A/B in ONE load (run inside a job wrapper: judge idle, GPU lock, capped unit).
+Phases (MU_PHASES, comma list): ref (solo legacy reference per prompt, plain + spec), plain (B = 1, 2, 4 batched plain), spec (B = 1, 2, 4 batched spec),
+pf (a long request arrives mid-decode: ttft + the running sessions' largest gap per prefill chunk size), logit (batched vs single-row step logits).
+Env: MU_NEW (tokens per request, default 96), MU_SLOTS, MU_CTX, MU_CHUNKS (e.g. 512,1024,2048), MU_PFLEN (long prompt tokens)."""
+import json
+import os
+import sys
+import time
+
+tree = os.getcwd()
+sys.path.insert(0, os.path.join(tree, "tools", "hy4"))
+import serve # noqa: E402
+
+CTX = int(os.environ.get("MU_CTX", "8192"))
+serve.apply_env(CTX)
+import torch # noqa: E402
+import serve_core as C # noqa: E402
+from mu_engine import MuEngine, MuScheduler, Request # noqa: E402
+
+GGUF = "/path/to/models/hy4-flash-gguf/Hy4-flash-Q3_K-00001-of-00002.gguf"
+NEW = int(os.environ.get("MU_NEW", "96"))
+SLOTS = int(os.environ.get("MU_SLOTS", "4"))
+PH = os.environ.get("MU_PHASES", "ref,plain").split(",")
+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."]
+mem0 = None
+e = MuEngine(tree, GGUF, ctx=CTX, k=3, slots=SLOTS)
+t0 = time.time()
+e.load(print)
+V = C.Vocab(e.meta)
+ids_of = [V.encode(V.template.render([{"role": "user", "content": p}], None, True, reasoning_effort="no_think")) for p in PROMPTS]
+free, tot = torch.cuda.mem_get_info()
+print(f"MEM after load: free {free / 2**30:.1f} GiB of {tot / 2**30:.1f}; allocated {torch.cuda.memory_allocated() / 2**30:.2f} GiB; slabs {SLOTS} x cap {e.GR.cap}", flush=True)
+RES = {}
+
+
+def solo_ref(idx, spec):
+ """legacy solo path of the shipped engine (GraphDecoder + MTPGraph) on slot 0: the reference stream and speed"""
+ SG, MH = e.SG, e.MH
+ GRm, MGm = e.GR, e.MG
+ if not hasattr(e, "GR1"):
+ e.GR1 = SG.GraphDecoder(e.M)
+ e.GR1.prepare()
+ e.MG1 = MH.MTPGraph(e.MT, e.k)
+ e.GR, e.MG = e.GR1, e.MG1
+ try:
+ s0 = GRm.new_session(0)
+ GRm.bind(s0)
+ out = []
+ st = e.generate(ids_of[idx], NEW, lambda t: out.extend(t) or False, speculative=spec)
+ finally:
+ e.GR, e.MG = GRm, MGm
+ return out, st
+
+
+def cmp(a, b):
+ n = min(len(a), len(b))
+ for i in range(n):
+ if a[i] != b[i]:
+ return i
+ return n if len(a) == len(b) else n
+
+
+def run_batch(B, spec, chunk=1024):
+ sch = MuScheduler(e, chunk=chunk, spec=spec)
+ sch.start()
+ reqs = [Request(ids_of[i % 4], NEW, speculative=spec) for i in range(B)]
+ for r in reqs:
+ sch.submit(r)
+ for r in reqs:
+ r.done.wait(600)
+ sch.shutdown()
+ sch.join(10)
+ errs = [r.error for r in reqs if r.error]
+ t_lo = max(r.t_first for r in reqs)
+ t_hi = min(r.t_done for r in reqs)
+ toks = sum(n for r in reqs for (t, n) in r.times if t_lo < t <= t_hi)
+ agg = toks / max(t_hi - t_lo, 1e-9)
+ per = []
+ for r in reqs:
+ tk = sum(n for (t, n) in r.times if t_lo < t <= t_hi)
+ per.append(round(tk / max(t_hi - t_lo, 1e-9), 2))
+ return reqs, dict(B=B, spec=spec, agg_tok_s=round(agg, 2), per_session=per, window_s=round(t_hi - t_lo, 2), errors=errs,
+ rounds=sch.stats["rounds"], mean_rows=round(sch.stats["round_rows"] / max(sch.stats["rounds"], 1), 2),
+ ttft=[round(r.stats.get("ttft", -1), 2) for r in reqs])
+
+
+if "ref" in PH:
+ REF = {}
+ for spec in (False, True):
+ for i in range(4):
+ if spec is False and i == 0:
+ solo_ref(0, False) # warm-up (graph captures)
+ if spec is True and i == 0:
+ solo_ref(0, True)
+ out, st = solo_ref(i, spec)
+ REF[(i, spec)] = out
+ tps = st["decode_tokens"] / st["decode_s"]
+ print("REF", "spec" if spec else "plain", i, "tok/s", round(tps, 2), "tau", st.get("tau"), "prompt", st["prompt_tokens"], flush=True)
+ RES.setdefault("ref", {})[f"{i}_{'spec' if spec else 'plain'}"] = dict(tok_s=round(tps, 2), tau=st.get("tau"))
+ json.dump({f"{k[0]}_{k[1]}": v for k, v in REF.items()}, open(os.environ.get("MU_REFOUT", "/tmp/mu_ref.json"), "w"))
+else:
+ REF = {}
+ p = os.environ.get("MU_REFOUT", "/tmp/mu_ref.json")
+ if os.path.exists(p):
+ REF = {(int(k.split("_")[0]), k.split("_")[1] == "True"): v for k, v in json.load(open(p)).items()}
+
+for mode in ("plain", "spec"):
+ if mode not in PH:
+ continue
+ spec = mode == "spec"
+ # warm-up: capture every (bucket, rows) graph the arms need
+ for B in (1, 2, 4):
+ run_batch(B, spec)
+ for B in (1, 2, 4):
+ reqs, r = run_batch(B, spec)
+ eq = []
+ for i, q in enumerate(reqs):
+ ref = REF.get((i % 4, spec))
+ eq.append(cmp(q.out, ref) if ref is not None else None)
+ r["equal_prefix"] = eq
+ r["tokens"] = [len(q.out) for q in reqs]
+ print("MU", mode, json.dumps(r), flush=True)
+ RES.setdefault(mode, []).append(r)
+ free, tot = torch.cuda.mem_get_info()
+ print(f"MEM after {mode}: free {free / 2**30:.1f} GiB; max allocated {torch.cuda.max_memory_allocated() / 2**30:.2f} GiB", flush=True)
+
+if "logit" in PH:
+ GR = e.GR
+ e.phase("prefill")
+ sess = []
+ for i in (0, 1):
+ s = GR.new_session(i)
+ e.prefill_begin(s, ids_of[i], 1024)
+ while not e.prefill_step(s):
+ pass
+ sess.append(s)
+ n0 = [s.n for s in sess]
+ ya, yb = sess[0].y, sess[1].y
+ lg1, am1, _, _ = GR.step_slots([(sess[0], [ya])])
+ a1 = lg1.clone()
+ GR.rewind(sess[0], n0[0])
+ lg2, am2, _, _ = GR.step_slots([(sess[0], [ya]), (sess[1], [yb])])
+ a2 = lg2[0].clone()
+ GR.rewind(sess[0], n0[0])
+ GR.rewind(sess[1], n0[1])
+ print("LOGIT row0 single vs batched: max abs diff", float((a1 - a2).abs().max()), "argmax equal", int(a1.argmax()) == int(a2.argmax()), "absmax", float(a1.abs().max()), flush=True)
+
+if "prof" in PH:
+ # eager per-class timers (synchronised): rows of 1 / 2 / 4 / 8 sessions in one step, the classes that scale with the row count are the batching cost
+ GR, fw = e.GR, e.M
+ e.phase("prefill")
+ sess = []
+ for i in range(4):
+ s_ = GR.new_session(i)
+ e.prefill_begin(s_, ids_of[i], 1024)
+ while not e.prefill_step(s_):
+ pass
+ sess.append(s_)
+ e.phase("decode")
+ gs = GR.gs
+ for T in (1, 2, 4, 8):
+ rows = [(sess[r % 4], [sess[r % 4].y]) for r in range(T)] if T <= 4 else [(sess[r // 2], [sess[r // 2].y, sess[r // 2].y]) for r in range(T)][:4]
+ if T == 8:
+ rows = [(sess[r], [sess[r].y, sess[r].y]) for r in range(4)]
+ 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 rep in range(3):
+ fw.tm.on = True
+ fw.tm.reset()
+ torch.cuda.synchronize()
+ t0 = time.perf_counter()
+ GR.body()
+ torch.cuda.synchronize()
+ dt = time.perf_counter() - t0
+ fw.tm.on = False
+ finally:
+ fw._gs = None
+ for s_, toks in rows:
+ del s_.tokens[s_.n:]
+ print("PROF T", Tn, "eager total ms", round(dt * 1000, 1), {k: round(v * 1000, 1) for k, v in sorted(fw.tm.acc.items(), key=lambda kv: -kv[1])}, flush=True)
+
+if "pf" in PH:
+ pfl = int(os.environ.get("MU_PFLEN", "2048"))
+ import json as _j
+ wiki = _j.load(open("/path/to/wiki_ids.json"))
+ for chunk in [int(x) for x in os.environ.get("MU_CHUNKS", "512,1024,2048").split(",")]:
+ for spec in (False,):
+ sch = MuScheduler(e, chunk=chunk, spec=spec)
+ sch.start()
+ runners = [Request(ids_of[i], 200, speculative=spec) for i in range(3)]
+ for r in runners:
+ sch.submit(r)
+ while not all(r.t_first for r in runners):
+ time.sleep(0.05)
+ time.sleep(1.5)
+ late = Request(wiki[:pfl], 24, speculative=spec)
+ ts = time.perf_counter()
+ sch.submit(late)
+ late.done.wait(300)
+ te = time.perf_counter()
+ gaps = []
+ for r in runners:
+ tt = [t for (t, n) in r.times if ts - 0.5 <= t <= te + 0.5]
+ gaps += [b - a for a, b in zip(tt, tt[1:])]
+ base = []
+ for r in runners:
+ tt = [t for (t, n) in r.times if ts - 3 <= t <= ts - 0.2]
+ base += [b - a for a, b in zip(tt, tt[1:])]
+ for r in runners:
+ r.done.wait(300)
+ sch.shutdown()
+ sch.join(10)
+ res = dict(chunk=chunk, pf_tokens=pfl, late_ttft=round(late.stats.get("ttft", -1), 2), max_gap_during_prefill=round(max(gaps), 3) if gaps else None,
+ median_gap_before=round(sorted(base)[len(base) // 2], 4) if base else None, pf_s=round(sch.stats["pf_s"], 2), late_err=late.error)
+ print("PF", json.dumps(res), flush=True)
+ RES.setdefault("pf", []).append(res)
+
+print("MU_DONE", json.dumps(RES), flush=True)
diff --git a/tools/hy4/mu_engine.py b/tools/hy4/mu_engine.py
new file mode 100644
index 0000000..c31d8dd
--- /dev/null
+++ b/tools/hy4/mu_engine.py
@@ -0,0 +1,282 @@
+"""Multi-session Hy4 engine + scheduler (perf/hy4-strix-mu): 2-4 sessions decoded in ONE batched trunk step, new requests prefilled in chunks between decode rounds.
+
+ MuEngine Hy4Engine with a MultiDecoder (loader/step_mu.py): per-session K / indexer slabs, per-session MTP head state, per-session n-gram + Engram history.
+ MuScheduler one thread: admit requests into free slots, one prefill chunk of the oldest prefilling request, then one decode round of every decoding session
+ (plain: one row each; speculative: the MTP drafts + n-gram rows of each session share ONE verify replay, TM = 8 rows split evenly).
+Greedy: a session's stream equals plain greedy decoding of the trunk (the verifier keeps only the rows the trunk agrees with)."""
+from __future__ import annotations
+
+import os
+import threading
+import time
+from collections import deque
+
+from engine import Hy4Engine, PRIME_ROWS
+
+
+class MuEngine(Hy4Engine):
+ def __init__(self, *a, slots: int = 4, **kw):
+ super().__init__(*a, **kw)
+ self.slots = slots
+
+ def _decoder(self, M):
+ from exllamav3.loader import step_mu
+ self.SM = step_mu
+ return step_mu.MultiDecoder(M, self.slots)
+
+ def _mtp_graph(self):
+ self.GR.attach_mtp(self.MT)
+ return self.SM.MTPGraphMU(self.MT, self.k)
+
+ # ------------------------------------------------------------------------------------------ sessions
+ def open(self, slot):
+ return self.GR.new_session(slot)
+
+ def prefill_begin(self, s, ids, chunk):
+ s.ids, s.pf_pos, s.H, s.chunk = list(ids), 0, [], chunk
+
+ def prefill_step(self, s):
+ """one chunk of the prompt of s (eager prefill set). -> True when the prompt is done: s.y = first token, s.hcur, draft cache primed"""
+ torch, M, GR = self.torch, self.M, self.GR
+ a = s.pf_pos
+ b = min(len(s.ids), a + s.chunk)
+ self.phase("prefill")
+ GR.bind(s)
+ if a == 0:
+ M.prefetch_engram(s.ids, s.chunk) # the row prefetch list is global: one prefill is in flight at a time, it starts with its first chunk
+ lg = M.step(s.ids[a:b])
+ s.H.append(M.head_state(M._x))
+ M._x = None
+ torch.cuda.synchronize()
+ GR.save(s)
+ s.pf_pos = b
+ if b < len(s.ids):
+ return False
+ H = torch.cat(s.H) if len(s.H) > 1 else s.H[0]
+ s.H = []
+ s.y = int(torch.argmax(lg))
+ s.hcur = H[-1:].clone()
+ self._prime_draft(s.ids, H) # MT is bound to s
+ torch.cuda.synchronize()
+ GR.start_graph_state(s)
+ self.phase("decode")
+ return True
+
+ # ------------------------------------------------------------------------------------------ decode rounds
+ def plain_round(self, sess):
+ """one row per session -> {session: [new token]}"""
+ rows = [(s, [s.y]) for s in sess]
+ _lg, am, _x, hv = self.GR.step_slots(rows)
+ amh = am.reshape(-1).tolist()
+ out = {}
+ for r, s in enumerate(sess):
+ s.y = amh[r]
+ out[s] = [s.y]
+ return out
+
+ def _ng(self, s):
+ if s.ng is None and self.ngram_ext > 0:
+ from ngram import NGram
+ s.ng = NGram(self.ngram_min, self.ngram_ext)
+ s.ng.reset(list(s.ids) + [s.y])
+ s.extra.update(rate=0.7, since=0)
+ return s.ng
+
+ def spec_round(self, sess):
+ """speculative round of every session in sess: drafts per session (own head state), ONE verify replay over all rows. -> {session: [new tokens]}"""
+ torch, GR, MG, MT, k = self.torch, self.GR, self.MG, self.MT, self.k
+ TM = self.SG.TM
+ Rs = max(1, TM // len(sess)) # verify rows per session
+ ks = min(k, Rs - 1)
+ plan = []
+ for s in sess:
+ if Rs == 1:
+ plan.append((s, [s.y], False, 0, None))
+ continue
+ j = s.n - 1
+ ng = self._ng(s)
+ skip, cl = False, []
+ if ng is not None and self.ngram_long > 0:
+ cl, ml = ng.propose([], Rs - 1)
+ skip = bool(cl) and ml >= self.ngram_long
+ if skip:
+ plan.append((s, [s.y] + cl, True, j, s.hcur.clone()))
+ continue
+ GR.bind(s)
+ MG.slot = s.slot
+ plan.append((s, None, False, j, MG.run(s.y, s.hcur, j))) # drafts launched; read below
+ rows, meta = [], []
+ for s, toks, skip, j, h in plan:
+ if toks is None:
+ d = h.tolist()[:ks]
+ ext = []
+ ng = s.ng
+ if ng is not None:
+ lim = min(self.ngram_ext, Rs - 1 - ks)
+ if self.ngram_gate:
+ st = s.extra
+ st["since"] += 1
+ rate, since = st["rate"], st["since"]
+ lim = lim if rate >= 0.6 else (2 if rate >= 0.4 else (lim if since >= 8 else 0))
+ ext, ml = ng.propose(d, lim) if lim > 0 else ([], 0)
+ if self.ngram_adapt and ext:
+ ext = ext[:max(1, (ml - self.ngram_min + 1) * 2)]
+ toks = [s.y] + d + ext
+ meta.append((s, toks, False, j, len(ext), ks))
+ else:
+ meta.append((s, toks, skip, j, 0, ks))
+ rows.append((s, toks))
+ starts = {s: s.n for s, _ in rows}
+ _lg, amv, _x, hv = GR.step_slots(rows)
+ amh_all = amv.reshape(-1).tolist()
+ out, o = {}, 0
+ for s, toks, skip, j, next_, kk in meta:
+ T = len(toks)
+ amh = amh_all[o:o + T]
+ hs = hv[o:o + T]
+ o += T
+ acc, nd = 0, T - 1
+ while acc < nd and toks[acc + 1] == amh[acc]:
+ acc += 1
+ st = s.extra
+ if next_ and not skip:
+ st["rate"] = 0.75 * st["rate"] + 0.25 * (max(0, acc - kk) / next_)
+ st["since"] = 0
+ new = toks[1:acc + 1] + [amh[acc]]
+ GR.rewind(s, starts[s] + 1 + acc)
+ if skip: # the chain wrote no head rows: pairs (token m, state before it) for head positions j .. j + acc
+ GR.bind(s)
+ N = ((j + acc + 1 + 3) // 4) * 4
+ sts = torch.cat([skip_h(plan, s), hs[:acc]]) if acc > 0 else skip_h(plan, s)
+ MT.step(torch.tensor(toks[:acc + 1], dtype=torch.long, device=self.dev), sts, MT.ar[j:j + acc + 1], N)
+ elif self.ngram_fill and acc >= kk and kk > 0:
+ GR.bind(s)
+ N = ((j + acc + 1 + 3) // 4) * 4
+ MT.step(torch.tensor(toks[kk:acc + 1], dtype=torch.long, device=self.dev), hs[kk - 1:acc], MT.ar[j + kk:j + acc + 1], N)
+ if s.ng is not None:
+ s.ng.add(new)
+ s.y, s.hcur = amh[acc], hs[acc:acc + 1].clone()
+ s.extra["hist"] = s.extra.get("hist", 0) + 1
+ s.extra["acc_sum"] = s.extra.get("acc_sum", 0) + acc
+ out[s] = new
+ return out
+
+
+def skip_h(plan, s):
+ for p in plan:
+ if p[0] is s:
+ return p[4]
+ raise KeyError
+
+
+class Request:
+ def __init__(self, ids, max_new, speculative=True, on_tokens=None):
+ self.ids, self.max_new, self.speculative = list(ids), max_new, speculative
+ self.on_tokens = on_tokens
+ self.out: list[int] = []
+ self.times: list[tuple[float, int]] = [] # (time, tokens emitted by this event)
+ self.t_submit = time.perf_counter()
+ self.t_first = self.t_done = None
+ self.done = threading.Event()
+ self.error = None
+ self.sess = None
+ self.stats: dict = {}
+
+
+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):
+ super().__init__(daemon=True)
+ self.eng, self.chunk, self.spec = eng, chunk, spec
+ self.cv = threading.Condition()
+ self.pending: deque = deque()
+ self.free = list(range(eng.slots))
+ self.pf: deque = deque()
+ self.dec: list = []
+ self.stop_flag = False
+ self.stats = {"rounds": 0, "round_rows": 0, "pf_chunks": 0, "pf_s": 0.0, "dec_s": 0.0}
+ self.trace: list = [] # (t0, t1, kind, n) per scheduler action
+
+ def submit(self, req: Request):
+ with self.cv:
+ self.pending.append(req)
+ self.cv.notify()
+ return req
+
+ def shutdown(self):
+ with self.cv:
+ self.stop_flag = True
+ self.cv.notify()
+
+ def _emit(self, req, new, now):
+ room = req.max_new - len(req.out)
+ new = new[:room]
+ req.out += new
+ req.times.append((now, len(new)))
+ stop = bool(req.on_tokens(new)) if req.on_tokens else False
+ return stop or len(req.out) >= req.max_new
+
+ def _finish(self, req):
+ req.t_done = time.perf_counter()
+ self.free.append(req.sess.slot)
+ if req in self.dec:
+ self.dec.remove(req)
+ req.done.set()
+
+ def run(self):
+ eng, pc = self.eng, time.perf_counter
+ try:
+ eng.phase("decode")
+ while True:
+ with self.cv:
+ while not (self.pending or self.pf or self.dec) and not self.stop_flag:
+ self.cv.wait()
+ if self.stop_flag:
+ return
+ while self.pending and self.free:
+ req = self.pending.popleft()
+ req.sess = eng.open(self.free.pop(0))
+ req.stats["admit"] = pc()
+ if len(req.ids) + req.max_new + eng.k + 2 > eng.ctx:
+ req.error = "context"
+ self._finish(req)
+ continue
+ eng.prefill_begin(req.sess, req.ids, self.chunk)
+ req.sess.req = req
+ self.pf.append(req)
+ if self.pf:
+ req = self.pf[0]
+ t0 = pc()
+ done = eng.prefill_step(req.sess)
+ t1 = pc()
+ self.stats["pf_chunks"] += 1
+ self.stats["pf_s"] += t1 - t0
+ self.trace.append((t0, t1, "pf", req.sess.pf_pos))
+ if done:
+ self.pf.popleft()
+ req.t_first = t1
+ req.stats["ttft"] = t1 - req.t_submit
+ if self._emit(req, [req.sess.y], t1):
+ self._finish(req)
+ else:
+ self.dec.append(req)
+ 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)
+ out = eng.spec_round(sess) if spec else eng.plain_round(sess)
+ t1 = pc()
+ self.stats["rounds"] += 1
+ self.stats["round_rows"] += len(sess)
+ self.stats["dec_s"] += t1 - t0
+ self.trace.append((t0, t1, "dec", len(sess)))
+ for r in list(self.dec):
+ if self._emit(r, out[r.sess], t1):
+ self._finish(r)
+ except Exception as ex: # noqa: BLE001
+ import traceback
+ traceback.print_exc()
+ for r in list(self.dec) + list(self.pf) + list(self.pending):
+ r.error = repr(ex)
+ r.done.set()
diff --git a/tools/hy4/mu_gpu_tests.py b/tools/hy4/mu_gpu_tests.py
new file mode 100644
index 0000000..bc49a93
--- /dev/null
+++ b/tools/hy4/mu_gpu_tests.py
@@ -0,0 +1,6 @@
+"""run tests/test_hy4_mu_slots.py on the GPU (compiled Triton kernels): small, no model. pytest comes from the system site-packages through a symlink dir."""
+import os, sys
+sys.path.insert(0, "/tmp/hy4mu_pt")
+os.environ["MU_DEV"] = "cuda"
+import pytest
+sys.exit(pytest.main(["-x", "-q", os.path.join(os.getcwd(), "tests", "test_hy4_mu_slots.py")]))