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 graph step in 3 segments (Engram rows of the later layers staged while the GPU runs), page-cache-first row reads, ab2 driver

YanissAmz48c19d72d8c9
diff --git a/exllamav3/loader/engram_stage.py b/exllamav3/loader/engram_stage.py
index 16af008..e47ab41 100644
--- a/exllamav3/loader/engram_stage.py
+++ b/exllamav3/loader/engram_stage.py
@@ -44,8 +44,18 @@ class EngramStager:
self.fd, self.o0, self.rb, self.nrows = tab.g.fds[fi], tab.g.bases[fi] + (tab.off & ((1 << 48) - 1)), tab.row_bytes, tab.rows
self.views = {} # (e, t, c) -> memoryview of the staging row
self.pool = pool
- self.workers = workers if workers is not None else int(os.environ.get("HY4_STAGE_WORKERS", "4"))
- self.inline_max = int(os.environ.get("HY4_STAGE_INLINE", "0")) # <= this many reads: no pool at all
+ self.workers = workers if workers is not None else int(os.environ.get("HY4_STAGE_WORKERS", "64"))
+ # cached rows are copied inline with preadv(RWF_NOWAIT) (0.1 ms for a whole step, no thread hand-off); the rows that are NOT in the page cache (the table is 65 GB:
+ # most rows of new text) go to the thread pool on a private fd with readahead off (4 KB per miss instead of ~13 KB)
+ self.nowait = hasattr(os, "RWF_NOWAIT") and os.environ.get("HY4_STAGE_NOWAIT", "1") == "1"
+ self.force_miss = False # tests: treat every row as a page-cache miss
+ self.fd_c = os.open(f"/proc/self/fd/{self.fd}", os.O_RDONLY)
+ self.fd_r = os.open(f"/proc/self/fd/{self.fd}", os.O_RDONLY)
+ try:
+ os.posix_fadvise(self.fd_r, 0, 0, os.POSIX_FADV_RANDOM)
+ except OSError:
+ pass
+ self.stats = {"rows": 0, "miss": 0}
# -- hash ----------------------------------------------------------------------------------------------------------------------------
@staticmethod
@@ -88,27 +98,55 @@ class EngramStager:
return v
def _read(self, items):
- fd, o0, rb = self.fd, self.o0, self.rb
+ fd, o0, rb = self.fd_r, self.o0, self.rb
for e, t, c, r in items:
mv = self._view(e, t, c)
- if os.preadv(fd, [mv], o0 + r * rb) != rb:
- raise IOError(f"{self.table.name}: short read of row {r}")
+ got = 0
+ while got < rb:
+ n = os.preadv(fd, [mv[got:]], o0 + r * rb + got)
+ if n <= 0:
+ raise IOError(f"{self.table.name}: short read of row {r}")
+ got += n
- def submit(self, ids, valid, t0: int):
- """ids int64 [nE, T, nc] (from hash), valid [T]: fill the staging rows t0 .. t0 + T - 1 -> futures to wait on (the calling thread's own share is already done)"""
+ def _read_cached(self, items):
+ """items whose bytes are all in the page cache are copied now; returns the others"""
+ fd, o0, rb = self.fd_c, self.o0, self.rb
+ miss = []
+ for it in items:
+ e, t, c, r = it
+ try:
+ n = os.preadv(fd, [self._view(e, t, c)], o0 + r * rb, os.RWF_NOWAIT)
+ except BlockingIOError:
+ n = 0
+ if n != rb:
+ miss.append(it)
+ return miss
+
+ def submit(self, ids, valid, t0: int, es=None):
+ """ids int64 [nE, T, nc] (from hash), valid [T]: fill the staging rows t0 .. t0 + T - 1 of the layers `es` (default all) -> futures to wait on (the calling
+ thread's own share is already done)"""
T = ids.shape[1]
- if ids.size and (int(ids.min()) < 0 or int(ids.max()) >= self.nrows):
+ es = list(range(self.nE)) if es is None else list(es)
+ sel = ids[es]
+ if sel.size and (int(sel.min()) < 0 or int(sel.max()) >= self.nrows):
raise IndexError(f"{self.table.name}: row id outside 0..{self.nrows - 1}")
if t0 + T > self.TM:
raise IndexError(f"rows {t0}..{t0 + T - 1} past the staging buffer ({self.TM})")
- self.vnp[:, t0:t0 + T, :] = valid[None, :, None]
- items = [(e, t0 + t, c, int(ids[e, t, c])) for e in range(self.nE) for t in range(T) for c in range(self.nc)]
- n = len(items)
- if self.pool is None or self.workers <= 1 or n <= self.inline_max:
+ for e in es:
+ self.vnp[e, t0:t0 + T, :] = valid[:, None]
+ idl = ids.tolist()
+ items = [(e, t0 + t, c, idl[e][t][c]) for e in es for t in range(T) for c in range(self.nc)]
+ self.stats["rows"] += len(items)
+ if self.nowait and not self.force_miss:
+ items = self._read_cached(items)
+ self.stats["miss"] += len(items)
+ if not items:
+ return []
+ if self.pool is None or self.workers <= 1:
self._read(items)
return []
- per = -(-n // self.workers)
- chunks = [items[a:a + per] for a in range(0, n, per)]
+ per = -(-len(items) // self.workers)
+ chunks = [items[a:a + per] for a in range(0, len(items), per)]
futs = [self.pool.submit(self._read, ch) for ch in chunks[1:]]
self._read(chunks[0])
return futs
diff --git a/exllamav3/loader/step_graph.py b/exllamav3/loader/step_graph.py
index 067f946..1745a19 100644
--- a/exllamav3/loader/step_graph.py
+++ b/exllamav3/loader/step_graph.py
@@ -14,6 +14,7 @@ Generic: shapes and config come from the Hy4Forward object; nothing is keyed on
from __future__ import annotations
import math
import os
+import time
from concurrent.futures import ThreadPoolExecutor
import numpy as np
@@ -30,6 +31,7 @@ MASK64 = (1 << 64) - 1
PERT = None # [cap, D] fp32 noise table (measurement arms only)
_IO_W = int(os.environ.get("HY4_GRAPH_IO", "64"))
_POOL = ThreadPoolExecutor(max_workers=_IO_W)
+SPLIT = os.environ.get("HY4_GRAPH_SPLIT", "1") == "1" # 3 graphs per step, cut before the first two Engram layers: the rows of the later layers are staged while the GPU runs the earlier ones
STAGE_VEC = os.environ.get("HY4_STAGE_VEC", "1") == "1" # vectorised Engram hash + a few big read chunks (engram_stage); 0 = the per-row python path
@@ -206,6 +208,8 @@ class GraphDecoder:
self.hin = torch.zeros(2, TM, dtype=torch.long).pin_memory()
self.hnp = self.hin.numpy()
self.stager = None
+ self.split = SPLIT
+ self.t_launch = 0.0
self._pre = None
self.stats = {"captures": 0, "replays": 0, "capture_s": 0.0}
self.ev = torch.cuda.Event()
@@ -274,14 +278,37 @@ class GraphDecoder:
ix.vgb.zero_()
# -- the step body (eager warm-up and capture run exactly this)
- def body(self):
+ def bounds(self):
+ """layer ranges of the graph segments. Engram rows are applied at the START of an Engram layer, so the cuts sit before the first two Engram layers:
+ [embedding + layers before ple[0]) | [ple[0], ple[1]) | [ple[1], end + head). The rows of ple[0] are staged while segment 0 runs, those of the later
+ layers while segment 1 runs (the host never holds the GPU back for them). One segment when split is off or the model has < 2 Engram layers."""
+ fw = self.fw
+ ple = sorted(fw.ple)
+ if self.split and self.stager is not None and len(ple) >= 2 and 0 < ple[0] < ple[1]:
+ return [(0, ple[0]), (ple[0], ple[1]), (ple[1], fw.n_layers)]
+ return [(0, fw.n_layers)]
+
+ def groups(self, bnds):
+ """per segment: the Engram module range [a, b) whose rows must be on the device before the segment starts (None = none)"""
+ ple = sorted(self.fw.ple)
+ out = []
+ for lo, hi in bnds:
+ es = [e for e, L in enumerate(ple) if lo <= L < hi]
+ out.append((es[0], es[-1] + 1) if es else None)
+ return out
+
+ def body_seg(self, si, x, bnds):
fw, gs = self.fw, self.gs
- e = _ns.gather_dequant_q8_0(self.st.table, gs.tok)
- if PERT is not None: # noise-ensemble null arm: 1e-6 fixed-seed perturbation of the embedding output (quality gate, never in production)
- e = e + PERT[gs.pos]
- x = e[:, None, :].expand(-1, fw.hc, -1).contiguous()
- for i in range(fw.n_layers):
+ lo, hi = bnds[si]
+ if si == 0:
+ e = _ns.gather_dequant_q8_0(self.st.table, gs.tok)
+ if PERT is not None: # noise-ensemble null arm: 1e-6 fixed-seed perturbation of the embedding output (quality gate, never in production)
+ e = e + PERT[gs.pos]
+ x = e[:, None, :].expand(-1, fw.hc, -1).contiguous()
+ for i in range(lo, hi):
x = fw.layer(i, x, gs.pos, None, 0)
+ if si < len(bnds) - 1:
+ return x
fw._ns_dev = True
try:
lg = fw._head(x, gs.T > 1) # T > 1: logits of every row [T, V]
@@ -289,6 +316,13 @@ class GraphDecoder:
fw._ns_dev = False
return lg, torch.argmax(lg, -1), x, fw._h
+ def body(self, bnds=None):
+ bnds = bnds or self.bounds()
+ x = None
+ for si in range(len(bnds)):
+ x = self.body_seg(si, x, bnds)
+ return x
+
def bucket(self, start, T=1):
"""context bucket Nb of a step of T rows at positions start .. start + T - 1 (rows past the last position are masked inside the graph)"""
return min(self.cap, ((start + T - 1) // BUCKET + 1) * BUCKET)
@@ -312,7 +346,7 @@ class GraphDecoder:
assert 1 <= T <= TM
for Nb in nbs:
assert Nb % BUCKET == 0 and Nb <= self.cap
- if (Nb, T) in self.graphs:
+ if (Nb, T, len(self.bounds())) in self.graphs:
continue
t = time.perf_counter()
self._graph(Nb, T)
@@ -322,7 +356,8 @@ class GraphDecoder:
return out
def _graph(self, Nb, T=1):
- g = self.graphs.get((Nb, T))
+ key = (Nb, T, len(self.bounds()))
+ g = self.graphs.get(key)
if g is not None:
return g
import time
@@ -330,20 +365,24 @@ class GraphDecoder:
fw, gs = self.fw, self.gs
gs.Nb, gs.T = Nb, T
fw._gs = gs
+ bnds = self.bounds()
try:
s = torch.cuda.Stream()
s.wait_stream(torch.cuda.current_stream())
with torch.cuda.stream(s):
for _ in range(2):
- self.body()
+ self.body(bnds)
torch.cuda.current_stream().wait_stream(s)
torch.cuda.synchronize()
- cg = torch.cuda.CUDAGraph()
- with torch.cuda.graph(cg, pool=self.pool):
- out = self.body()
+ cgs, x = [], None
+ for si in range(len(bnds)):
+ cg = torch.cuda.CUDAGraph()
+ with torch.cuda.graph(cg, pool=self.pool):
+ x = self.body_seg(si, x, bnds)
+ cgs.append(cg)
finally:
fw._gs = None
- g = self.graphs[(Nb, T)] = (cg, out)
+ g = self.graphs[key] = (cgs, x)
self.stats["captures"] += 1
self.stats["capture_s"] += time.perf_counter() - t_cap
return g
@@ -400,8 +439,8 @@ class GraphDecoder:
futs = self._submit(self._jobs(start, 0, 1, fw.tokens + [int(tok)]))
self._pre = (start, int(tok), futs)
- def stage(self, start, T=1):
- """host side of T tokens: Engram hash + threaded pread of their rows into pinned staging, one H2D each (fw.tokens holds them at start .. start + T - 1)"""
+ def _stage_begin(self, start, T):
+ """host side of a step, part 1: match the prestaged row 0 (token fw.tokens[start]) and hash every (layer, row) still to read"""
fw = self.fw
pre, self._pre = self._pre, None
t0 = 0
@@ -411,16 +450,34 @@ class GraphDecoder:
for f in pre[2]: # stale staged row: its reads still write into the staging rows below
f.result()
pre = None
+ hs = self.stager.hash(fw.tokens, start, t0, T) if self.stager is not None and T > t0 else None
+ self._sp = [start, T, t0, pre, hs]
+
+ def _stage_group(self, a, b):
+ """part 2: 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)"""
+ sp = self._sp
+ start, T, t0, pre, hs = sp
+ fw = self.fw
if self.stager is not None:
- futs = self.stager.stage(fw.tokens, start, t0, T) if T > t0 else []
+ futs = self.stager.submit(hs[0], hs[1], t0, es=range(a, b)) if hs is not None else []
else:
futs = self._submit(self._jobs(start, t0, T, fw.tokens)) if T > t0 else []
- if t0:
- futs += pre[2]
+ if pre is not None:
+ futs = futs + pre[2]
+ sp[3] = None
for f in futs:
f.result()
- self.gs.eng_raw.copy_(self.rpin, non_blocking=True)
- self.gs.eng_valid.copy_(self.vpin, non_blocking=True)
+ 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 stage(self, start, T=1):
+ """host side of T tokens, all layers at once (fw.tokens holds them at start .. start + T - 1)"""
+ self._stage_begin(start, T)
+ self._stage_group(0, self.rpin.shape[0])
def step(self, tok):
"""append host token id `tok` at position fw.n; returns the DEVICE logits [V] of this position (valid until the next step)"""
@@ -449,11 +506,24 @@ class GraphDecoder:
self.hnp[0, :T] = toks
self.hnp[1, :T] = np.arange(start, start + T)
self.gs.inp.copy_(self.hin, non_blocking=True)
- self.stage(start, T)
- cg, _out = self._graph(Nb, T)
+ bnds = self.bounds()
+ g = self.graphs.get((Nb, T, len(bnds)))
+ full = g is None
+ if full: # first use of this (bucket, rows): stage everything, then build the graphs (their warm-up bodies see the real inputs)
+ self.stage(start, T)
+ g = self._graph(Nb, T)
+ cgs, _out = g
self.x_out = _out[2]
fw._h = _out[3]
- cg.replay()
+ grp = self.groups(bnds)
+ if not full:
+ self._stage_begin(start, T)
+ for si, cg in enumerate(cgs):
+ if not full and grp[si] is not None:
+ self._stage_group(*grp[si]) # segment si - 1 is already running on the GPU
+ cg.replay()
+ if si == 0:
+ self.t_launch = time.perf_counter()
self.ev.record()
self.ev_set = True
fw.n += T
diff --git a/tools/hy4/engine.py b/tools/hy4/engine.py
index 104f216..8937711 100644
--- a/tools/hy4/engine.py
+++ b/tools/hy4/engine.py
@@ -256,6 +256,7 @@ class Hy4Engine:
cap0, caps0 = GR.stats["captures"], GR.stats["capture_s"]
lt = [0.0] # time of the last draft launch (set by plan)
td_prev = None
+ busy = [0.0] # host time of the whole verify launch call (includes the staging that overlaps the GPU)
gap = [0.0, 0.0] # host time with the GPU idle: verify result known -> next draft launched, draft tokens known -> verify launched
def plan(y_, hcur_, j_):
@@ -316,7 +317,8 @@ class Hy4Engine:
tm[0] += tb - ta
tm[1] += tc - tb
tm[2] += td - tc
- gap[1] += tc - tb
+ gap[1] += GR.t_launch - tb # draft tokens known -> the verify's first graph launched (the later segments' rows are staged while the GPU runs)
+ busy[0] += tc - tb
acc = 0
nd = len(toks) - 1
while acc < nd and toks[acc + 1] == amh[acc]:
@@ -358,6 +360,7 @@ class Hy4Engine:
stop = on_tokens(new)
st["round_ms"] = [x / max(rounds, 1) * 1000 for x in tm]
st["gap_ms"] = [x / max(rounds, 1) * 1000 for x in gap] # host time per round with the GPU idle: [after verify, before verify]
+ st["busy_ms"] = busy[0] / max(rounds, 1) * 1000
st["captures"] = GR.stats["captures"] - cap0
st["capture_s"] = GR.stats["capture_s"] - caps0
if self.policy is not None:
diff --git a/tools/hy4/spec2/ab2.py b/tools/hy4/spec2/ab2.py
new file mode 100644
index 0000000..beee0e7
--- /dev/null
+++ b/tools/hy4/spec2/ab2.py
@@ -0,0 +1,119 @@
+"""ab2.py: ONE load. Phase 0 exactness + bounds (graph == eager, split == unsplit, bit for bit, T = 1..8, two context buckets), phase 1 precapture cost / memory,
+phase 2 A/B of the host-time levers on 5 texts (old = shipped host path, nosplit = vectorised staging + pipelined draft + prestage, new = + 3-segment graph), equal output md5
+required. Run inside job.sh (box rules)."""
+import hashlib, json, os, statistics, sys, time
+import numpy as np
+tree = os.getcwd()
+sys.path.insert(0, os.path.join(tree, "tools", "hy4"))
+import serve
+serve.apply_env(16384)
+import torch
+from engine import Hy4Engine
+import serve_core as C
+GGUF = "/path/to/models/hy4-flash-gguf/Hy4-flash-Q3_K-00001-of-00002.gguf"
+e = Hy4Engine(tree, GGUF, ctx=16384, k=3)
+e.load(print)
+GR, MG, fw = e.GR, e.MG, e.GR.fw
+STG = GR.stager
+V = C.Vocab(e.meta)
+wiki = json.load(open("/path/to/wiki_ids.json"))
+pc = time.perf_counter
+sync = torch.cuda.synchronize
+free = lambda: torch.cuda.mem_get_info()[0] / 2 ** 30
+def set_arm(a):
+ if a == "old":
+ e.pipe, GR.stager, e.MH._STAGE_OV[0], GR.split = False, None, False, False
+ elif a == "nosplit":
+ e.pipe, GR.stager, e.MH._STAGE_OV[0], GR.split = True, STG, True, False
+ else:
+ e.pipe, GR.stager, e.MH._STAGE_OV[0], GR.split = True, STG, True, True
+
+# ---------------------------------------------------------------- phase 0: exactness
+def eager_rows(toks):
+ """step_rows without the graph: same staging, same static inputs, the body run eagerly"""
+ T, start = len(toks), fw.n
+ if GR.ev_set:
+ GR.ev.synchronize()
+ fw.tokens.extend(int(t) for t in toks)
+ GR.gs.Nb, GR.gs.T = GR.bucket(start, T), T
+ GR.hnp[0, :T] = toks
+ GR.hnp[1, :T] = np.arange(start, start + T)
+ GR.gs.inp.copy_(GR.hin, non_blocking=True)
+ GR.stage(start, T)
+ fw._gs = GR.gs
+ try:
+ out = GR.body(GR.bounds())
+ finally:
+ fw._gs = None
+ fw.n += T
+ GR.expect_n = fw.n
+ return out
+bad = 0
+for ctxn in (200, 700):
+ e._t0 = pc(); e.reset(); e.prefill(wiki[:ctxn]); e.phase("decode")
+ for T in (1, 2, 3, 4, 5, 8):
+ toks = wiki[ctxn:ctxn + T]
+ res = {}
+ for name in ("split", "nosplit", "eager"):
+ set_arm("new" if name != "nosplit" else "nosplit")
+ if name == "eager":
+ out = eager_rows(toks)
+ else:
+ out = GR.step_rows(toks)
+ sync()
+ res[name] = [o.clone() for o in out[:3]]
+ GR.rewind(ctxn)
+ for name in ("nosplit", "eager"):
+ ok = all(torch.equal(a, b) for a, b in zip(res["split"], res[name]))
+ if not ok and name == "nosplit":
+ bad += 1
+ print(f"EXACT ctx {ctxn} T {T} split vs {name}: {'bit-exact' if ok else 'MISMATCH'}", flush=True)
+if bad:
+ print("EXACTNESS FAILED", bad, flush=True); sys.exit(2)
+print("EXACT_OK", flush=True)
+
+# ---------------------------------------------------------------- phase 1: precapture cost + memory
+NBS = [512, 1024, 1536]
+m0, t0 = free(), pc()
+built = []
+for mode in ("new", "nosplit"):
+ set_arm(mode)
+ built += GR.precapture(nbs=NBS)
+nd = MG.precapture(NBS)
+sync()
+print(f"PRECAP {len(built)} verify graphs (both modes) + {nd} draft graphs: {pc() - t0:.1f} s, {m0 - free():.2f} GiB; per verify graph {statistics.mean(x[2] for x in built):.0f} ms; "
+ f"full cap = {len(range(512, GR.cap + 1, 512))} buckets x 8 T x 1 mode ~ {len(range(512, GR.cap + 1, 512)) * 8 * statistics.mean(x[2] for x in built) / 1000:.0f} s, {(m0 - free()) / len(built) * len(range(512, GR.cap + 1, 512)) * 8 / 2:.1f} GiB", flush=True)
+
+# ---------------------------------------------------------------- phase 2: A/B
+WT = V.decode(wiki[3000:3300]); WT2 = V.decode(wiki[9000:9300])
+CODE = open(os.path.join(tree, "tools/hy4/serve_core.py")).read()[:2600]
+chat = lambda t: V.encode(V.template.render([{"role": "user", "content": t}], None, True, reasoning_effort="no_think"))
+texts = {"quote": chat("Here is a passage:\n\n" + WT + "\n\nQuote the three most important sentences verbatim, then summarize in two sentences."),
+ "code": chat("Add a short docstring to every function in this Python file and return the full file.\n\n" + CODE),
+ "chat": chat("Explain how a hash table handles collisions, with a short Python example and the cost of each operation."),
+ "quote2": chat("Here is a passage:\n\n" + WT2 + "\n\nQuote the two most surprising sentences verbatim, then summarize in one sentence."),
+ "chat2": chat("Describe how a B-tree keeps itself balanced during insertions, with a short Python sketch.")}
+N = int(os.environ.get("BN", "120"))
+res = {}
+for i, (pn, ids) in enumerate(texts.items()):
+ seq = ["old", "new", "new", "old", "nosplit", "nosplit"] if i % 2 == 0 else ["new", "old", "old", "new", "nosplit", "nosplit"]
+ first = None
+ for k, arm in enumerate(seq):
+ set_arm(arm)
+ out = []
+ st = e.generate(ids, N, lambda t: out.extend(t) or False)
+ md5 = hashlib.md5(str(out).encode()).hexdigest()[:8]
+ first = first or md5
+ r = dict(text=pn, run=k, arm=arm, cold=(k == 0), tok_s=round(st["decode_tokens"] / st["decode_s"], 2), tau=round(st["tau"], 3), rounds=st["rounds"], md5=md5, same=md5 == first,
+ round_ms=[round(x, 1) for x in st["round_ms"]], gap_ms=[round(x, 2) for x in st["gap_ms"]], busy_ms=round(st["busy_ms"], 2), caps=st["captures"])
+ res.setdefault(arm, []).append(r)
+ print("RES", json.dumps(r), flush=True)
+for arm in ("old", "nosplit", "new"):
+ rs = res[arm]
+ f = lambda sel, key: round(statistics.mean(sel(x)[key] if isinstance(key, str) else sel(x)[key[0]][key[1]] for x in rs if sel(x) is not None), 2) if rs else None
+ for lab, sub in (("all", rs), ("cold", [x for x in rs if x["cold"]]), ("warm", [x for x in rs if not x["cold"]])):
+ if sub:
+ print("MEAN", arm, lab, "tok_s", round(statistics.mean(x["tok_s"] for x in sub), 2), "gap_ms", [round(statistics.mean(x["gap_ms"][j] for x in sub), 2) for j in (0, 1)], "busy_ms",
+ round(statistics.mean(x["busy_ms"] for x in sub), 2), "verify_wait_ms", round(statistics.mean(x["round_ms"][2] for x in sub), 1), flush=True)
+print("md5 all equal:", all(x["same"] for a in res.values() for x in a), flush=True)
+print("AB2_DONE", flush=True)
diff --git a/tools/hy4/spec2/host_prof.py b/tools/hy4/spec2/host_prof.py
index dd2dd58..aa7a34f 100644
--- a/tools/hy4/spec2/host_prof.py
+++ b/tools/hy4/spec2/host_prof.py
@@ -65,9 +65,11 @@ N = int(os.environ.get("BN", "120"))
STG = GR.stager
def set_arm(a):
if a == "old":
- e.pipe, GR.stager, e.MH._STAGE_OV[0] = False, None, False
+ e.pipe, GR.stager, e.MH._STAGE_OV[0], GR.split = False, None, False, False
+ elif a == "nosplit":
+ e.pipe, GR.stager, e.MH._STAGE_OV[0], GR.split = True, STG, True, False
else:
- e.pipe, GR.stager, e.MH._STAGE_OV[0] = True, STG, True
+ e.pipe, GR.stager, e.MH._STAGE_OV[0], GR.split = True, STG, True, True
def q(v, p):
s = sorted(v); return s[min(len(s) - 1, int(p * len(s)))]
def summ(v):
@@ -81,7 +83,7 @@ def run(tag, arm, pn, ids):
st = e.generate(ids, N, cb)
gaps = [(b - a) * 1000 for a, b in zip(stamps[1:], stamps[2:])]
thr = 150.0
- print(f"RUN {tag} arm={arm} {pn} tok_s {st['decode_tokens'] / st['decode_s']:.2f} tau {st['tau']:.3f} rounds {st['rounds']} md5 {hashlib.md5(str(out).encode()).hexdigest()[:8]} round_ms {[round(x, 1) for x in st['round_ms']]} gap_ms {[round(x, 2) for x in st.get('gap_ms', [])]} caps {st.get('captures')} cap_s {st.get('capture_s', 0):.1f}", flush=True)
+ print(f"RUN {tag} arm={arm} {pn} tok_s {st['decode_tokens'] / st['decode_s']:.2f} tau {st['tau']:.3f} rounds {st['rounds']} md5 {hashlib.md5(str(out).encode()).hexdigest()[:8]} round_ms {[round(x, 1) for x in st['round_ms']]} gap_ms {[round(x, 2) for x in st.get('gap_ms', [])]} busy {st.get('busy_ms', 0):.2f} caps {st.get('captures')} cap_s {st.get('capture_s', 0):.1f}", flush=True)
print(f" read_bytes {(rbytes() - rb0) / 1e6:.1f} MB; steady step_rows {summ([x for x in REC['step_rows'] if x < thr])}; stage {summ([x for x in REC.get('stage', []) if x < thr])}; hash {summ(REC.get('hash', []))}; submit {summ(REC.get('submit', []))}; ng_propose {summ(REC.get('ng_propose', []))}; ng_add {summ(REC.get('ng_add', []))}; round wall {summ([g for g in gaps if g < 450])}; capture keys {CAPKEYS}", flush=True)
return out
for pn in PA:
diff --git a/tools/hy4/spec2/read_bench.py b/tools/hy4/spec2/read_bench.py
new file mode 100644
index 0000000..48972e5
--- /dev/null
+++ b/tools/hy4/spec2/read_bench.py
@@ -0,0 +1,40 @@
+"""CPU-only: cost of the Engram row reads of one verify round (4 layers x T rows x 16 columns of 99-byte rows from the 65 GB table in the GGUF), cold random rows,
+per strategy. Run from the tree root with the engine venv; no GPU."""
+import os, sys, time, types, statistics
+import numpy as np
+tree = os.getcwd()
+for n, sub in (("exllamav3", ""), ("exllamav3.loader", "loader")):
+ m = types.ModuleType(n); m.__path__ = [os.path.join(tree, "exllamav3", sub)]; sys.modules[n] = m
+from concurrent.futures import ThreadPoolExecutor
+from exllamav3.loader.gguf_collection import GGUFCollection
+from exllamav3.loader.engram_rows import F8Rows
+from exllamav3.loader import engram_stage as ES
+g = GGUFCollection("/path/to/models/hy4-flash-gguf/Hy4-flash-Q3_K-00001-of-00002.gguf")
+tab = F8Rows(g)
+print("table rows", tab.rows, "row_bytes", tab.row_bytes, flush=True)
+nE, TM, nc, T = 4, 8, 16, int(os.environ.get("T", "4"))
+rng = np.random.default_rng(5)
+mods = [types.SimpleNamespace(e=i, n_gram=3, n_head=8, n_cols=16, token_map=[0, 1], pad_id=0, mult=[1, 2, 3], primes=[5] * 16, offs=[0] * 16) for i in range(nE)]
+rnp = np.zeros((nE, TM, nc, tab.row_bytes), dtype=np.uint8); vnp = np.zeros((nE, TM, nc), dtype=np.float32)
+def q(v, p): s = sorted(v); return s[min(len(s) - 1, int(p * len(s)))]
+for name, workers, pool_n, inline in (("pool64 old-like (chunks of 4)", 64, 64, 0), ("4 workers", 4, 8, 0), ("8 workers", 8, 8, 0), ("16 workers", 16, 16, 0), ("32 workers", 32, 32, 0), ("inline", 1, 0, 10 ** 9)):
+ pool = ThreadPoolExecutor(max_workers=pool_n) if pool_n else None
+ st = ES.EngramStager(mods, tab, rnp, vnp, pool=pool, workers=workers)
+ st.inline_max = inline
+ ts = []
+ for r in range(int(os.environ.get("ROUNDS", "150"))):
+ ids = rng.integers(0, tab.rows, size=(nE, T, nc))
+ t = time.perf_counter()
+ for f in st.submit(ids, np.ones(T, dtype=np.float32), 0):
+ f.result()
+ ts.append((time.perf_counter() - t) * 1000)
+ print(f"{name:32s} cold random rows: med {statistics.median(ts):.2f} p90 {q(ts, .9):.2f} max {max(ts):.2f} ms", flush=True)
+ ids = rng.integers(0, tab.rows, size=(nE, T, nc))
+ st.submit(ids, np.ones(T, dtype=np.float32), 0)
+ ts = []
+ for r in range(50):
+ t = time.perf_counter()
+ for f in st.submit(ids, np.ones(T, dtype=np.float32), 0):
+ f.result()
+ ts.append((time.perf_counter() - t) * 1000)
+ print(f"{name:32s} warm same rows: med {statistics.median(ts):.2f} p90 {q(ts, .9):.2f} max {max(ts):.2f} ms", flush=True)
diff --git a/tools/hy4/spec2/read_bench2.py b/tools/hy4/spec2/read_bench2.py
new file mode 100644
index 0000000..a98cbd8
--- /dev/null
+++ b/tools/hy4/spec2/read_bench2.py
@@ -0,0 +1,79 @@
+"""CPU-only: cold random Engram row reads, strategies (readahead off, O_DIRECT, RWF_NOWAIT hybrid). Tree root, engine venv, no GPU."""
+import os, sys, time, types, statistics, mmap
+import numpy as np
+tree = os.getcwd()
+for n, sub in (("exllamav3", ""), ("exllamav3.loader", "loader")):
+ m = types.ModuleType(n); m.__path__ = [os.path.join(tree, "exllamav3", sub)]; sys.modules[n] = m
+from concurrent.futures import ThreadPoolExecutor
+from exllamav3.loader.gguf_collection import GGUFCollection
+from exllamav3.loader.engram_rows import F8Rows
+g = GGUFCollection("/path/to/models/hy4-flash-gguf/Hy4-flash-Q3_K-00001-of-00002.gguf")
+tab = F8Rows(g)
+fi = tab.off >> 48
+o0 = g.bases[fi] + (tab.off & ((1 << 48) - 1)); rb = tab.row_bytes; rows = tab.rows
+path = os.readlink(f"/proc/self/fd/{g.fds[fi]}")
+print("path", path, flush=True)
+N = int(os.environ.get("N", "256")); R = int(os.environ.get("ROUNDS", "150"))
+rng = np.random.default_rng(11)
+out = np.zeros((N, rb), dtype=np.uint8)
+mvs = [memoryview(out[i]) for i in range(N)]
+def q(v, p): s = sorted(v); return s[min(len(s) - 1, int(p * len(s)))]
+fd_buf = os.open(path, os.O_RDONLY)
+fd_rand = os.open(path, os.O_RDONLY); os.posix_fadvise(fd_rand, 0, 0, os.POSIX_FADV_RANDOM)
+fd_dir = os.open(path, os.O_RDONLY | os.O_DIRECT)
+class A: # aligned 4 KB buffers per thread slot
+ pass
+bufs = [mmap.mmap(-1, 4096) for _ in range(N)]
+def rd_buf(fd, idxs, pos):
+ for i in idxs:
+ os.preadv(fd, [mvs[i]], int(pos[i]))
+def rd_dir(idxs, pos):
+ for i in idxs:
+ p = int(pos[i]); a = p & ~4095
+ os.preadv(fd_dir, [bufs[i]], a)
+ out[i] = np.frombuffer(bufs[i], dtype=np.uint8, count=rb, offset=p - a) if (p - a) + rb <= 4096 else 0
+def rd_nowait(idxs, pos, miss):
+ for i in idxs:
+ try:
+ os.preadv(fd_buf, [mvs[i]], int(pos[i]), os.RWF_NOWAIT)
+ except BlockingIOError:
+ miss.append(i)
+def run(name, fn, rounds=R):
+ ts = []
+ for r in range(rounds):
+ pos = o0 + rng.integers(0, rows, size=N) * rb
+ t = time.perf_counter(); fn(pos); ts.append((time.perf_counter() - t) * 1000)
+ print(f"{name:40s} cold: med {statistics.median(ts):.2f} p90 {q(ts, .9):.2f} max {max(ts):.2f} ms", flush=True)
+def pooled(fd, W, pool):
+ def f(pos):
+ per = -(-N // W)
+ fs = [pool.submit(rd_buf, fd, range(a, min(N, a + per)), pos) for a in range(per, N, per)]
+ rd_buf(fd, range(0, min(N, per)), pos)
+ for x in fs: x.result()
+ return f
+for W in (64, 128, 256):
+ pool = ThreadPoolExecutor(max_workers=W)
+ run(f"buffered {W} workers", pooled(fd_buf, W, pool))
+ run(f"fadvise RANDOM {W} workers", pooled(fd_rand, W, pool))
+ def fdir(pos, W=W, pool=pool):
+ per = -(-N // W)
+ fs = [pool.submit(rd_dir, range(a, min(N, a + per)), pos) for a in range(per, N, per)]
+ rd_dir(range(0, min(N, per)), pos)
+ for x in fs: x.result()
+ run(f"O_DIRECT 4K {W} workers", fdir)
+pool = ThreadPoolExecutor(max_workers=128)
+def hyb(pos):
+ miss = []
+ rd_nowait(range(N), pos, miss)
+ if miss:
+ W = 128; per = max(1, -(-len(miss) // W))
+ fs = [pool.submit(rd_buf, fd_rand, miss[a:a + per], pos) for a in range(per, len(miss), per)]
+ rd_buf(fd_rand, miss[:per], pos)
+ for x in fs: x.result()
+run("NOWAIT + RANDOM 128 (cold)", hyb)
+pos = o0 + rng.integers(0, rows, size=N) * rb
+hyb(pos)
+ts = []
+for r in range(100):
+ t = time.perf_counter(); hyb(pos); ts.append((time.perf_counter() - t) * 1000)
+print(f"NOWAIT hybrid warm same rows: med {statistics.median(ts):.2f} p90 {q(ts, .9):.2f} max {max(ts):.2f} ms")
diff --git a/tools/hy4/spec2/test_stage.py b/tools/hy4/spec2/test_stage.py
index 21ce232..62f167c 100644
--- a/tools/hy4/spec2/test_stage.py
+++ b/tools/hy4/spec2/test_stage.py
@@ -17,7 +17,7 @@ NC = (NG - 1) * NH
def make_mods(rng, nE, vocab, rows):
tm = [rng.choice([-1, rng.randrange(0, 5000)]) if rng.random() < 0.1 else rng.randrange(0, 5000) for _ in range(vocab)]
pad_id = next(i for i, x in enumerate(tm) if x != -1)
- mods = []
+ mods, top = [], 0
for e in range(nE):
primes = [rng.randrange(rows // 40, rows // 20) | 1 for _ in range(NC)]
offs = [0] * NC
@@ -26,7 +26,8 @@ def make_mods(rng, nE, vocab, rows):
offs[c] = acc; acc += primes[c]
mods.append(types.SimpleNamespace(e=e, n_gram=NG, n_head=NH, n_cols=NC, token_map=tm, pad_id=pad_id,
mult=[rng.getrandbits(64) | 1 for _ in range(NG)], primes=primes, offs=offs))
- return mods, acc
+ top = max(top, acc)
+ return mods, top
def make_table(path, rows, rb, rng, shard_off=4096):
data = np.frombuffer(bytes(rng.getrandbits(8) for _ in range(rows * rb)), dtype=np.uint8)
@@ -62,7 +63,7 @@ def test_hash_matches_reference():
assert np.array_equal(ids, ids2) and np.array_equal(valid, valid2)
print("hash == engram_hash: ok")
-def run_reads(workers, inline):
+def run_reads(workers, nowait, force_miss):
rng = random.Random(7)
nE, rb, TM = 4, 99, 8
mods, tot = make_mods(rng, nE, 3000, 400000)
@@ -72,7 +73,7 @@ def run_reads(workers, inline):
for trial in range(40):
rnp = np.full((nE, TM, NC, rb), 0xCD, dtype=np.uint8); vnp = np.full((nE, TM, NC), -7.0, dtype=np.float32)
st = ES.EngramStager(mods, tab, rnp, vnp, pool=pool, workers=workers)
- st.inline_max = inline
+ st.nowait, st.force_miss = nowait, force_miss
n = rng.randrange(3, 50)
hist = [rng.randrange(0, 3000) for _ in range(n)]
T = rng.randrange(1, TM + 1); start = n - 1; hist = hist + [rng.randrange(0, 3000) for _ in range(T)]
@@ -86,10 +87,31 @@ def run_reads(workers, inline):
assert (vnp[e, t0 + t] == valid[t]).all()
assert (rnp[:, :t0] == 0xCD).all() and (rnp[:, T:] == 0xCD).all() # canary: rows outside the staged range are untouched
assert (vnp[:, :t0] == -7.0).all() and (vnp[:, T:] == -7.0).all()
- print(f"reads == table rows (workers {workers}, inline {inline}): ok")
+ print(f"reads == table rows (workers {workers}, nowait {nowait}, force_miss {force_miss}): ok")
+
+def test_groups():
+ """reading the layers in two groups (as the split graph does) gives the same staging as one pass; layers outside a group are untouched by that call"""
+ rng = random.Random(9)
+ nE, rb, TM = 4, 96, 8
+ mods, tot = make_mods(rng, nE, 3000, 400000)
+ with tempfile.TemporaryDirectory() as d:
+ tab, data = make_table(os.path.join(d, "t.bin"), tot, rb, rng)
+ pool = ThreadPoolExecutor(max_workers=8)
+ for fm in (False, True):
+ rnp = np.full((nE, TM, NC, rb), 0xCD, dtype=np.uint8); vnp = np.full((nE, TM, NC), -7.0, dtype=np.float32)
+ st = ES.EngramStager(mods, tab, rnp, vnp, pool=pool, workers=8); st.force_miss = fm
+ hist = [rng.randrange(0, 3000) for _ in range(30)]
+ ids, valid = st.hash(hist, 20, 0, 5)
+ for f in st.submit(ids, valid, 0, es=range(0, 1)): f.result()
+ assert (rnp[1:] == 0xCD).all() and (vnp[1:] == -7.0).all()
+ for f in st.submit(ids, valid, 0, es=range(1, 4)): f.result()
+ for e in range(nE):
+ for t in range(5):
+ assert np.array_equal(rnp[e, t], data[ids[e, t]])
+ print("layer groups: ok")
def test_reads():
- run_reads(1, 0); run_reads(4, 0); run_reads(4, 10 ** 9); run_reads(8, 0)
+ run_reads(1, False, False); run_reads(4, False, False); run_reads(4, True, False); run_reads(4, True, True); run_reads(64, True, True); run_reads(1, True, True)
def test_bounds():
rng = random.Random(3)
@@ -139,5 +161,5 @@ def test_bucket():
print("bucket: ok")
if __name__ == "__main__":
- test_hash_matches_reference(); test_reads(); test_bounds(); test_bucket()
+ test_hash_matches_reference(); test_reads(); test_groups(); test_bounds(); test_bucket()
print("ALL_OK")