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.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
Hy4 spec2: vectorised Engram staging, next-round draft launched before the host bookkeeping, row 0 prestaged, graph bucket API (bucket / graph / precapture), host-time probes and CPU tests
YanissAmz94bd2cf78512
diff --git a/exllamav3/loader/engram_stage.py b/exllamav3/loader/engram_stage.pynew file mode 100644index 0000000..16af008--- /dev/null+++ b/exllamav3/loader/engram_stage.py@@ -0,0 +1,118 @@+"""Host staging of the Engram rows of a graph step (HY4_GRAPH), vectorised.++The graph step reads its Engram rows from static device buffers (eng_raw / eng_valid) that the host fills before every replay: for every Engram layer e, every+verify row t and every column c the id of the row in the (65 GB, file resident) table is a hash of the last n_gram token ids, the bytes are pread into pinned+staging, one H2D each. step_graph.GraphDecoder used a Python hash per (layer, row) and one future per ~4 reads; here++ * ONE numpy pass hashes every (layer, row, column) of the step (uint64 arithmetic wraps exactly like the `& MASK64` of engram_rows.engram_hash),+ * the id bounds are checked in one vectorised test (a bad id would read the next tensor of the file),+ * reads go to cached memoryviews of the pinned staging, a few big chunks (the calling thread takes one itself: no hand-off for small steps).++Generic: nothing is keyed on a model name; every parameter comes from the Hy4EngramGPU modules.+"""+from __future__ import annotations+import os+from concurrent.futures import ThreadPoolExecutor++import numpy as np++MASK64 = (1 << 64) - 1+++class EngramStager:+ """mods: Hy4EngramGPU modules (index e = mod.e), table: F8Rows, rpin [nE, TM, nc, rb] uint8 pinned, vpin [nE, TM, nc] float32 pinned (host views)"""++ def __init__(self, mods, table, rnp: np.ndarray, vnp: np.ndarray, pool: ThreadPoolExecutor | None = None, workers: int | None = None):+ self.mods = sorted(mods, key=lambda m: m.e)+ m0 = self.mods[0]+ self.nE = len(self.mods)+ assert [m.e for m in self.mods] == list(range(self.nE))+ self.ng, self.nh, self.nc = m0.n_gram, m0.n_head, m0.n_cols+ self.table = table+ self.rnp, self.vnp = rnp, vnp+ self.TM = rnp.shape[1]+ assert rnp.shape == (self.nE, self.TM, self.nc, table.row_bytes) and vnp.shape == (self.nE, self.TM, self.nc)+ tm = np.asarray(list(m0.token_map), dtype=np.int64)+ self.tm, self.pad = tm, int(tm[m0.pad_id])+ for m in self.mods: # one token map / pad for every module (the hash below shares them)+ assert m.pad_id == m0.pad_id and m.n_gram == self.ng and m.n_head == self.nh+ self.mult = np.array([[int(x) & MASK64 for x in m.mult] for m in self.mods], dtype=np.uint64) # [nE, ng]+ self.primes = np.array([[int(x) for x in m.primes] for m in self.mods], dtype=np.uint64) # [nE, nc]+ self.offs = np.array([[int(x) for x in m.offs] for m in self.mods], dtype=np.int64) # [nE, nc]+ tab = table+ fi = tab.off >> 48+ 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++ # -- hash ----------------------------------------------------------------------------------------------------------------------------+ @staticmethod+ def window(tokens, lo: int, hi: int, extra=()):+ """token ids at positions lo .. hi - 1 (-1 before the sequence start); positions past len(tokens) come from `extra`"""+ n = len(tokens)+ seg = [-1] * max(0, -lo) + list(tokens[max(lo, 0):min(hi, n)])+ if hi > n:+ seg += list(extra)[max(0, max(lo, n) - n):hi - n]+ if len(seg) != hi - lo:+ raise IndexError(f"token history too short: need positions {lo}..{hi - 1}, have {n} + {len(extra)}")+ return np.asarray(seg, dtype=np.int64)++ def hash(self, tokens, start: int, t0: int, t1: int, extra=()):+ """positions start + t for t in [t0, t1): -> (ids int64 [nE, T, nc], valid float32 [T]) with T = t1 - t0. `tokens` (+ `extra`) holds the history through start + t1 - 1."""+ T, ng = t1 - t0, self.ng+ a = self.window(tokens, start + t0 - (ng - 1), start + t1, extra)+ n_tm = len(self.tm)+ ok = (a >= 0) & (a < n_tm)+ c = np.where(ok, self.tm[np.where(ok, a, 0)], -1) # class id, -1 = not in the map / before the sequence start+ # window[t, s] = class of the token at position start + t0 + t - s+ idx = np.arange(T)[:, None] + (ng - 1) - np.arange(ng)[None, :]+ w = c[idx]+ dead = w[:, 0] == -1+ w = np.where(w == -1, self.pad, w).astype(np.uint64)+ prod = w[None] * self.mult[:, None, :] # [nE, T, ng], wraps mod 2^64+ ids = np.empty((self.nE, T, self.nc), dtype=np.int64)+ r = prod[:, :, 0].copy()+ for o in range(1, ng):+ r ^= prod[:, :, o]+ sl = slice((o - 1) * self.nh, o * self.nh)+ ids[:, :, sl] = (r[:, :, None] % self.primes[:, None, sl]).astype(np.int64) + self.offs[:, None, sl]+ return ids, np.where(dead, 0.0, 1.0).astype(np.float32)++ # -- reads ---------------------------------------------------------------------------------------------------------------------------+ def _view(self, e, t, c):+ v = self.views.get((e, t, c))+ if v is None:+ v = self.views[(e, t, c)] = memoryview(self.rnp[e, t, c])+ return v++ def _read(self, items):+ fd, o0, rb = self.fd, 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}")++ 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)"""+ T = ids.shape[1]+ if ids.size and (int(ids.min()) < 0 or int(ids.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:+ self._read(items)+ return []+ per = -(-n // self.workers)+ chunks = [items[a:a + per] for a in range(0, n, per)]+ futs = [self.pool.submit(self._read, ch) for ch in chunks[1:]]+ self._read(chunks[0])+ return futs++ def stage(self, tokens, start: int, t0: int, t1: int, extra=()):+ ids, valid = self.hash(tokens, start, t0, t1, extra)+ return self.submit(ids, valid, t0)diff --git a/exllamav3/loader/mtp_head.py b/exllamav3/loader/mtp_head.pyindex 9a10024..ffa6362 100644--- a/exllamav3/loader/mtp_head.py+++ b/exllamav3/loader/mtp_head.py@@ -248,6 +248,17 @@ class MTPGraph:g = self.graphs[N] = (cg, out)return g+ def precapture(self, ns=None):+ """capture the draft graph of every context bucket now (default: every bucket up to the cap); -> number built"""+ mt = self.mt+ ns = sorted(set(ns)) if ns is not None else list(range(self.BUCKET, mt.cap + 1, self.BUCKET))+ built = 0+ for N in ns:+ if N not in self.graphs:+ self._graph(N)+ built += 1+ return built+def run(self, tok, h, j):"""tok: host int (the token of the pair, x_{j+1}), h: device [1, D] trunk state h_j, j: head position -> device tensor [k] of drafts"""mt = self.mtdiff --git a/exllamav3/loader/step_graph.py b/exllamav3/loader/step_graph.pyindex 5cd5570..067f946 100644--- a/exllamav3/loader/step_graph.py+++ b/exllamav3/loader/step_graph.py@@ -22,6 +22,7 @@ import torchfrom . import step_nosync as _nsfrom .engram_rows import QB, E4M3, E8M0from . import attn_eager as _ae+from .engram_stage import EngramStagerBUCKET = int(os.environ.get("HY4_GRAPH_BUCKET", "512"))TM = int(os.environ.get("HY4_GRAPH_TM", "8")) # max rows of one graph step (verify rows)@@ -29,6 +30,7 @@ MASK64 = (1 << 64) - 1PERT = 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)+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# ---------------------------------------------------------------------------------------------------- static indexer@@ -202,7 +204,10 @@ class GraphDecoder:self.prepared = Falseself.expect_n = Noneself.hin = torch.zeros(2, TM, dtype=torch.long).pin_memory()- self.stats = {"captures": 0, "replays": 0}+ self.hnp = self.hin.numpy()+ self.stager = None+ self._pre = None+ self.stats = {"captures": 0, "replays": 0, "capture_s": 0.0}self.ev = torch.cuda.Event()self.ev_set = False@@ -240,6 +245,8 @@ class GraphDecoder:self.vpin = torch.zeros(nE, TM, nc, dtype=torch.float32).pin_memory()self.rnp = self.rpin.numpy()self._rmv = None+ if STAGE_VEC:+ self.stager = EngramStager([fw.eng[i] for i in sorted(fw.ple)], fw.table, self.rnp, self.vpin.numpy(), pool=_POOL)for i in range(fw.n_layers):if fw._layer(i).ix:indexer_static_init(fw._indexer_fused(i), self.cap)@@ -257,6 +264,7 @@ class GraphDecoder:"""new sequence: zero the static state (buffers keep their addresses so captured graphs stay valid)"""fw = self.fwself.expect_n = None+ self._drain_pre()for b in self.st.kv.values():b.zero_()for ix in getattr(fw, "ixf", {}).values():@@ -281,10 +289,44 @@ class GraphDecoder:fw._ns_dev = Falsereturn lg, torch.argmax(lg, -1), x, fw._h+ 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)++ def graph(self, Nb, T=1):+ """the captured (graph, outputs) of a T-row step at context bucket Nb (captured now if not yet). Row-generic: T = rows of ONE sequence (verify) or any+ batch of rows that the body maps onto positions (inp[1, :T])."""+ return self._graph(Nb, T)++ def precapture(self, nbs=None, ts=None, progress=None):+ """capture every (Nb, T) graph now (a capture inside a decode round costs 2 eager bodies + the capture: 0.5 - 1 s of host time that lands in one round).+ nbs: iterable of buckets (default every bucket up to the cap), ts: row counts (default 1 .. TM). Returns [(Nb, T, ms)] of the graphs built. The static+ inputs keep their last values: call it between requests (the K / indexer rows it rewrites are the same ones the last step wrote) and reset() after."""+ import time+ nbs = sorted(set(nbs)) if nbs is not None else list(range(BUCKET, self.cap + 1, BUCKET))+ ts = sorted(set(ts)) if ts is not None else list(range(1, TM + 1))+ if not self.prepared:+ self.prepare()+ out = []+ for T in ts:+ assert 1 <= T <= TM+ for Nb in nbs:+ assert Nb % BUCKET == 0 and Nb <= self.cap+ if (Nb, T) in self.graphs:+ continue+ t = time.perf_counter()+ self._graph(Nb, T)+ out.append((Nb, T, round((time.perf_counter() - t) * 1000)))+ if progress:+ progress(f"graph Nb={Nb} T={T} {out[-1][2]} ms")+ return out+def _graph(self, Nb, T=1):g = self.graphs.get((Nb, T))if g is not None:return g+ import time+ t_cap = time.perf_counter()fw, gs = self.fw, self.gsgs.Nb, gs.T = Nb, Tfw._gs = gs@@ -303,6 +345,7 @@ class GraphDecoder:fw._gs = Noneg = self.graphs[(Nb, T)] = (cg, out)self.stats["captures"] += 1+ self.stats["capture_s"] += time.perf_counter() - t_capreturn gdef _jobs(self, start, t0, t1, toks):@@ -337,23 +380,41 @@ class GraphDecoder:per = max(1, -(-len(jobs) // _IO_W))return [_POOL.submit(rd, jobs[a:a + per]) for a in range(0, len(jobs), per)]+ def _drain_pre(self):+ """wait for the reads of a staged row that was never used (they write into the shared pinned staging)"""+ pre, self._pre = self._pre, None+ if pre is not None:+ for f in pre[2]:+ f.result()+def prestage(self, tok):"""HY4_STAGE_OV: row 0 of the next verify (token tok at position fw.n) does not depend on the drafts: start its Engram reads now, while the draft chain runs on the GPU"""fw = self.fw+ self._drain_pre()if self.ev_set:self.ev.synchronize() # the previous replay has finished reading the pinned staging rowsstart = fw.n- jobs = self._jobs(start, 0, 1, fw.tokens + [int(tok)])- self._pre = (start, int(tok), self._submit(jobs))+ if self.stager is not None:+ futs = self.stager.stage(fw.tokens, start, 0, 1, extra=[int(tok)])+ else:+ 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)"""fw = self.fw- pre, self._pre = getattr(self, "_pre", None), None+ pre, self._pre = self._pre, Nonet0 = 0if pre is not None and pre[0] == start and pre[1] == fw.tokens[start]:t0 = 1- futs = self._submit(self._jobs(start, t0, T, fw.tokens)) if T > t0 else []+ elif pre is not None:+ for f in pre[2]: # stale staged row: its reads still write into the staging rows below+ f.result()+ pre = None+ if self.stager is not None:+ futs = self.stager.stage(fw.tokens, start, t0, T) if T > t0 else []+ else:+ futs = self._submit(self._jobs(start, t0, T, fw.tokens)) if T > t0 else []if t0:futs += pre[2]for f in futs:@@ -383,10 +444,10 @@ class GraphDecoder:if self.ev_set:self.ev.synchronize() # the previous replay has read the pinned staging buffers: safe to overwrite themfw.tokens.extend(int(t) for t in toks)- Nb = min(self.cap, ((start + T - 1) // BUCKET + 1) * BUCKET)+ Nb = self.bucket(start, T)self.gs.Nb = Nb- self.hin[0, :T] = torch.tensor([int(t) for t in toks])- self.hin[1, :T] = torch.arange(start, start + T)+ 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)diff --git a/tools/hy4/engine.py b/tools/hy4/engine.pyindex ec05f7e..104f216 100644--- a/tools/hy4/engine.py+++ b/tools/hy4/engine.py@@ -41,6 +41,7 @@ class Hy4Engine:self.ngram_fill = os.environ.get("HY4_NGRAM_FILL", "0") == "1"self.ngram_long = int(os.environ.get("HY4_NGRAM_LONG", "0")) # >= 1: a match of at least this many tokens REPLACES the MTP draft chain (verify y + up to TM - 1 copied tokens; the draft cache is refilled from the trunk states); 0 = offself._tune = None # torch.cuda.tunable module while a frozen TunableOp results file is loaded (HY4_TUNABLEOP_FILE)+ self.pipe = os.environ.get("HY4_PIPE", "1") == "1" # start the next round's draft before the host bookkeeping of this round (host-only reorder, same tokens)self.policy = Noneif os.environ.get("HY4_DRAFT_POLICY", "0") == "1":from draft_policy import CostPolicy@@ -130,9 +131,22 @@ class Hy4Engine:ids = [(i * 7919 + 13) % 50000 for i in range(n)]t0 = time.perf_counter()self.generate(ids, 8, lambda toks: False)+ spec = os.environ.get("HY4_PRECAPTURE", "0")+ if spec != "0":+ self.precapture(spec)self.reset()print(f"warm-up {n} tokens: {time.perf_counter() - t0:.1f} s", flush=True)+ def precapture(self, spec: str = "all", progress=print):+ """build the decode graphs now instead of inside a decode round (a build = 2 eager bodies + the capture, 0.5 - 1 s of host time): spec = "all" (every context+ bucket up to the cap, T = 1 .. TM, plus every draft bucket) or "T1,T2,.." (those verify row counts; "all" buckets). Call between requests, reset() after."""+ t0 = time.perf_counter()+ ts = None if spec in ("all", "1") else [int(x) for x in spec.split(",") if x]+ built = self.GR.precapture(ts=ts)+ nb = self.MG.precapture()+ free = self.torch.cuda.mem_get_info()[0] / 2 ** 30+ progress(f"precapture: {len(built)} verify graphs ({sum(x[2] for x in built) / 1000:.1f} s), {nb} draft graphs, {time.perf_counter() - t0:.1f} s, {free:.1f} GiB free")+# ------------------------------------------------------------------------------------------ request statedef reset(self):M, GR = self.M, self.GR@@ -238,18 +252,40 @@ class Hy4Engine:self.policy.reset_stats()n_ext = n_hit = n_extacc = n_long = 0rate, since = 0.7, 0 # recent acceptance of the extra rows; below 0.4 the proposer pauses (a probe every 8 rounds)+ stage_ov = self.MH._STAGE_OV[0]+ cap0, caps0 = GR.stats["captures"], GR.stats["capture_s"]+ lt = [0.0] # time of the last draft launch (set by plan)+ td_prev = None+ 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_):+ """the next round's draft, started BEFORE the host bookkeeping of this round: the n-gram long-match test (a long match replaces the chain) or the draft+ launch (async: its tokens are read at the top of the round) + the Engram reads of verify row 0 (they do not depend on the drafts)"""+ skip_, cl_, dd_ = False, [], None+ if ng is not None and self.ngram_long > 0:+ cl_, ml_ = ng.propose([], self.SG.TM - 1)+ skip_ = bool(cl_) and ml_ >= self.ngram_long+ if not skip_:+ dd_ = MG.run(y_, hcur_, j_)+ lt[0] = pc()+ if stage_ov:+ GR.prestage(y_)+ return skip_, cl_, dd_++ planned = Falsewhile out_n < max_new and not stop and not cancel():j = GR.fw.n - 1ta = pc()- skip = False- if ng is not None and self.ngram_long > 0:- cl, ml = ng.propose([], self.SG.TM - 1)- skip = bool(cl) and ml >= self.ngram_long+ if not planned:+ skip, cl, dd = plan(y, hcur, j)+ planned = False+ if td_prev is not None and not skip:+ gap[0] += lt[0] - td_previf skip:d, ext = [], cltb = pc()else:- d = MG.run(y, hcur, j).tolist()+ d = dd.tolist()confs = Noneif self.MH.CONF: # the draft graph appended the k confidences (fixed point 2^-20)confs = [c / 1048576.0 for c in d[k:]]@@ -280,6 +316,7 @@ class Hy4Engine:tm[0] += tb - tatm[1] += tc - tbtm[2] += td - tc+ gap[1] += tc - tbacc = 0nd = len(toks) - 1while acc < nd and toks[acc + 1] == amh[acc]:@@ -308,14 +345,21 @@ class Hy4Engine:if ng is not None:ng.add(new)y, hcur = amh[acc], hv[acc:acc + 1]- hist[acc] += 1- rounds += 1room = max_new - out_nif len(new) > room:new = new[:room]+ if self.pipe and out_n + len(new) < max_new:+ skip, cl, dd = plan(y, hcur, GR.fw.n - 1)+ planned = True+ td_prev = td+ hist[acc] += 1+ rounds += 1out_n += len(new)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["captures"] = GR.stats["captures"] - cap0+ st["capture_s"] = GR.stats["capture_s"] - caps0if self.policy is not None:st["policy"] = self.policy.stats()st["ngram"] = {"ext": self.ngram_ext, "min": self.ngram_min, "fill": self.ngram_fill, "hit_rounds": n_hit, "ext_rows": n_ext, "ext_accepted": n_extacc, "long": self.ngram_long, "long_rounds": n_long}diff --git a/tools/hy4/spec2/host_prof.py b/tools/hy4/spec2/host_prof.pynew file mode 100644index 0000000..dd2dd58--- /dev/null+++ b/tools/hy4/spec2/host_prof.py@@ -0,0 +1,94 @@+"""host_prof.py: where the host time of a speculative round goes (box, ONE load, run inside job.sh). Wraps the decoder's host steps with timers and prints, per run,+captures (lazy graph builds inside the run) and per-round medians / p90 / max of: draft launch+wait, step_rows total, stage parts (hash, submit, pread wait, H2D), replay launch,+and the round wall time (gap between on_tokens calls)."""+import hashlib, json, os, statistics, sys, time+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 = e.GR, e.MG+V = C.Vocab(e.meta)+wiki = json.load(open("/path/to/wiki_ids.json"))+pc = time.perf_counter+REC = {}+def rec(k, v):+ REC.setdefault(k, []).append(v)+def wrap(obj, name, key):+ f = getattr(obj, name)+ def w(*a, **kw):+ t = pc()+ try:+ return f(*a, **kw)+ finally:+ rec(key, (pc() - t) * 1000)+ setattr(obj, name, w)+wrap(GR, "step_rows", "step_rows")+wrap(GR, "stage", "stage")+wrap(GR, "_jobs", "hash")+wrap(GR, "_submit", "submit")+wrap(GR.stager, "hash", "hash")+wrap(GR.stager, "submit", "submit")+wrap(MG, "run", "draft_run")+wrap(MG, "_graph", "dgcall")+import ngram as _ng+wrap(_ng.NGram, "propose", "ng_propose")+wrap(_ng.NGram, "add", "ng_add")+_gk = GR._graph+CAPKEYS = []+def _gk2(Nb, T=1):+ new = (Nb, T) not in GR.graphs+ t = pc(); r = _gk(Nb, T)+ if new: CAPKEYS.append((Nb, T, round((pc() - t) * 1000)))+ return r+GR._graph = _gk2+def rbytes():+ for l in open("/proc/self/io"):+ if l.startswith("read_bytes"): return int(l.split()[1])+ev0 = GR.ev+ncap0 = lambda: GR.stats["captures"]+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]; CODE2 = open(os.path.join(tree, "tools/hy4/engine.py")).read()[1200:3800]+chat = lambda t: V.encode(V.template.render([{"role": "user", "content": t}], None, True, reasoning_effort="no_think"))+PA = {"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.")}+PB = {"quote": chat("Here is a passage:\n\n" + WT2 + "\n\nQuote the two most surprising sentences verbatim, then summarize in one sentence."),+ "code": chat("Rename every local variable of this Python file to a longer descriptive name and return the full file.\n\n" + CODE2),+ "chat": chat("Describe how a B-tree keeps itself balanced during insertions, with a short Python sketch.")}+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+ else:+ e.pipe, GR.stager, e.MH._STAGE_OV[0] = True, STG, True+def q(v, p):+ s = sorted(v); return s[min(len(s) - 1, int(p * len(s)))]+def summ(v):+ return "n=%d med %.2f p90 %.2f max %.2f" % (len(v), statistics.median(v), q(v, 0.9), max(v)) if v else "none"+def run(tag, arm, pn, ids):+ set_arm(arm)+ REC.clear(); CAPKEYS.clear(); rb0 = rbytes()+ stamps, out = [], []+ def cb(t):+ stamps.append(pc()); out.extend(t); return False+ 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" 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:+ seq = [("A", "old", PA), ("A", "old", PA), ("A", "new", PA), ("A", "new", PA), ("B", "new", PB), ("B", "new", PB), ("B", "old", PB), ("B", "old", PB)]+ md = {}+ for i, (t, arm, P) in enumerate(seq):+ out = run(f"{t}{i}", arm, pn, P[pn])+ md.setdefault((t, arm), []).append(hashlib.md5(str(out).encode()).hexdigest()[:8])+ print("MD5", pn, {f"{k[0]}-{k[1]}": v for k, v in md.items()}, flush=True)+print("HP_DONE", flush=True)diff --git a/tools/hy4/spec2/test_stage.py b/tools/hy4/spec2/test_stage.pynew file mode 100644index 0000000..21ce232--- /dev/null+++ b/tools/hy4/spec2/test_stage.py@@ -0,0 +1,143 @@+"""CPU unit + bounds tests of the vectorised Engram staging (exllamav3/loader/engram_stage.py) and the bucket arithmetic of step_graph. No GPU, no model.+Run: python -I tools/hy4/spec2/test_stage.py (from the tree root; needs torch + numpy only)"""+import importlib.util, os, random, sys, tempfile, types+from concurrent.futures import ThreadPoolExecutor+import numpy as np+import torch++ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))+def load(name, fn):+ sp = importlib.util.spec_from_file_location(name, os.path.join(ROOT, "exllamav3", "loader", fn))+ m = importlib.util.module_from_spec(sp); sys.modules[name] = m; sp.loader.exec_module(m); return m+ER = load("engram_rows_t", "engram_rows.py")+ES = load("engram_stage_t", "engram_stage.py")++NG, NH = 3, 8+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 = []+ for e in range(nE):+ primes = [rng.randrange(rows // 40, rows // 20) | 1 for _ in range(NC)]+ offs = [0] * NC+ acc = 0+ for c in range(NC): # disjoint id ranges like the real head offsets+ 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++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)+ with open(path, "wb") as f:+ f.write(b"\xAA" * shard_off); f.write(data.tobytes()); f.write(b"\xBB" * 4096) # bytes around the table: an off-by-one read shows up+ fd = os.open(path, os.O_RDONLY)+ tab = types.SimpleNamespace(off=(0 << 48) | 0, rows=rows, row_bytes=rb, name="synthetic", g=types.SimpleNamespace(fds=[fd], bases=[shard_off]))+ return tab, data.reshape(rows, rb)++def test_hash_matches_reference():+ rng = random.Random(1)+ rows = 20000+ mods, tot = make_mods(rng, 4, 4000, tot_rows := 10 ** 6)+ tab = types.SimpleNamespace(off=0, rows=tot, row_bytes=8, name="x", g=types.SimpleNamespace(fds=[0], bases=[0]))+ TM = 8+ rnp = np.zeros((4, TM, NC, 8), dtype=np.uint8); vnp = np.zeros((4, TM, NC), dtype=np.float32)+ st = ES.EngramStager(mods, tab, rnp, vnp, pool=None)+ for trial in range(300):+ n = rng.randrange(1, 60)+ toks = [rng.choice([rng.randrange(0, 4000), rng.randrange(3990, 4100), -1]) for _ in range(n)] # includes ids past the token map+ T = rng.randrange(1, TM + 1)+ start = rng.randrange(0, n)+ hist = toks[:start] + [rng.randrange(0, 4000) for _ in range(T)]+ t0 = rng.randrange(0, T)+ ids, valid = st.hash(hist, start, t0, T)+ for e, m in enumerate(mods):+ ref, rv = ER.engram_hash(hist, start + t0, T - t0, m.token_map, m.pad_id, m.mult, m.primes, m.offs, NG, NH)+ assert np.array_equal(ids[e], ref.numpy()), (trial, e)+ assert np.array_equal(np.broadcast_to(valid[:, None], rv.shape), rv.numpy()), (trial, e)+ # the history passed as tokens + extra gives the same hash+ k = rng.randrange(0, min(T, 3) + 1)+ ids2, valid2 = st.hash(hist[:len(hist) - k], start, t0, T, extra=hist[len(hist) - k:]) if start + T - k >= start else (ids, valid)+ assert np.array_equal(ids, ids2) and np.array_equal(valid, valid2)+ print("hash == engram_hash: ok")++def run_reads(workers, inline):+ rng = random.Random(7)+ nE, rb, TM = 4, 99, 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 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+ 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)]+ t0 = rng.randrange(0, T)+ for f in st.stage(hist, start, t0, T):+ f.result()+ ids, valid = st.hash(hist, start, t0, T)+ for e in range(nE):+ for t in range(T - t0):+ assert np.array_equal(rnp[e, t0 + t], data[ids[e, t]]), (trial, e, t)+ 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")++def test_reads():+ run_reads(1, 0); run_reads(4, 0); run_reads(4, 10 ** 9); run_reads(8, 0)++def test_bounds():+ rng = random.Random(3)+ nE, rb, TM = 2, 16, 4+ mods, tot = make_mods(rng, nE, 500, 100000)+ with tempfile.TemporaryDirectory() as d:+ tab, data = make_table(os.path.join(d, "t.bin"), tot, rb, rng)+ rnp = np.full((nE, TM, NC, rb), 0xCD, dtype=np.uint8); vnp = np.zeros((nE, TM, NC), dtype=np.float32)+ st = ES.EngramStager(mods, tab, rnp, vnp, pool=None)+ hist = [rng.randrange(0, 500) for _ in range(20)]+ # a table one row too short: some id is past the end -> IndexError and NO byte staged+ small = types.SimpleNamespace(**{**tab.__dict__, "rows": 5000})+ st2 = ES.EngramStager(mods, small, rnp, vnp, pool=None)+ try:+ st2.stage(hist, 10, 0, 4); raise SystemExit("bounds: out-of-range id was not caught")+ except IndexError:+ pass+ assert (rnp == 0xCD).all(), "bounds: bytes staged before the check"+ # more rows than the staging buffer+ try:+ st.stage(hist + [1] * 8, 10, 2, 10); raise SystemExit("bounds: T past TM not caught")+ except (IndexError, ValueError):+ pass+ # history too short for the window+ try:+ st.hash(hist[:5], 10, 0, 2); raise SystemExit("bounds: short history not caught")+ except IndexError:+ pass+ # last row of the table: read exactly rb bytes, bytes after it never staged+ ids = np.full((nE, 1, NC), tot - 1, dtype=np.int64)+ st.submit(ids, np.ones(1, dtype=np.float32), 0)+ assert (rnp[:, 0] == data[tot - 1]).all() and (rnp[:, 1:] == 0xCD).all()+ print("bounds: ok")++def test_bucket():+ for n, sub in (("exllamav3", ""), ("exllamav3.loader", "loader")):+ m = types.ModuleType(n); m.__path__ = [os.path.join(ROOT, "exllamav3", sub)]; sys.modules[n] = m+ from exllamav3.loader import step_graph as SG+ B = SG.BUCKET+ gd = types.SimpleNamespace(cap=8 * B)+ f = lambda start, T: SG.GraphDecoder.bucket(gd, start, T)+ assert f(0, 1) == B and f(B - 1, 1) == B and f(B, 1) == 2 * B and f(B - 2, 4) == 2 * B and f(8 * B - 2, 8) == 8 * B+ for start in range(0, 8 * B - 8, 37):+ for T in range(1, SG.TM + 1):+ Nb = f(start, T)+ assert Nb % B == 0 and start + T <= Nb <= gd.cap # the bucket covers the last row of the step and stays inside the static buffers+ print("bucket: ok")++if __name__ == "__main__":+ test_hash_matches_reference(); test_reads(); test_bounds(); test_bucket()+ print("ALL_OK")