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 server: serve.py --slots N (scheduler path, cancel, stats), scheduler tests with a fake engine, served test driver, teacher-forced NLL phase

YanissAmz302f88f488f2
diff --git a/tests/test_hy4_mu_sched.py b/tests/test_hy4_mu_sched.py
new file mode 100644
index 0000000..f18ce71
--- /dev/null
+++ b/tests/test_hy4_mu_sched.py
@@ -0,0 +1,109 @@
+"""MuScheduler logic with a fake engine (no torch, no GPU): admission into free slots, queueing past the slot count, slot reuse, one prefill chunk between decode rounds,
+cancel, max_new, context error, error propagation."""
+import os
+import sys
+import threading
+import time
+
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tools", "hy4"))
+import mu_engine as ME # noqa: E402
+
+
+class Sess:
+ def __init__(self, slot):
+ self.slot, self.pf_pos, self.y, self.n = slot, 0, 100 + slot, 0
+
+
+class FakeEng:
+ k, ctx = 3, 4096
+
+ def __init__(self, slots=2, boom=False):
+ self.slots, self.log, self.boom = slots, [], boom
+
+ def phase(self, _):
+ pass
+
+ def open(self, slot):
+ self.log.append(("open", slot))
+ return Sess(slot)
+
+ def prefill_begin(self, s, ids, chunk):
+ s.ids, s.chunk = ids, chunk
+
+ def prefill_step(self, s):
+ s.pf_pos = min(len(s.ids), s.pf_pos + s.chunk)
+ self.log.append(("pf", s.slot, s.pf_pos))
+ time.sleep(0.002)
+ return s.pf_pos >= len(s.ids)
+
+ def plain_round(self, sess):
+ if self.boom:
+ raise RuntimeError("boom")
+ self.log.append(("dec", tuple(s.slot for s in sess)))
+ time.sleep(0.002)
+ out = {}
+ for s in sess:
+ s.y += 1
+ out[s] = [s.y]
+ return out
+
+ spec_round = plain_round
+
+
+def run(reqs, eng, chunk=4, spec=False):
+ sch = ME.MuScheduler(eng, chunk=chunk, spec=spec)
+ sch.start()
+ for r in reqs:
+ sch.submit(r)
+ for r in reqs:
+ assert r.done.wait(10), "request did not finish"
+ sch.shutdown()
+ sch.join(5)
+ return sch
+
+
+def test_queue_past_slots_reuse_and_max_new():
+ eng = FakeEng(slots=2)
+ reqs = [ME.Request(list(range(10)), 5) for _ in range(5)]
+ run(reqs, eng)
+ assert all(len(r.out) == 5 and not r.error for r in reqs)
+ opens = [x[1] for x in eng.log if x[0] == "open"]
+ assert len(opens) == 5 and set(opens) == {0, 1}
+ assert max(len(x[1]) for x in eng.log if x[0] == "dec") == 2 # never more rows than slots
+
+
+def test_prefill_chunk_is_interleaved_with_decode_rounds():
+ eng = FakeEng(slots=2)
+ a = ME.Request(list(range(4)), 40)
+ b = ME.Request(list(range(40)), 3) # 10 chunks of 4
+ sch = ME.MuScheduler(eng, chunk=4)
+ sch.start()
+ sch.submit(a)
+ while not a.out:
+ time.sleep(0.001)
+ sch.submit(b)
+ b.done.wait(10)
+ a.done.wait(10)
+ sch.shutdown()
+ seq = [x[0] for x in eng.log if x[0] in ("pf", "dec")]
+ i0 = seq.index("pf", 1) # b's chunks (a's single chunk comes first)
+ run_pf = 0
+ longest = 0
+ for x in seq[i0:i0 + 25]:
+ run_pf = run_pf + 1 if x == "pf" else 0
+ longest = max(longest, run_pf)
+ assert longest <= 1, "two prefill chunks ran back to back while a session was decoding"
+
+
+def test_cancel_context_and_error():
+ eng = FakeEng(slots=2)
+ r = ME.Request(list(range(4)), 3000)
+ r.on_tokens = lambda new: (len(r.out) > 20) and r.cancel.set()
+ big = ME.Request(list(range(5000)), 4)
+ done = []
+ r.on_done = lambda: done.append(1)
+ run([r, big], eng)
+ assert 20 < len(r.out) < 40 and done == [1] and big.error == "context"
+ bad = ME.Request(list(range(4)), 5)
+ run([bad], FakeEng(boom=True))
+ assert bad.error and "boom" in bad.error
diff --git a/tools/hy4/mu_bench.py b/tools/hy4/mu_bench.py
index c41fc76..08903c6 100644
--- a/tools/hy4/mu_bench.py
+++ b/tools/hy4/mu_bench.py
@@ -194,6 +194,87 @@ if "prof" in PH:
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 "nll" in PH:
+ # teacher-forced NLL per session: batched slot step (B = 4 rows, B = 1 row) vs the legacy solo graph (R = 1, R = 4 rows) and the 1e-6 embedding-noise null arms of the solo path.
+ # Same text per session in every arm; per-token paired differences give the se. A batched arm inside the null band = the batched step is the same maths up to noise.
+ import numpy as np
+ wiki = json.load(open("/path/to/wiki_ids.json"))
+ PRE, NN = int(os.environ.get("MU_PRE", "200")), int(os.environ.get("MU_NN", "240"))
+ segs = [wiki[1000 * i:1000 * i + PRE + NN + 8] for i in range(4)]
+ 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)
+
+ def lp_of(lg, tgt):
+ lp = torch.log_softmax(lg.reshape(len(tgt), -1).float(), -1)
+ return (-lp[torch.arange(len(tgt), device=e.dev), torch.tensor(tgt, device=e.dev)]).tolist()
+
+ def solo_nll(i, R, seed=None):
+ seg = segs[i]
+ e.GR, e.MG = e.GR1, e.MG1
+ try:
+ SG.PERT = None if seed is None else (torch.randn(e.GR1.cap, e.M.D, generator=torch.Generator().manual_seed(seed)) * 1e-6).to(e.dev)
+ e.GR1.clear()
+ s0 = GRm.new_session(0)
+ GRm.bind(s0)
+ e._t0 = time.perf_counter()
+ e.reset()
+ e.prefill(seg[:PRE])
+ e.phase("decode")
+ out, j = [], 0
+ while j < NN:
+ r = min(R, NN - j)
+ lg, _am, _x, _h = e.GR1.step_rows(seg[PRE + j:PRE + j + r])
+ out.extend(lp_of(lg, seg[PRE + j + 1:PRE + j + r + 1]))
+ j += r
+ finally:
+ SG.PERT = None
+ e.GR1.clear()
+ e.GR, e.MG = GRm, MGm
+ return np.array(out)
+
+ def slot_nll(B):
+ sess = []
+ e.phase("prefill")
+ for i in range(B):
+ s_ = GRm.new_session(i)
+ e.prefill_begin(s_, segs[i][:PRE], 1024)
+ while not e.prefill_step(s_):
+ pass
+ sess.append(s_)
+ e.phase("decode")
+ outs = [[] for _ in range(B)]
+ for j in range(NN):
+ rows = [(sess[i], [segs[i][PRE + j]]) for i in range(B)]
+ lg, _am, _x, _h = GRm.step_slots(rows)
+ lg = lg.reshape(B, -1)
+ for i in range(B):
+ outs[i].extend(lp_of(lg[i], [segs[i][PRE + j + 1]]))
+ return [np.array(o) for o in outs]
+
+ arms = {}
+ for i in range(4):
+ for name, R, sd in (("R1", 1, None), ("R1_n1", 1, 1), ("R1_n2", 1, 2), ("R4", 4, None)):
+ arms[(name, i)] = solo_nll(i, R, sd)
+ print("NLL solo session", i, {n: round(float(arms[(n, i)].mean()), 4) for n in ("R1", "R1_n1", "R1_n2", "R4")}, flush=True)
+ for B in (4, 1):
+ o = slot_nll(B)
+ for i in range(B):
+ arms[(f"slotB{B}", i)] = o[i]
+ for i in range(4):
+ base = arms[("R1", i)]
+ null = [arms[(n, i)].mean() for n in ("R1", "R1_n1", "R1_n2", "R4")]
+ row = {"null_band_spread": round(float(max(null) - min(null)), 4), "R1_mean": round(float(base.mean()), 4)}
+ for n in ("R1_n1", "R1_n2", "R4", "slotB4", "slotB1"):
+ if (n, i) in arms:
+ d = arms[(n, i)] - base
+ row[n] = [round(float(d.mean()), 4), round(float(d.std(ddof=1) / np.sqrt(len(d))), 4), round(float(np.abs(d).max()), 3)]
+ print("NLLD session", i, json.dumps(row), flush=True)
+ RES.setdefault("nll", []).append(row)
+
if "pf" in PH:
pfl = int(os.environ.get("MU_PFLEN", "2048"))
import json as _j
diff --git a/tools/hy4/mu_engine.py b/tools/hy4/mu_engine.py
index c31d8dd..85f78da 100644
--- a/tools/hy4/mu_engine.py
+++ b/tools/hy4/mu_engine.py
@@ -178,9 +178,21 @@ class Request:
self.t_submit = time.perf_counter()
self.t_first = self.t_done = None
self.done = threading.Event()
+ self.cancel = threading.Event() # set by the server when the client went away
+ self.on_done = None # called once from the scheduler thread when the request ends (any reason)
self.error = None
self.sess = None
self.stats: dict = {}
+ self.rounds = 0
+
+ def engine_stats(self, k):
+ """the stats dict the single-session engine returns from generate() (what serve.py prints / reports as timings)"""
+ t_first = self.t_first or self.t_done
+ dec = max((self.t_done or t_first) - t_first, 1e-9)
+ n = max(len(self.out) - 1, 0)
+ return {"prompt_tokens": len(self.ids), "speculative": self.speculative, "k": k, "prefill_s": t_first - self.t_submit, "ttft_s": t_first - self.t_submit,
+ "decode_s": dec, "decode_tokens": n, "rounds": self.rounds, "accept_hist": [], "tau": (n / self.rounds) if self.rounds else None,
+ "prefill_trunk_s": self.stats.get("pf_s", 0.0), "prime_s": 0.0, "generated": len(self.out), "cancelled": self.cancel.is_set()}
class MuScheduler(threading.Thread):
@@ -215,14 +227,17 @@ class MuScheduler(threading.Thread):
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
+ return stop or len(req.out) >= req.max_new or req.cancel.is_set()
def _finish(self, req):
req.t_done = time.perf_counter()
- self.free.append(req.sess.slot)
+ if req.sess is not None:
+ self.free.append(req.sess.slot)
if req in self.dec:
self.dec.remove(req)
req.done.set()
+ if req.on_done is not None:
+ req.on_done()
def run(self):
eng, pc = self.eng, time.perf_counter
@@ -238,18 +253,21 @@ class MuScheduler(threading.Thread):
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"
+ if req.cancel.is_set() or len(req.ids) + req.max_new + eng.k + 2 > eng.ctx:
+ req.error = None if req.cancel.is_set() else "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 and self.pf[0].cancel.is_set():
+ self._finish(self.pf.popleft())
if self.pf:
req = self.pf[0]
t0 = pc()
done = eng.prefill_step(req.sess)
t1 = pc()
+ req.stats["pf_s"] = req.stats.get("pf_s", 0.0) + t1 - t0
self.stats["pf_chunks"] += 1
self.stats["pf_s"] += t1 - t0
self.trace.append((t0, t1, "pf", req.sess.pf_pos))
@@ -272,6 +290,7 @@ class MuScheduler(threading.Thread):
self.stats["dec_s"] += t1 - t0
self.trace.append((t0, t1, "dec", len(sess)))
for r in list(self.dec):
+ r.rounds += 1
if self._emit(r, out[r.sess], t1):
self._finish(r)
except Exception as ex: # noqa: BLE001
@@ -280,3 +299,16 @@ class MuScheduler(threading.Thread):
for r in list(self.dec) + list(self.pf) + list(self.pending):
r.error = repr(ex)
r.done.set()
+ if r.on_done is not None:
+ r.on_done()
+
+
+def warmup(sch: MuScheduler, n: int, new: int = 24):
+ """compile / capture what a served mix needs at the first bucket: B = 1 .. slots concurrent requests of n prompt tokens (graphs per (bucket, rows), MTP chains per slot)"""
+ eng = sch.eng
+ ids = [(i * 7919 + 13) % 50000 for i in range(n)]
+ for B in range(1, eng.slots + 1):
+ reqs = [sch.submit(Request(ids[i:] + ids[:i], new)) for i in range(B)]
+ for r in reqs:
+ r.done.wait(900)
+ print(f"mu warm-up: {n} prompt tokens, 1..{eng.slots} sessions", flush=True)
diff --git a/tools/hy4/mu_served_test.py b/tools/hy4/mu_served_test.py
new file mode 100644
index 0000000..85880d9
--- /dev/null
+++ b/tools/hy4/mu_served_test.py
@@ -0,0 +1,156 @@
+"""mu_served_test.py: SERVED numbers of the multi-session server (serve.py --slots N) over HTTP, run inside a job wrapper.
+Starts the server on a free port, waits for /health, then: 1 / 2 / 4 concurrent streaming chat requests (aggregate + per-session tok/s, ttft), and a long request
+arriving while 3 sessions decode (its ttft, the running sessions' largest gap between stream chunks during its prefill, per sched chunk size = one server start each).
+Env: MU_PORT (8341), MU_SLOTS (4), MU_CTX (8192), MU_NEW (96), MU_CHUNK (1024), MU_PFLEN (2048), MU_SPEC (1 = speculative requests)."""
+import http.client
+import json
+import os
+import subprocess
+import sys
+import threading
+import time
+
+tree = os.getcwd()
+PORT = int(os.environ.get("MU_PORT", "8341"))
+SLOTS = int(os.environ.get("MU_SLOTS", "4"))
+CTX = int(os.environ.get("MU_CTX", "8192"))
+NEW = int(os.environ.get("MU_NEW", "96"))
+CHUNK = int(os.environ.get("MU_CHUNK", "1024"))
+PFLEN = int(os.environ.get("MU_PFLEN", "2048"))
+SPEC = os.environ.get("MU_SPEC", "1") == "1"
+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."]
+
+
+def post(path, body, res):
+ t0 = time.perf_counter()
+ res.update(t0=t0, chunks=[], usage=None)
+ c = http.client.HTTPConnection("127.0.0.1", PORT, timeout=600)
+ c.request("POST", path, json.dumps(body), {"Content-Type": "application/json"})
+ r = c.getresponse()
+ res["status"] = r.status
+ buf = b""
+ while True:
+ part = r.read1(65536)
+ if not part:
+ break
+ buf += part
+ while b"\n\n" in buf:
+ ev, buf = buf.split(b"\n\n", 1)
+ if not ev.startswith(b"data: ") or ev.endswith(b"[DONE]"):
+ continue
+ j = json.loads(ev[6:])
+ if j.get("usage"):
+ res["usage"] = j["usage"]
+ ch = j.get("choices") or []
+ if ch and (ch[0].get("delta", {}).get("content") or ch[0].get("delta", {}).get("reasoning_content") or ch[0].get("text")):
+ res["chunks"].append(time.perf_counter())
+ res["t1"] = time.perf_counter()
+ c.close()
+
+
+def chat(i):
+ return "/v1/chat/completions", {"messages": [{"role": "user", "content": PROMPTS[i % 4]}], "max_tokens": NEW, "stream": True, "stream_options": {"include_usage": True},
+ "chat_template_kwargs": {"reasoning_effort": "no_think"}, "speculative": SPEC}
+
+
+def launch(bodies, delay=0.0):
+ rs = [dict() for _ in bodies]
+ th = [threading.Thread(target=post, args=(p, b, r)) for (p, b), r in zip(bodies, rs)]
+ for t in th:
+ t.start()
+ time.sleep(delay)
+ return rs, th
+
+
+def summarise(rs):
+ t_lo = max(r["chunks"][0] for r in rs)
+ t_hi = min(r["t1"] for r in rs)
+ n = [r["usage"]["completion_tokens"] for r in rs]
+ per = []
+ for r in rs: # tokens are streamed per round: count chunks in the window, scaled by tokens per chunk
+ tot = r["usage"]["completion_tokens"]
+ k = len(r["chunks"])
+ inwin = sum(1 for t in r["chunks"] if t_lo < t <= t_hi)
+ per.append(round(inwin * (tot / max(k, 1)) / max(t_hi - t_lo, 1e-9), 2))
+ return dict(B=len(rs), agg_tok_s=round(sum(per), 2), per_session=per, window_s=round(t_hi - t_lo, 2), tokens=n,
+ ttft=[round(r["chunks"][0] - r["t0"], 2) for r in rs])
+
+
+def serve_up(chunk):
+ env = dict(os.environ, HY4_WARMUP_TOKENS="64")
+ cmd = [sys.executable, "-u", os.path.join(tree, "tools", "hy4", "serve.py"), "--model", GGUF, "--port", str(PORT), "-c", str(CTX), "--slots", str(SLOTS),
+ "--sched-chunk", str(chunk), "--default-max-tokens", str(NEW)]
+ p = subprocess.Popen(cmd, env=env, stdout=open(f"/tmp/mu_serve_{PORT}.log", "w"), stderr=subprocess.STDOUT)
+ t0 = time.time()
+ while time.time() - t0 < 420:
+ try:
+ c = http.client.HTTPConnection("127.0.0.1", PORT, timeout=3)
+ c.request("GET", "/health")
+ if c.getresponse().status == 200:
+ return p
+ except Exception: # noqa: BLE001
+ pass
+ if p.poll() is not None:
+ raise RuntimeError("server exited: " + open(f"/tmp/mu_serve_{PORT}.log").read()[-1500:])
+ time.sleep(3)
+ raise RuntimeError("server not ready")
+
+
+def main():
+ wiki = json.load(open("/path/to/wiki_ids.json"))
+ out = []
+ for ci, chunk in enumerate([int(x) for x in os.environ.get("MU_CHUNKS", str(CHUNK)).split(",")]):
+ p = serve_up(chunk)
+ try:
+ print("served: ready, chunk", chunk, flush=True)
+ if ci == 0:
+ for B in (1, 2, 4):
+ post_all = launch([chat(i) for i in range(B)])
+ for t in post_all[1]:
+ t.join()
+ time.sleep(1)
+ rs, th = launch([chat(i) for i in range(B)])
+ for t in th:
+ t.join()
+ r = summarise(rs)
+ print("SERVED", json.dumps(r), flush=True)
+ out.append(r)
+ rs, th = launch([chat(i) for i in range(3)])
+ while not all(r.get("chunks") for r in rs):
+ time.sleep(0.05)
+ time.sleep(1.5)
+ late = {}
+ ts = time.perf_counter()
+ tl = threading.Thread(target=post, args=("/v1/completions", {"prompt": wiki[:PFLEN], "max_tokens": 16, "stream": True, "stream_options": {"include_usage": True}, "speculative": SPEC}, late))
+ tl.start()
+ tl.join()
+ te = time.perf_counter()
+ for t in th:
+ t.join()
+ gaps = []
+ for r in rs:
+ tt = [t for t in r["chunks"] if ts - 0.5 <= t <= te + 0.5]
+ gaps += [b - a for a, b in zip(tt, tt[1:])]
+ base = []
+ for r in rs:
+ tt = [t for t in r["chunks"] if ts - 3 <= t <= ts - 0.2]
+ base += [b - a for a, b in zip(tt, tt[1:])]
+ res = dict(chunk=chunk, pf_tokens=PFLEN, late_ttft=round(late["chunks"][0] - late["t0"], 2) if late.get("chunks") else None,
+ max_gap=round(max(gaps), 3) if gaps else None, median_gap_before=round(sorted(base)[len(base) // 2], 3) if base else None)
+ print("SERVED_PF", json.dumps(res), flush=True)
+ out.append(res)
+ finally:
+ p.terminate()
+ try:
+ p.wait(30)
+ except Exception: # noqa: BLE001
+ p.kill()
+ time.sleep(3)
+ print("MUS_DONE", json.dumps(out), flush=True)
+
+
+main()
diff --git a/tools/hy4/serve.py b/tools/hy4/serve.py
index 85e0ca9..3dfdf2a 100644
--- a/tools/hy4/serve.py
+++ b/tools/hy4/serve.py
@@ -57,6 +57,7 @@ class State:
self.error: str | None = None
self.stage = "starting"
self.lock: asyncio.Lock | None = None
+ self.sched = None # mu_engine.MuScheduler with --slots > 1
self.served = 0
@@ -102,8 +103,47 @@ def build_app(st: State):
if n + max_new + args.num_draft + 2 > args.max_ctx:
raise C.RequestError(f"prompt ({n} tokens) + max_tokens ({max_new}) exceeds the context window ({args.max_ctx})", 400, "context_length_exceeded")
+ async def run_job_mu(ids, r, in_think, request):
+ """--slots > 1: the request joins the scheduler (own slot, batched decode with the other sessions); same events as run_job"""
+ from mu_engine import Request
+ loop = asyncio.get_running_loop()
+ q: asyncio.Queue = asyncio.Queue()
+ out = C.OutputStream(st.vocab, in_think=in_think, stops=r["stop"])
+
+ def on_tokens(toks):
+ for ch, tx in out.push(toks):
+ loop.call_soon_threadsafe(q.put_nowait, ("delta", ch, tx))
+ return out.done
+
+ req = Request(ids, r["max_tokens"], speculative=r["speculative"], on_tokens=on_tokens)
+ req.on_done = lambda: loop.call_soon_threadsafe(q.put_nowait, ("end",))
+ st.sched.submit(req)
+ try:
+ while True:
+ ev = await q.get()
+ if ev[0] == "end":
+ break
+ yield ev
+ finally:
+ req.cancel.set()
+ for ch, tx in out.finish():
+ yield ("delta", ch, tx)
+ if req.error:
+ raise RuntimeError(req.error)
+ stats = req.engine_stats(st.engine.k)
+ finish = out.finish_reason or "length"
+ st.served += 1
+ pf, dc = stats["prefill_s"], stats["decode_s"]
+ print(f"req {st.served}: prompt {stats['prompt_tokens']} tok ttft {pf:.2f} s (own prefill {stats['prefill_trunk_s']:.2f} s) | 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']} | {finish}", flush=True)
+ yield ("end", stats, finish, out.n_tokens)
+
async def run_job(ids, r, in_think, request):
"""async generator of ("delta", channel, text) events, then ("end", stats, finish_reason, n_generated)"""
+ if st.sched is not None:
+ async for ev in run_job_mu(ids, r, in_think, request):
+ yield ev
+ return
loop = asyncio.get_running_loop()
q: asyncio.Queue = asyncio.Queue()
out = C.OutputStream(st.vocab, in_think=in_think, stops=r["stop"])
@@ -266,13 +306,24 @@ def load_in_background(st: State):
try:
from engine import Hy4Engine
a = st.args
- eng = Hy4Engine(TREE, a.model, ctx=a.max_ctx, k=a.num_draft, chunk=a.prefill_chunk, prime_rows=a.draft_fill_rows)
+ if a.slots > 1:
+ from mu_engine import MuEngine
+ eng = MuEngine(TREE, a.model, ctx=a.max_ctx, k=a.num_draft, chunk=a.prefill_chunk, prime_rows=a.draft_fill_rows, slots=a.slots)
+ else:
+ eng = Hy4Engine(TREE, a.model, ctx=a.max_ctx, k=a.num_draft, chunk=a.prefill_chunk, prime_rows=a.draft_fill_rows)
def progress(s):
st.stage = s
print("load:", s, flush=True)
eng.load(progress)
- if os.environ.get("HY4_WARMUP_TOKENS", "0") != "0":
+ if a.slots > 1:
+ import mu_engine
+ st.sched = mu_engine.MuScheduler(eng, chunk=a.sched_chunk)
+ st.sched.start()
+ if os.environ.get("HY4_WARMUP_TOKENS", "0") != "0":
+ st.stage = "warm-up"
+ mu_engine.warmup(st.sched, int(os.environ["HY4_WARMUP_TOKENS"]))
+ elif os.environ.get("HY4_WARMUP_TOKENS", "0") != "0":
st.stage = "warm-up"
print("load: warm-up", flush=True)
eng.warmup(int(os.environ["HY4_WARMUP_TOKENS"]))
@@ -298,6 +349,8 @@ def main(argv=None):
ap.add_argument("--prefill-chunk", type=int, default=8192)
ap.add_argument("--draft-fill-rows", type=int, default=0, help="fill the draft head's cache for the last N prompt rows only (0 = the whole prompt)")
ap.add_argument("--default-max-tokens", type=int, default=1024)
+ ap.add_argument("--slots", type=int, default=1, help="concurrent sessions decoded in ONE batched step (1 = the single-request engine behind the lock)")
+ ap.add_argument("--sched-chunk", type=int, default=1024, help="prefill rows per scheduler turn with --slots > 1 (a decode round of the other sessions runs between chunks)")
args = ap.parse_args(argv)
apply_env(args.max_ctx)
st = State(args)