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: HY4_MU_HOSTFAST=1 batched host path (off by default): Engram rows hashed by the numpy stager and staged group by group before the graph segment that reads them, one indexed hcur copy, one draft readback, no bind for captured draft graphs, deferred n-gram appends; HY4_MU_HOSTPROF=1 per-round splits + FIRES counters in the server log; HY4_MU_PRECAP=512,1024 precaptures every (bucket, rows) trunk graph and (slot, bucket) draft graph and prints the replay curve; CPU tests

YanissAmz81dbda96351c
diff --git a/exllamav3/loader/step_mu.py b/exllamav3/loader/step_mu.py
index fcf6a8f..c46596e 100644
--- a/exllamav3/loader/step_mu.py
+++ b/exllamav3/loader/step_mu.py
@@ -10,7 +10,9 @@ head runs on a session unchanged, on the slab views. Graphs are keyed (bucket, r
from __future__ import annotations
import os
+import time
+import numpy as np
import torch
from . import mu_debug as DBG
@@ -21,6 +23,20 @@ from .engram_rows import QB # noqa: F401 (re-export for callers)
TM = SG.TM
+# HY4_MU_HOSTFAST=1: the Engram rows of a step are hashed with the numpy EngramStager (one pass per session), read with the cached-row fast path, and each layer group is staged
+# right before its own graph segment so the reads overlap the GPU (the solo step_rows pipeline); the step inputs are written through a numpy view of the pinned buffer.
+# HY4_MU_HOSTPROF=1: perf_counter splits per step (HT, seconds) for the server log line of mu_engine.
+FIRES = {"stage_vec": 0, "stage_ov": 0, "inp_np": 0, "rows_gt8": 0, "steps": 0} # path counters (FIRES-CHECK): a flagged arm with 0 stage_ov FAILS
+HT = {"stage": 0.0, "launch": 0.0, "inputs": 0.0}
+
+
+def hostfast() -> bool:
+ return os.environ.get("HY4_MU_HOSTFAST", "0") not in ("", "0")
+
+
+def hostprof() -> bool:
+ return os.environ.get("HY4_MU_HOSTPROF", "0") not in ("", "0")
+
class _GSMU(SG._GS):
"""static context of a multi-session step: inp rows 0 token, 1 position, 2 slab base (slot * cap)"""
@@ -70,6 +86,7 @@ class MultiDecoder(SG.GraphDecoder):
self.S = nslots
self.gs = _GSMU(fw, self.cap)
self.hin = torch.zeros(3, TM, dtype=torch.long).pin_memory()
+ self.hnp = self.hin.numpy()
self.mt = None
# -- one-time setup: flat slabs, then the solo prepare on slot 0's views
@@ -192,6 +209,25 @@ class MultiDecoder(SG.GraphDecoder):
self.gs.eng_raw.copy_(self.rpin, non_blocking=True)
self.gs.eng_valid.copy_(self.vpin, non_blocking=True)
+ # -- HY4_MU_HOSTFAST: vectorised staging of the Engram rows (numpy hash per session, rows concatenated along T), group by group
+ def _hash_rows(self, rows):
+ """ids int64 [nE, T, nc] and valid float32 [T] of every row of the step, rows in step order (EngramStager.hash per session: same integer maths as engram_row_ids)"""
+ parts = [self.stager.hash(s.tokens, s.n, 0, len(toks)) for s, toks in rows]
+ if len(parts) == 1:
+ return parts[0]
+ return np.concatenate([p[0] for p in parts], axis=1), np.concatenate([p[1] for p in parts])
+
+ def _stage_group_mu(self, hs, a, b):
+ """read the rows of the Engram modules a .. b - 1 into the pinned staging, then ONE H2D of those layers (stream-ordered before the next replay)"""
+ for f in self.stager.submit(hs[0], hs[1], 0, es=range(a, b)):
+ f.result()
+ if a == 0 and b == self.rpin.shape[0]:
+ self.gs.eng_raw.copy_(self.rpin, non_blocking=True)
+ self.gs.eng_valid.copy_(self.vpin, non_blocking=True)
+ else:
+ self.gs.eng_raw[a:b].copy_(self.rpin[a:b], non_blocking=True)
+ self.gs.eng_valid[a:b].copy_(self.vpin[a:b], non_blocking=True)
+
def step_slots(self, rows):
"""rows = [(session, [tokens])]: append each token list at that session's next positions, ONE graph replay for all rows. Returns DEVICE (logits, argmax, x, h)
with the rows concatenated in order (single row: logits [V], argmax scalar). session.n and session.tokens advance; a verifier that rejects rows calls `rewind`."""
@@ -200,6 +236,10 @@ class MultiDecoder(SG.GraphDecoder):
assert 1 <= T <= TM
if not self.prepared:
self.prepare()
+ fast = hostfast() and self.stager is not None
+ prof = hostprof()
+ pc = time.perf_counter
+ t0 = pc() if prof else 0.0
if self.ev_set:
self.ev.synchronize()
tk, ps, bs, top = [], [], [], 0
@@ -212,27 +252,65 @@ class MultiDecoder(SG.GraphDecoder):
top = max(top, s.n + len(toks))
Nb = min(self.cap, ((top - 1) // SG.BUCKET + 1) * SG.BUCKET)
gs.Nb = Nb
- what = f"step_slots T={T} Nb={Nb} rows={[(s.slot, s.n, len(t)) for s, t in rows]}"
+ what = f"step_slots T={T} Nb={Nb} rows={[(s.slot, s.n, len(t)) for s, t in rows]}" if (not fast or DBG.enabled()) else "step_slots"
+ bnds = self.bounds() if fast else None
+ ov = fast and (Nb, T, len(bnds)) in self.graphs # graph already captured: stage group by group while the earlier segments run
+ hs = None
with DBG.stage(what + " inputs + Engram rows"):
- self.hin[0, :T] = torch.tensor(tk)
- self.hin[1, :T] = torch.tensor(ps)
- self.hin[2, :T] = torch.tensor(bs)
+ if fast:
+ self.hnp[0, :T] = tk
+ self.hnp[1, :T] = ps
+ self.hnp[2, :T] = bs
+ FIRES["inp_np"] += 1
+ else:
+ self.hin[0, :T] = torch.tensor(tk)
+ self.hin[1, :T] = torch.tensor(ps)
+ self.hin[2, :T] = torch.tensor(bs)
gs.inp.copy_(self.hin, non_blocking=True)
- self._stage_rows(rows)
+ if prof:
+ t1 = pc()
+ HT["inputs"] += t1 - t0
+ t0 = t1
+ if fast:
+ hs = self._hash_rows(rows)
+ FIRES["stage_vec"] += 1
+ if not ov: # first use of this (bucket, rows): stage everything, the capture's warm-up bodies read the rows
+ self._stage_group_mu(hs, 0, self.rpin.shape[0])
+ else:
+ self._stage_rows(rows)
+ if prof:
+ t1 = pc()
+ HT["stage"] += t1 - t0
+ t0 = t1
if DBG.probe_enabled():
self._probe(Nb, T, rows)
with DBG.stage(what + " graph (capture if new)"):
cgs, _out = self._graph(Nb, T) # the solo capture: a LIST of graph segments (Engram split), replayed in order like step_rows
self.x_out = _out[2]
fw._h = _out[3]
- for si, cg in enumerate(cgs): # every Engram row of the step is already staged by _stage_rows: no per-segment staging, only the order
+ grp = self.groups(bnds) if ov else None
+ for si, cg in enumerate(cgs): # staged up front (_stage_rows / first use); with `ov` each group is read just before its own segment
+ if ov and grp[si] is not None:
+ t2 = pc() if prof else 0.0
+ self._stage_group_mu(hs, *grp[si])
+ if prof:
+ dt = pc() - t2
+ HT["stage"] += dt
+ t0 += dt # launch = the replay calls only
with DBG.stage(f"{what} replay segment {si}/{len(cgs)}"):
cg.replay()
+ if ov:
+ FIRES["stage_ov"] += 1
+ if T > 8:
+ FIRES["rows_gt8"] += 1
+ FIRES["steps"] += 1
self.ev.record()
self.ev_set = True
for s, toks in rows:
s.n += len(toks)
self.stats["replays"] += 1
+ if prof:
+ HT["launch"] += pc() - t0
return _out[0], _out[1], _out[2], _out[3]
@staticmethod
@@ -249,6 +327,10 @@ class MTPGraphMU(_MH.MTPGraph):
"""the draft chain graph per (slot, bucket): the captured graph holds the addresses of the slot's K buffer / indexer slab views (set `slot` and bind the session first)"""
slot = 0
+ def captured(self, slot, j):
+ """True when the draft graph of (slot, the bucket of head position j) exists: run() then needs no `bind` (a replay touches no eager state)"""
+ return (slot, min(self.mt.cap, ((j + self.k) // self.BUCKET + 1) * self.BUCKET)) in self.graphs
+
def run(self, tok, h, j):
"""drafts of the bound session as a PRIVATE device tensor. The (slot, N) graphs share one memory pool and a graph's output can live in a block that an
earlier-captured graph used for intermediates: replaying graph A after graph B (two sessions whose slots were first drafted in the other order) overwrote
diff --git a/tests/test_hy4_mu_hostfast.py b/tests/test_hy4_mu_hostfast.py
new file mode 100644
index 0000000..f879342
--- /dev/null
+++ b/tests/test_hy4_mu_hostfast.py
@@ -0,0 +1,305 @@
+"""CPU tests of HY4_MU_HOSTFAST (batched host path of a multi-session decode round), stub engine / stub decoder, no GPU:
+ 1. plain_round / spec_round produce the SAME tokens, session state (y, ng history, hcur values) and verify rows with the flag on and off (greedy stub trunk, drafts that depend on hcur,
+ real NGram, TM 8 and TM 16, plain -> spec -> plain transitions, 1 / 2 / 4 / 8 sessions);
+ 2. the numpy EngramStager hash + staging of several sessions == the per-row python staging of the baseline `_stage_rows` (bytes read from a fake table file);
+ 3. step_slots with the flag stages each Engram layer group just before its own graph segment (overlap), without it everything before the first replay; same rows either way;
+ 4. the FIRES counters fire."""
+import os
+import sys
+import types
+from types import SimpleNamespace
+
+import numpy as np
+import pytest
+import torch
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+sys.path.insert(0, os.path.join(ROOT, "tools", "hy4"))
+for _n, _s in (("exllamav3", ""), ("exllamav3.loader", "loader")):
+ _m = sys.modules.get(_n) or types.ModuleType(_n)
+ _m.__path__ = [os.path.join(ROOT, "exllamav3", _s)]
+ sys.modules[_n] = _m
+
+import mu_engine as ME # noqa: E402
+from ngram import NGram # noqa: E402
+
+K = 3
+D = 3
+
+
+def f_next(t, pos):
+ """the stub trunk: next token after token t at position pos (short cycles, so the n-gram index finds matches)"""
+ return (t * 5 + 1 + (pos // 11)) % 13
+
+
+class Sess:
+ def __init__(self, slot, prompt):
+ self.slot, self.ids, self.ng, self.hcur, self.extra = slot, list(prompt), None, None, {}
+ self.tokens, self.n = [], 0
+ self.y = None
+
+
+class FakeGR:
+ """step_slots: argmax of a row = f_next(token, position); trunk state of a row = [token, position, argmax]"""
+
+ def __init__(self, tm):
+ self.tm, self.binds, self.steps, self.rows_log = tm, 0, 0, []
+
+ def step_slots(self, rows):
+ am, hv = [], []
+ T = sum(len(t) for _, t in rows)
+ assert 1 <= T <= self.tm
+ for s, toks in rows:
+ for i, t in enumerate(toks):
+ p = s.n + i
+ a = f_next(t, p)
+ am.append(a)
+ hv.append([float(t), float(p), float(a)])
+ s.tokens.extend(toks)
+ s.n += len(toks)
+ self.rows_log.append([(s.slot, list(t)) for s, t in rows])
+ self.steps += 1
+ return None, torch.tensor(am), None, torch.tensor(hv)
+
+ def rewind(self, s, n):
+ del s.tokens[n:]
+ s.n = n
+
+ def bind(self, s):
+ self.binds += 1
+
+
+class FakeMG:
+ """draft chain: the true greedy chain, corrupted by the trunk state it is given (a wrong hcur changes the drafts, so the streams would diverge)"""
+
+ def __init__(self):
+ self.slot = 0
+ self.graphs = set()
+ self.runs = 0
+
+ def captured(self, slot, j):
+ return (slot, j // 512) in self.graphs
+
+ def run(self, tok, h, j):
+ self.graphs.add((self.slot, j // 512))
+ self.runs += 1
+ t, out = tok, []
+ pos = int(h[0, 1].item()) + 1
+ for i in range(K):
+ t = f_next(t, pos + i)
+ out.append(t + 1 if (int(h[0, 0].item()) + int(h[0, 2].item()) + i) % 4 == 0 else t)
+ return torch.tensor(out)
+
+
+def make(tm, ng_ext=4, slots=8):
+ eng = object.__new__(ME.MuEngine)
+ eng.torch, eng.dev, eng.k, eng.slots = torch, "cpu", K, slots
+ eng.GR, eng.MG, eng.MT = FakeGR(tm), FakeMG(), SimpleNamespace(step=lambda *a, **k: None, ar=torch.arange(64))
+ eng.SG = SimpleNamespace(TM=tm)
+ eng.ngram_ext, eng.ngram_min, eng.ngram_gate, eng.ngram_adapt, eng.ngram_fill, eng.ngram_long = ng_ext, 2, True, False, False, 0
+ return eng
+
+
+def start(eng, n):
+ out = []
+ for slot in range(n):
+ s = Sess(slot, [(slot * 3 + i * 2) % 13 for i in range(20 + slot)])
+ s.tokens = list(s.ids)
+ s.n = len(s.ids)
+ s.y = (slot * 7 + 1) % 13
+ s.hcur = torch.tensor([[float(s.ids[-1]), float(s.n - 1), 0.0]])
+ out.append(s)
+ return out
+
+
+def drive(fast, tm, n, plan, monkeypatch):
+ """plan = sequence of 'p' / 's' rounds; -> everything observable"""
+ monkeypatch.setenv("HY4_MU_HOSTFAST", "1" if fast else "0")
+ eng = make(tm)
+ sess = start(eng, n)
+ emitted = {s.slot: [] for s in sess}
+ for kind in plan:
+ out = eng.plain_round(sess) if kind == "p" else eng.spec_round(sess)
+ for s in sess:
+ emitted[s.slot] += out[s]
+ for s in sess:
+ eng._ng_flush(s)
+ return {"emitted": emitted, "y": [s.y for s in sess], "n": [s.n for s in sess], "tokens": [list(s.tokens) for s in sess], "hcur": [s.hcur.clone().tolist() for s in sess],
+ "ng": [list(s.ng.seq) if s.ng is not None else None for s in sess], "rows": eng.GR.rows_log, "gate": [dict(s.extra) for s in sess]}, eng
+
+
[email protected]("tm", [8, 16])
[email protected]("n", [1, 2, 4, 8])
+def test_rounds_identical_with_and_without_hostfast(tm, n, monkeypatch):
+ plan = "pppsssspsspppsssss"
+ if n * 2 > tm: # spec needs >= 2 rows per session (the scheduler runs plain above MAXB)
+ plan = "pppp" + "p" * 14
+ a, ea = drive(False, tm, n, plan, monkeypatch)
+ b, eb = drive(True, tm, n, plan, monkeypatch)
+ assert a == b
+ assert ea.GR.binds >= eb.GR.binds
+ if "s" in plan:
+ assert eb.GR.binds < ea.GR.binds # the captured (slot, bucket) draft graphs run without bind
+ assert ME.FIRES["bind_skip"] > 0 and ME.FIRES["draft_cat"] > 0 and ME.FIRES["spec"] > 0
+ assert ME.FIRES["plain"] > 0 and ME.FIRES["hcur_idx"] > 0
+
+
+def test_hcur_rows_are_isolated_and_values_are_the_continuation_row(monkeypatch):
+ monkeypatch.setenv("HY4_MU_HOSTFAST", "1")
+ eng = make(8)
+ sess = start(eng, 3)
+ eng.spec_round(sess)
+ for s in sess:
+ want = [float(s.tokens[-1]), float(s.n - 1), float(f_next(s.tokens[-1], s.n - 1))]
+ assert s.hcur.shape == (1, D) and s.hcur[0].tolist() == want
+ sess[0].hcur.zero_() # a view of ITS slot row only
+ assert all(float(s.hcur.abs().sum()) > 0 for s in sess[1:])
+
+
+def test_plain_round_defers_the_history_append_but_never_loses_it(monkeypatch):
+ monkeypatch.setenv("HY4_MU_HOSTFAST", "1")
+ eng = make(8)
+ s = start(eng, 1)[0]
+ s.ng = NGram(2, 4)
+ s.ng.reset(list(s.ids) + [s.y])
+ s.extra.update(rate=0.7, since=0)
+ n0 = len(s.ng.seq)
+ eng.plain_round([s])
+ assert len(s.ng.seq) == n0 # appended while the NEXT round runs
+ eng.plain_round([s])
+ assert len(s.ng.seq) == n0 + 1
+ eng.spec_round([s]) # a spec round flushes before it proposes
+ assert s.ng_pend is not None
+
+
+# ------------------------------------------------------------------------------------------------------------------ Engram staging
+def decoder(tmp_path):
+ if not os.path.exists("/proc/self/fd"):
+ pytest.skip("Linux only (page-cache reads through /proc/self/fd)")
+ from exllamav3.loader import step_mu
+ from exllamav3.loader.engram_stage import EngramStager
+ ng, nh, nE, TMX, rb = 3, 2, 3, 8, 16
+ nc = (ng - 1) * nh
+ n_tm = 40
+ rng = np.random.RandomState(7)
+ primes = [101, 103, 107, 109]
+ offs = np.cumsum([0] + primes[:-1]).tolist()
+ nrows = sum(primes) + 4
+ path = tmp_path / "table.bin"
+ path.write_bytes(rng.randint(1, 255, size=nrows * rb, dtype=np.uint8).tobytes())
+ fd = os.open(str(path), os.O_RDONLY)
+ g = SimpleNamespace(fds=[fd], bases=[0])
+ table = SimpleNamespace(off=0, row_bytes=rb, rows=nrows, name="t", g=g)
+ token_map = rng.randint(0, 29, size=n_tm).tolist()
+ mods = []
+ for e in range(nE):
+ mods.append(SimpleNamespace(e=e, token_map=token_map, pad_id=1, n_gram=ng, n_head=nh, n_cols=nc, mult=[int(x) for x in rng.randint(1, 2 ** 31, size=ng)],
+ primes=primes, offs=offs))
+ d = object.__new__(step_mu.MultiDecoder)
+ d.fw = SimpleNamespace(ple=[2, 5, 9][:nE], eng={2: mods[0], 5: mods[1], 9: mods[2]}, table=table, g=g, n_layers=12)
+ d.rpin = torch.zeros(nE, TMX, nc, rb, dtype=torch.uint8)
+ d.vpin = torch.zeros(nE, TMX, nc, dtype=torch.float32)
+ d.rnp = d.rpin.numpy()
+ d._rmv = None
+ d.gs = SimpleNamespace(eng_raw=torch.zeros(nE, TMX, nc, rb, dtype=torch.uint8), eng_valid=torch.zeros(nE, TMX, nc))
+ d.stager = EngramStager(mods, table, d.rnp, d.vpin.numpy(), pool=None)
+ d.stager.nowait = False
+ yield d
+ os.close(fd)
+
+
+def sessions_for_rows(spec, n_tm=40):
+ rng = np.random.RandomState(3)
+ rows = []
+ for slot, (n, T) in enumerate(spec):
+ s = Sess(slot, [])
+ hist = [int(x) for x in rng.randint(0, n_tm + 10, size=n + T)] # ids past the token map: dead rows
+ s.tokens, s.n = hist, n
+ rows.append((s, hist[n:]))
+ return rows
+
+
[email protected]("spec", [[(0, 1)], [(1, 2), (20, 1)], [(5, 3), (0, 2), (31, 2), (2, 1)]])
+def test_vectorised_staging_equals_the_python_baseline(decoder, spec):
+ d = decoder
+ rows = sessions_for_rows(spec)
+ d._stage_rows(rows) # baseline: per row, per layer python hash
+ want_r, want_v = d.rpin.clone(), d.vpin.clone()
+ want_g = (d.gs.eng_raw.clone(), d.gs.eng_valid.clone())
+ d.rpin.zero_()
+ d.vpin.zero_()
+ d.gs.eng_raw.zero_()
+ d.gs.eng_valid.zero_()
+ hs = d._hash_rows(rows)
+ nE = d.rpin.shape[0]
+ d._stage_group_mu(hs, 0, 1) # group by group, as the overlapped replay does
+ d._stage_group_mu(hs, 1, nE)
+ T = sum(len(t) for _, t in rows)
+ assert torch.equal(d.rpin[:, :T], want_r[:, :T]) and torch.equal(d.vpin[:, :T], want_v[:, :T])
+ assert torch.equal(d.gs.eng_raw[:, :T], want_g[0][:, :T]) and torch.equal(d.gs.eng_valid[:, :T], want_g[1][:, :T])
+
+
+# ------------------------------------------------------------------------------------------------------------------ step_slots overlap
+class FakeSeg:
+ def __init__(self, d, si, log, expect):
+ self.d, self.si, self.log, self.expect = d, si, log, expect
+
+ def replay(self):
+ raw = self.d.gs.eng_raw
+ staged = [bool(raw[e].any()) for e in range(raw.shape[0])]
+ self.log.append((self.si, staged))
+
+
+def make_step(d, rows_spec, monkeypatch, fast):
+ from exllamav3.loader import step_mu
+ monkeypatch.setenv("HY4_MU_HOSTFAST", "1" if fast else "0")
+ d.hin = torch.zeros(3, 8, dtype=torch.long)
+ d.hnp = d.hin.numpy()
+ d.gs.inp = torch.zeros(3, 8, dtype=torch.long)
+ d.gs.Nb = d.gs.T = 0
+ d.cap, d.prepared, d.ev_set, d.ev = 4096, True, False, SimpleNamespace(synchronize=lambda: None, record=lambda: None)
+ d.stats = {"replays": 0}
+ d.split = True
+ log = []
+ out = (None, torch.zeros(1), torch.zeros(1), torch.zeros(1))
+ d.graphs = {}
+ segs = [FakeSeg(d, i, log, None) for i in range(3)]
+ d._graph = lambda Nb, T: (segs, out)
+ return step_mu, log
+
+
[email protected]("fast", [False, True])
+def test_step_slots_stages_before_the_segment_that_reads_them(decoder, monkeypatch, fast):
+ d = decoder
+ step_mu, log = make_step(d, None, monkeypatch, fast)
+ rows = sessions_for_rows([(5, 2), (9, 1)])
+ key = (512, 3, len(d.bounds()))
+ if fast:
+ d.graphs[key] = True # the graph exists: overlapped staging
+ f0 = dict(step_mu.FIRES)
+ d.step_slots(rows)
+ assert [si for si, _ in log] == [0, 1, 2]
+ if fast:
+ assert log[0][1] == [False, False, False] and log[1][1] == [True, False, False] and log[2][1] == [True, True, True]
+ assert step_mu.FIRES["stage_ov"] == f0["stage_ov"] + 1 and step_mu.FIRES["stage_vec"] == f0["stage_vec"] + 1
+ else:
+ assert log[0][1] == [True, True, True] # baseline: everything staged before the first replay
+ assert step_mu.FIRES["stage_ov"] == f0["stage_ov"]
+ assert [s.n for s, _ in rows] == [7, 10] and d.stats["replays"] == 1
+
+
+def test_step_slots_rows_equal_in_both_modes(decoder, monkeypatch):
+ d = decoder
+ got = {}
+ for fast in (False, True):
+ step_mu, _ = make_step(d, None, monkeypatch, fast)
+ d.rpin.zero_()
+ d.vpin.zero_()
+ d.gs.eng_raw.zero_()
+ d.gs.eng_valid.zero_()
+ rows = sessions_for_rows([(5, 2), (9, 1), (0, 2)])
+ d.graphs = {(512, 5, len(d.bounds())): True} if fast else {}
+ d.step_slots(rows)
+ got[fast] = (d.gs.eng_raw[:, :5].clone(), d.gs.eng_valid[:, :5].clone(), d.hin[:, :5].clone())
+ assert all(torch.equal(a, b) for a, b in zip(got[False], got[True]))
diff --git a/tools/hy4/mu_engine.py b/tools/hy4/mu_engine.py
index 4f0fc87..2bfb483 100644
--- a/tools/hy4/mu_engine.py
+++ b/tools/hy4/mu_engine.py
@@ -15,6 +15,38 @@ from collections import deque
from engine import Hy4Engine, PRIME_ROWS, warmup_clamp
+# HY4_MU_HOSTFAST=1 (default OFF): the batched host path of a decode round (see MuEngine._hcur_set, plain_round, spec_round, step_mu.step_slots).
+# HY4_MU_HOSTPROF=1: perf_counter splits per round, one `MUFAST` line per 100 rounds in the server log (also the FIRES-CHECK path counters).
+FIRES = {"plain": 0, "spec": 0, "hcur_idx": 0, "bind_skip": 0, "draft_cat": 0}
+HT = {"rounds": 0, "rows": 0, "draft": 0.0, "wait": 0.0, "post": 0.0, "emit": 0.0, "round": 0.0}
+
+
+def _fast() -> bool:
+ return os.environ.get("HY4_MU_HOSTFAST", "0") not in ("", "0")
+
+
+def _prof() -> bool:
+ return os.environ.get("HY4_MU_HOSTPROF", "0") not in ("", "0")
+
+
+def fires_line(eng, last: dict | None = None) -> str:
+ """one log line: path counters (cumulative) + mean ms per decode round since the previous line (`last` = the previous snapshot, updated in place)"""
+ sm = getattr(eng, "SM", None)
+ fs = dict(FIRES)
+ ht = dict(HT)
+ if sm is not None:
+ fs.update(sm.FIRES)
+ ht.update({"stage": sm.HT["stage"], "launch": sm.HT["launch"], "inputs": sm.HT["inputs"]})
+ last = {} if last is None else last
+ nr = max(1, ht["rounds"] - last.get("rounds", 0))
+ ms = {k: 1000.0 * (ht.get(k, 0.0) - last.get(k, 0.0)) / nr for k in ("round", "inputs", "stage", "launch", "draft", "wait", "post", "emit")}
+ rows = (ht["rows"] - last.get("rows", 0)) / nr
+ last.clear()
+ last.update(ht)
+ return ("MUFAST rounds=%d fast=%d " % (ht["rounds"], int(_fast())) + " ".join(f"{k}={v}" for k, v in fs.items()) +
+ " | ms/round " + " ".join(f"{k}={v:.2f}" for k, v in ms.items()) + f" rows/round={rows:.2f}")
+
+
def _stage(name):
"""HY4_MU_SYNC_DEBUG=1: log the stage and sync the device when it ends (loader/mu_debug.py); a null context otherwise"""
if os.environ.get("HY4_MU_SYNC_DEBUG", "0") in ("", "0"):
@@ -90,6 +122,8 @@ class MuEngine(Hy4Engine):
# ------------------------------------------------------------------------------------------ decode rounds
def plain_round(self, sess):
"""one row per session -> {session: [new token]}"""
+ if _fast():
+ return self._plain_round_fast(sess)
rows = [(s, [s.y]) for s in sess]
_lg, am, _x, hv = self.GR.step_slots(rows)
amh = am.reshape(-1).tolist()
@@ -103,6 +137,77 @@ class MuEngine(Hy4Engine):
out[s] = [s.y]
return out
+ # ---- HY4_MU_HOSTFAST: batched host work of a round
+ def _hcur_set(self, sess, hv, rows=None):
+ """s.hcur of every session in ONE indexed device copy into a preallocated [slots, D] buffer (no per-slot clone); s.hcur is then a [1, D] view of the session's row.
+ hv = the step's trunk states [T, D]; rows = the row of hv each session continues from (None: row r of session r, T == len(sess))."""
+ torch = self.torch
+ D = hv.shape[-1]
+ hb = getattr(self, "_hbuf", None)
+ if hb is None:
+ dev = hv.device
+ hb = self._hbuf = torch.zeros(self.slots, D, dtype=hv.dtype, device=dev)
+ self._hviews = [hb[i:i + 1] for i in range(self.slots)]
+ self._sidx = {}
+ n = max(self.slots, 16)
+ self._rpin = torch.zeros(n, dtype=torch.long).pin_memory() if dev.type == "cuda" else torch.zeros(n, dtype=torch.long)
+ self._rdev = torch.zeros(n, dtype=torch.long, device=dev)
+ key = tuple(s.slot for s in sess)
+ idx = self._sidx.get(key)
+ if idx is None: # once per distinct slot tuple (a blocking pageable H2D): never in a steady round
+ idx = self._sidx[key] = torch.tensor(key, dtype=torch.long, device=hv.device)
+ src = hv.reshape(-1, D)
+ if rows is None:
+ src = src[:len(key)]
+ else:
+ n = len(rows)
+ self._rpin[:n] = torch.tensor(rows, dtype=torch.long)
+ self._rdev[:n].copy_(self._rpin[:n], non_blocking=True) # the previous copy of this pinned slice was enqueued before the last readback (a sync): safe to overwrite
+ src = src.index_select(0, self._rdev[:n])
+ hb.index_copy_(0, idx, src)
+ views = self._hviews
+ for s in sess:
+ s.hcur = views[s.slot]
+ FIRES["hcur_idx"] += 1
+
+ @staticmethod
+ def _ng_flush(s):
+ """append the tokens of the previous round to the n-gram history (deferred out of the round's critical path)"""
+ p = getattr(s, "ng_pend", None)
+ if p and s.ng is not None:
+ s.ng.add(p)
+ p.clear()
+
+ def _plain_round_fast(self, sess):
+ pc = time.perf_counter
+ prof = _prof()
+ t0 = pc()
+ rows = [(s, [s.y]) for s in sess]
+ _lg, am, _x, hv = self.GR.step_slots(rows) # launched, the GPU runs from here
+ for s in sess:
+ self._ng_flush(s) # history appends of the previous round overlap the replay
+ self._hcur_set(sess, hv) # stream-ordered after the replay: no host wait
+ t1 = pc()
+ amh = am.reshape(-1).tolist() # the ONE readback
+ t2 = pc()
+ out = {}
+ for r, s in enumerate(sess):
+ y = amh[r]
+ s.y = y
+ if s.ng is not None:
+ p = getattr(s, "ng_pend", None)
+ if p is None:
+ p = s.ng_pend = []
+ p.append(y)
+ out[s] = [y]
+ FIRES["plain"] += 1
+ if prof:
+ t3 = pc()
+ HT["wait"] += t2 - t1
+ HT["post"] += t3 - t2
+ return out
+
+
def _ng(self, s):
if s.ng is None and self.ngram_ext > 0:
from ngram import NGram
@@ -112,8 +217,13 @@ class MuEngine(Hy4Engine):
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]}"""
+ """speculative round of every session in sess: drafts per session (own head state), ONE verify replay over all rows. -> {session: [new tokens]}
+ HY4_MU_HOSTFAST: no bind where the (slot, bucket) draft graph exists, ONE readback of all drafts, hcur by one indexed copy, history appends deferred"""
torch, GR, MG, MT, k = self.torch, self.GR, self.MG, self.MT, self.k
+ fast = _fast()
+ prof = _prof()
+ pc = time.perf_counter
+ t0 = pc()
TM = self.SG.TM
Rs = max(1, TM // len(sess)) # verify rows per session
ks = min(k, Rs - 1)
@@ -124,21 +234,36 @@ class MuEngine(Hy4Engine):
continue
j = s.n - 1
ng = self._ng(s)
+ if fast:
+ self._ng_flush(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()))
+ plan.append((s, [s.y] + cl, True, j, s.hcur if fast else s.hcur.clone())) # fast: s.hcur is only replaced after the round
continue
- GR.bind(s)
+ cap = getattr(MG, "captured", None)
+ if fast and cap is not None and cap(s.slot, j):
+ FIRES["bind_skip"] += 1 # a replay of a captured (slot, bucket) graph reads no eager state
+ else:
+ GR.bind(s)
MG.slot = s.slot
with _stage(f"spec_round draft chain slot {s.slot} j {j}"):
plan.append((s, None, False, j, MG.run(s.y, s.hcur, j))) # drafts launched; read below
+ drafts = {}
+ if fast:
+ pend = [p for p in plan if p[1] is None]
+ if pend:
+ flat = torch.cat([p[4] for p in pend]).tolist() # ONE readback for the drafts of every session
+ L = len(flat) // len(pend)
+ for i, p in enumerate(pend):
+ drafts[p[0]] = flat[i * L:i * L + ks]
+ FIRES["draft_cat"] += 1
rows, meta = [], []
for s, toks, skip, j, h in plan:
if toks is None:
- d = h.tolist()[:ks]
+ d = drafts[s] if fast else h.tolist()[:ks]
ext = []
ng = s.ng
if ng is not None:
@@ -156,15 +281,18 @@ class MuEngine(Hy4Engine):
else:
meta.append((s, toks, skip, j, 0, ks))
rows.append((s, toks))
+ t1 = pc()
starts = {s: s.n for s, _ in rows}
_lg, amv, _x, hv = GR.step_slots(rows)
+ t2 = pc()
amh_all = amv.reshape(-1).tolist()
+ t3 = pc()
out, o = {}, 0
+ accrow = []
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
@@ -186,11 +314,30 @@ class MuEngine(Hy4Engine):
with _stage(f"spec_round draft catch-up (fill) slot {s.slot} j {j} acc {acc} N {N}"):
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()
+ if fast:
+ p = getattr(s, "ng_pend", None)
+ if p is None:
+ p = s.ng_pend = []
+ p.extend(new)
+ else:
+ s.ng.add(new)
+ if fast:
+ s.y = amh[acc]
+ accrow.append(o + acc)
+ else:
+ s.y, s.hcur = amh[acc], hs[acc:acc + 1].clone()
+ o += T
s.extra["hist"] = s.extra.get("hist", 0) + 1
s.extra["acc_sum"] = s.extra.get("acc_sum", 0) + acc
out[s] = new
+ if fast:
+ self._hcur_set([m[0] for m in meta], hv, accrow)
+ FIRES["spec"] += 1
+ if prof:
+ t4 = pc()
+ HT["draft"] += t1 - t0
+ HT["wait"] += t3 - t2
+ HT["post"] += t4 - t3
return out
@@ -284,6 +431,7 @@ class MuScheduler(threading.Thread):
def run(self):
eng, pc = self.eng, time.perf_counter
+ prof, snap = _prof(), {}
try:
eng.phase("decode")
while True:
@@ -336,6 +484,13 @@ class MuScheduler(threading.Thread):
r.rounds += 1
if self._emit(r, out[r.sess], t1):
self._finish(r)
+ if prof:
+ HT["rounds"] += 1
+ HT["rows"] += len(sess)
+ HT["round"] += t1 - t0
+ HT["emit"] += pc() - t1
+ if HT["rounds"] % 100 == 0:
+ print(fires_line(eng, snap), flush=True)
except Exception as ex: # noqa: BLE001
import traceback
traceback.print_exc()
@@ -358,3 +513,48 @@ def warmup(sch: MuScheduler, n: int, new: int = 24):
for r in reqs:
r.done.wait(900)
print(f"mu warm-up: {n} prompt tokens, 1..{eng.slots} sessions", flush=True)
+
+
+def precapture(sch: MuScheduler, nbs=None, ts=None, progress=print):
+ """HY4_MU_PRECAP=512,1024 (context buckets): capture every (bucket, rows) trunk graph for rows in 1..TM and every (slot, bucket) draft graph NOW, before any timing, and print
+ the replay curve `MUCURVE Nb T ms` (one timed replay each; rows of one dummy session on the last slot, which a real request re-zeroes on admission). Call before the server is ready:
+ the scheduler must be idle. Rows above 8 run the fallback kernels (mla_bgemv / router_gemv keep their MAXT = 8 guards, mu_slots MAX_T = 16): the curve shows their cost."""
+ eng, torch = sch.eng, sch.eng.torch
+ GR, MG = eng.GR, eng.MG
+ TM = eng.SG.TM
+ if nbs is None:
+ nbs = [int(x) for x in os.environ.get("HY4_MU_PRECAP", "512").replace("+", ",").split(",") if x.strip()]
+ ts = list(ts) if ts is not None else list(range(1, TM + 1))
+ pc = time.perf_counter
+ t00 = pc()
+ s = GR.new_session(eng.slots - 1)
+ for Nb in nbs:
+ for T in ts:
+ base = Nb - T # top = Nb: the rows land in bucket Nb
+ for rep in range(3):
+ GR.rewind(s, 0)
+ s.tokens = [0] * base
+ s.n = base
+ t = pc()
+ GR.step_slots([(s, [1] * T)])
+ torch.cuda.synchronize()
+ ms = (pc() - t) * 1000
+ if rep == 0:
+ cap_ms = ms
+ progress(f"MUCURVE Nb={Nb} T={T} ms={ms:.1f} capture_or_first_ms={cap_ms:.0f}")
+ GR.rewind(s, 0)
+ nd = 0
+ for slot in range(eng.slots): # the draft chain graph is keyed (slot, bucket): every slot may serve the first request of a cell
+ s2 = GR.new_session(slot)
+ GR.bind(s2)
+ MG.slot = slot
+ for Nb in nbs:
+ if (slot, Nb) not in MG.graphs:
+ MG._graph(Nb)
+ nd += 1
+ free = None
+ try:
+ free = torch.cuda.mem_get_info()[0] / 2 ** 30
+ except Exception: # noqa: BLE001
+ pass
+ progress(f"mu precapture: buckets {nbs} rows {ts[0]}..{ts[-1]}: {len(nbs) * len(ts)} trunk graphs, {nd} draft graphs, {pc() - t00:.1f} s, free GiB {free}")
diff --git a/tools/hy4/serve.py b/tools/hy4/serve.py
index 36a6b0d..a5793dd 100644
--- a/tools/hy4/serve.py
+++ b/tools/hy4/serve.py
@@ -450,6 +450,9 @@ def load_in_background(st: State):
if os.environ.get("HY4_WARMUP_TOKENS", "0") != "0":
st.stage = "warm-up"
mu_engine.warmup(st.sched, int(os.environ["HY4_WARMUP_TOKENS"]))
+ if os.environ.get("HY4_MU_PRECAP", "0") not in ("", "0"): # HY4_MU_PRECAP=512,1024: every (bucket, rows) trunk graph + every (slot, bucket) draft graph before the first request
+ st.stage = "precapture"
+ mu_engine.precapture(st.sched)
elif os.environ.get("HY4_WARMUP_TOKENS", "0") != "0":
st.stage = "warm-up"
print("load: warm-up", flush=True)