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 prefill: Engram host side (vectorised hash, GIL-free native row reads, single prefetch worker), sync-free MoE routing counts (flags HY4_ENGRAM_NPHASH, HY4_ENGRAM_NATIVE_IO, HY4_ENGRAM_PF_WORKERS, HY4_PF_NOSYNC_ROUTE, default off)

YanissAmze5f8cdeaffa5
diff --git a/exllamav3/loader/engram_gpu.py b/exllamav3/loader/engram_gpu.py
index f51510f..caf5266 100644
--- a/exllamav3/loader/engram_gpu.py
+++ b/exllamav3/loader/engram_gpu.py
@@ -28,6 +28,47 @@ def _tabs(dev):
return _TABS[k]
+_NAT = [None, False] # [ctypes lib or None, tried]
+
+
+def _native_lib():
+ """HY4_ENGRAM_NATIVE_IO=1: the row reads of one fetch run in C threads (engram_io.c: pread per distinct row, no GIL). Built once with gcc into the cache dir; None = Python path."""
+ if os.environ.get("HY4_ENGRAM_NATIVE_IO", "0") != "1":
+ return None
+ if _NAT[0] is not None or _NAT[1]:
+ return _NAT[0]
+ _NAT[1] = True
+ import ctypes, hashlib, shutil, subprocess
+ src = os.path.join(os.path.dirname(os.path.abspath(__file__)), "engram_io.c")
+ try:
+ tag = hashlib.sha1(open(src, "rb").read()).hexdigest()[:10]
+ d = os.path.join(os.environ.get("XDG_CACHE_HOME") or os.path.join(os.path.expanduser("~"), ".cache"), "kyojin", "engram_io")
+ so = os.path.join(d, f"libengram_io_{tag}.so")
+ if not os.path.exists(so):
+ os.makedirs(d, exist_ok=True)
+ tmp = so + f".{os.getpid()}.tmp"
+ subprocess.run([shutil.which("gcc") or "gcc", "-O2", "-shared", "-fPIC", "-pthread", src, "-o", tmp], check=True, capture_output=True)
+ os.replace(tmp, so)
+ lib = ctypes.CDLL(so)
+ lib.engram_read_rows.restype = ctypes.c_int
+ lib.engram_read_rows.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_void_p, ctypes.c_int]
+ _NAT[0] = lib
+ except Exception as ex: # noqa: BLE001 - speed only: the Python reader below does the same reads
+ print(f"engram native io unavailable ({type(ex).__name__}: {ex}); Python reader", flush=True)
+ return _NAT[0]
+
+
+def _read_rows_native(lib, table: F8Rows, uniq, view):
+ g = table.g
+ fds = np.ascontiguousarray(np.asarray(g.fds, dtype=np.int32))
+ bases = np.ascontiguousarray(np.asarray(g.bases, dtype=np.int64))
+ rows = np.ascontiguousarray(uniq, dtype=np.int64)
+ nt = int(os.environ.get("HY4_ENGRAM_NATIVE_THREADS", "32"))
+ rc = lib.engram_read_rows(fds.ctypes.data, bases.ctypes.data, rows.ctypes.data, len(rows), int(table.off), int(table.row_bytes), view.ctypes.data, nt)
+ if rc != 0:
+ raise IOError(f"{table.name}: native row read failed (rc {rc})")
+
+
def fetch_rows_host(table: F8Rows, ids):
"""CPU half of fetch_rows: distinct rows pread once (threaded) into one pinned buffer. -> (shape, uniq, inv, buf). Safe to run in a worker thread."""
ids = np.asarray(torch.as_tensor(ids, dtype=torch.int64).numpy())
@@ -38,7 +79,10 @@ def fetch_rows_host(table: F8Rows, ids):
if len(uniq) and (int(uniq[0]) < 0 or int(uniq[-1]) >= table.rows):
raise IndexError(f"{table.name}: row outside 0..{table.rows - 1}")
- if len(uniq) > 8:
+ lib = _native_lib() if len(uniq) > 8 else None
+ if lib is not None:
+ _read_rows_native(lib, table, uniq, view)
+ elif len(uniq) > 8:
# one task per slice of the sorted row list (a task per row cost more in future / GIL hand-offs than the read itself); preadv straight into the pinned buffer
nw = _IO_THREADS
step = (len(uniq) + nw - 1) // nw
diff --git a/exllamav3/loader/engram_io.c b/exllamav3/loader/engram_io.c
new file mode 100644
index 0000000..adfd85c
--- /dev/null
+++ b/exllamav3/loader/engram_io.c
@@ -0,0 +1,50 @@
+/* engram_io.c: GIL-free parallel row reads for the Engram table (same bytes as engram_gpu._read_rows: one pread per distinct row into a flat buffer).
+ build: gcc -O2 -shared -fPIC -pthread engram_io.c -o libengram_io.so */
+#define _GNU_SOURCE
+#include <pthread.h>
+#include <stdint.h>
+#include <unistd.h>
+#include <errno.h>
+#include <stdlib.h>
+
+typedef struct {
+ const int *fds; const int64_t *bases; const int64_t *rows; int64_t lo, hi, off0, rb; uint8_t *out; int err;
+} job_t;
+
+static void *work(void *p) {
+ job_t *j = (job_t *)p;
+ for (int64_t k = j->lo; k < j->hi; k++) {
+ int64_t o = j->off0 + j->rows[k] * j->rb;
+ int fi = (int)(o >> 48);
+ int64_t pos = j->bases[fi] + (o & ((1LL << 48) - 1));
+ uint8_t *dst = j->out + k * j->rb;
+ int64_t got = 0;
+ while (got < j->rb) {
+ ssize_t n = pread(j->fds[fi], dst + got, (size_t)(j->rb - got), (off_t)(pos + got));
+ if (n <= 0) { j->err = n < 0 ? errno : -1; return NULL; }
+ got += n;
+ }
+ }
+ return NULL;
+}
+
+/* rows: sorted distinct row ids [n]; returns 0 or an errno / -1 (short read) */
+int engram_read_rows(const int *fds, const int64_t *bases, const int64_t *rows, int64_t n, int64_t off0, int64_t rb, uint8_t *out, int nthreads) {
+ if (n <= 0) return 0;
+ if (nthreads < 1) nthreads = 1;
+ if (nthreads > 256) nthreads = 256;
+ if (nthreads > n) nthreads = (int)n;
+ pthread_t th[256]; job_t jobs[256];
+ int64_t step = (n + nthreads - 1) / nthreads;
+ int started = 0;
+ for (int t = 0; t < nthreads; t++) {
+ int64_t lo = t * step, hi = lo + step < n ? lo + step : n;
+ if (lo >= hi) break;
+ jobs[t] = (job_t){fds, bases, rows, lo, hi, off0, rb, out, 0};
+ if (pthread_create(&th[t], NULL, work, &jobs[t]) != 0) { work(&jobs[t]); th[t] = 0; }
+ started++;
+ }
+ int err = 0;
+ for (int t = 0; t < started; t++) { if (th[t]) pthread_join(th[t], NULL); if (jobs[t].err && !err) err = jobs[t].err; }
+ return err;
+}
diff --git a/exllamav3/loader/engram_rows.py b/exllamav3/loader/engram_rows.py
index b06e5cc..8b20dcc 100644
--- a/exllamav3/loader/engram_rows.py
+++ b/exllamav3/loader/engram_rows.py
@@ -144,6 +144,33 @@ def engram_hash(tokens, start, n_tokens, token_map, pad_id, mult, primes, offs,
return torch.from_numpy(ids), torch.from_numpy(valid)
+def engram_hash_np(tokens, start, n_tokens, token_map, pad_id, mult, primes, offs, n_gram, n_head):
+ """engram_hash, vectorised over the positions (uint64 arithmetic wraps exactly like the Python `& MASK64`; same ids / valid, bit for bit)."""
+ n_cols = (n_gram - 1) * n_head
+ tm = np.asarray(list(token_map), dtype=np.int64)
+ pad = int(tm[pad_id])
+ pos = start + np.arange(n_tokens, dtype=np.int64)
+ toks_all = np.asarray(tokens[:start + n_tokens], dtype=np.int64)
+
+ def cid(q): # q: positions (may be < 0) -> compressed id, -1 = dead
+ t = toks_all[np.clip(q, 0, None)]
+ ok = (q >= 0) & (t >= 0) & (t < len(tm))
+ return np.where(ok, tm[np.clip(t, 0, len(tm) - 1)], -1)
+
+ cs = [cid(pos - s) for s in range(n_gram)]
+ dead = cs[0] == -1
+ toks = [np.where(c == -1, pad, c).astype(np.uint64) for c in cs]
+ ids = np.zeros((n_tokens, n_cols), dtype=np.int64)
+ rolling = toks[0] * np.uint64(int(mult[0]) & MASK64)
+ for o in range(1, n_gram):
+ rolling = rolling ^ (toks[o] * np.uint64(int(mult[o]) & MASK64))
+ for h in range(n_head):
+ col = (o - 1) * n_head + h
+ ids[:, col] = (rolling % np.uint64(int(primes[col]))).astype(np.int64) + int(offs[col])
+ valid = np.broadcast_to(np.where(dead, 0.0, 1.0).astype(np.float32)[:, None], (n_tokens, n_cols)).copy()
+ return torch.from_numpy(ids), torch.from_numpy(valid)
+
+
# ------------------------------------------------------------------------------------------------ weights
def _dequant_q8_0(raw: np.ndarray, K: int, N: int) -> torch.Tensor:
b = np.ascontiguousarray(raw).reshape(N, K // 32, 34)
@@ -212,7 +239,7 @@ class Hy4Engram:
assert self.table.width == self.head_dim
def row_ids(self, tokens, start, n):
- return engram_hash(tokens, start, n, self.token_map, self.pad_id, self.mult, self.primes, self.offs, self.n_gram, self.n_head)
+ return (engram_hash_np if os.environ.get("HY4_ENGRAM_NPHASH", "0") == "1" else engram_hash)(tokens, start, n, self.token_map, self.pad_id, self.mult, self.primes, self.offs, self.n_gram, self.n_head)
def apply(self, x: torch.Tensor, rows: torch.Tensor, valid: torch.Tensor) -> torch.Tensor:
"""x [T, hc, n_embd] fp32 stream, rows [T, n_cols, head_dim] decoded table rows, valid [T, n_cols] -> x + delta (M:5292-5353)."""
diff --git a/exllamav3/loader/hy4_forward.py b/exllamav3/loader/hy4_forward.py
index b67f420..c008bfa 100644
--- a/exllamav3/loader/hy4_forward.py
+++ b/exllamav3/loader/hy4_forward.py
@@ -777,7 +777,7 @@ class Hy4Forward:
self.eng[i] = Hy4EngramGPU(self.g, i, self.dev, table=self.table, lin=None if os.environ.get("HY4_ENGRAM_GPU") == "2" else self._lin)
toks = [int(t) for t in ids_all]
self._eng_pf = {}
- ex = ThreadPoolExecutor(max_workers=2)
+ ex = ThreadPoolExecutor(max_workers=int(os.environ.get("HY4_ENGRAM_PF_WORKERS", "2"))) # 1 with HY4_ENGRAM_NATIVE_IO: one layer at a time gets the whole read queue
for s, e in chunk_plan(self.n, len(toks), chunk):
n = e - s
for i in layers:
diff --git a/exllamav3/loader/prefill_kernels.py b/exllamav3/loader/prefill_kernels.py
index 5725312..0690473 100644
--- a/exllamav3/loader/prefill_kernels.py
+++ b/exllamav3/loader/prefill_kernels.py
@@ -885,7 +885,10 @@ def route_blocks(sel, E, BM):
P = T * S
ex = sel.reshape(-1)
order = torch.argsort(ex, stable=True)
- counts = torch.bincount(ex, minlength=E)
+ if os.environ.get("HY4_PF_NOSYNC_ROUTE", "0") == "1": # torch.bincount reads max / min back to the host (2 syncs per MoE layer: the host waits for the whole queued layer); integer scatter-add = same counts, no sync
+ counts = torch.zeros(E, dtype=torch.int64, device=ex.device).scatter_add_(0, ex, torch.ones_like(ex))
+ else:
+ counts = torch.bincount(ex, minlength=E)
nblk = (counts + (BM - 1)) // BM
csum = torch.cumsum(nblk, 0)
bstart = csum - nblk