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 decode: drop the dead zeros fill and the lat clone in the grouped MoE decode path, n-gram long-match-replaces-chain arm (HY4_NGRAM_LONG), zero-GPU n-gram env check

YanissAmz4ce03e46aa1f
diff --git a/exllamav3/loader/hy4_forward.py b/exllamav3/loader/hy4_forward.py
index 4315db0..cbbc761 100644
--- a/exllamav3/loader/hy4_forward.py
+++ b/exllamav3/loader/hy4_forward.py
@@ -211,6 +211,7 @@ def _dq_q8_0_t(packed):
# rows <= DENSE_MAXR run the extension GEMV (activation quantised to q8_1 inside, like llama.cpp), more rows dequantise per call (no resident fp32 copy).
GG_DENSE = {8: (32, 34, "fq_gemv_q8_0", _dq_q8_0_t)}
DENSE_MAXR = 16
+NO_ALIAS_LAT = os.environ.get("HY4_LAT_CLONE", "0") == "1" # 1 = copy the grouped MoE output before the rup matmul (old behaviour)
DENSE_DQ = os.environ.get("HY4_DENSE_DQ", "0") == "1" # 1 = old path: dense matrices dequantised once to fp32 and kept resident
@@ -557,7 +558,7 @@ class Hy4Forward:
sel_l = [] if (pf or _ns.skip_host_ids(self, i, T, MMVQ_MAXR)) else sorted(set(sel.flatten().tolist()))
with tm.t("other"):
z = self._mm(x, L.rdown)
- lat = torch.zeros(T, z.shape[1], device=dev)
+ lat = None # allocated (zeros) only by the paths that accumulate into it: the grouped / prefill paths overwrite it
lim, N = float(self.clamp[i]), z.shape[1]
b = f"blk.{i}."
if pf and PF_MOE_REF:
@@ -582,9 +583,11 @@ class Hy4Forward:
ext.fq_moe_kq_set_swiglu_limit(lim)
ext.fq_moe_kq_grouped_mixed_q8(z.half().contiguous(), sel.contiguous(), w.half().contiguous(), *rs.ptrs, *rs.strides, rs.fu, rs.fd,
self._gpart[:T * S], self._gout[:T])
- lat = self._gout[:T].clone()
+ lat = self._gout[:T] if (self.hook is None and not NO_ALIAS_LAT) else self._gout[:T].clone() # rup reads it before the next layer's grouped call overwrites _gout (one stream); hooks keep a copy
self.stats["grouped_calls"] = self.stats.get("grouped_calls", 0) + 1
sel_l = [] # the per-expert pread loop below runs zero times
+ if lat is None:
+ lat = torch.zeros(T, N, device=dev)
kg, kd = (None, None) if (self.expert_dq or T > MMVQ_MAXR or dev.type != "cuda") else (mmvq_fn(L.ety, N), mmvq_fn(L.ety_down, N))
use_k = kg is not None or kd is not None # per tensor: a stored type without a kernel keeps the torch dequant for that tensor only
with tm.t("routed experts"):
diff --git a/tests/test_hy4_ngram_env.py b/tests/test_hy4_ngram_env.py
new file mode 100644
index 0000000..85142f7
--- /dev/null
+++ b/tests/test_hy4_ngram_env.py
@@ -0,0 +1,30 @@
+"""zero-GPU check: the shipped environment (serve.SHIPPED_ENV through apply_env) turns the n-gram rows on in the engine, with the gate; an explicit env value wins."""
+import os
+import sys
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+TREE = os.path.dirname(HERE)
+sys.path.insert(0, os.path.join(TREE, "tools", "hy4"))
+
+
+def _engine(env):
+ for k in [k for k in os.environ if k.startswith("HY4_NGRAM")]:
+ del os.environ[k]
+ os.environ.update(env)
+ import serve
+ serve.apply_env(16384)
+ from engine import Hy4Engine
+ return Hy4Engine(TREE, "/nonexistent.gguf", ctx=16384, k=3)
+
+
+def test_shipped_flags_enable_ngram():
+ e = _engine({})
+ assert (e.ngram_ext, e.ngram_min, e.ngram_gate) == (4, 8, True)
+ assert e.ngram_adapt is False and e.ngram_fill is False
+
+
+def test_explicit_env_wins_and_zero_disables():
+ e = _engine({"HY4_NGRAM_EXT": "0"})
+ assert e.ngram_ext == 0
+ e = _engine({"HY4_NGRAM_EXT": "6", "HY4_NGRAM_MIN": "5", "HY4_NGRAM_GATE": "0"})
+ assert (e.ngram_ext, e.ngram_min, e.ngram_gate) == (6, 5, False)
diff --git a/tools/hy4/engine.py b/tools/hy4/engine.py
index b73a702..b1dd66e 100644
--- a/tools/hy4/engine.py
+++ b/tools/hy4/engine.py
@@ -39,6 +39,7 @@ class Hy4Engine:
self.ngram_adapt = os.environ.get("HY4_NGRAM_ADAPT", "0") == "1"
self.ngram_gate = os.environ.get("HY4_NGRAM_GATE", "0") == "1"
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 = off
self.ready = False
self.meta = None
self.last_stats: dict = {}
@@ -203,15 +204,23 @@ class Hy4Engine:
from ngram import NGram
ng = NGram(self.ngram_min, self.ngram_ext)
ng.reset(list(ids) + [y])
- n_ext = n_hit = n_extacc = 0
+ n_ext = n_hit = n_extacc = n_long = 0
rate, since = 0.7, 0 # recent acceptance of the extra rows; below 0.4 the proposer pauses (a probe every 8 rounds)
while out_n < max_new and not stop and not cancel():
j = GR.fw.n - 1
ta = pc()
- d = MG.run(y, hcur, j).tolist()
- tb = pc()
- ext = []
- if ng is not None:
+ 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 skip:
+ d, ext = [], cl
+ tb = pc()
+ else:
+ d = MG.run(y, hcur, j).tolist()
+ tb = pc()
+ ext = []
+ if ng is not None and not skip:
lim = min(self.ngram_ext, self.SG.TM - 1 - k)
if self.ngram_gate:
since += 1
@@ -220,9 +229,12 @@ class Hy4Engine:
if self.ngram_adapt and ext: # longer match, more rows: 2 rows at the minimum match, +2 per extra matched token
ext = ext[:max(1, (ml - self.ngram_min + 1) * 2)]
toks = [y] + d + ext
- if ext:
+ if skip:
+ n_long += 1
+ elif ext:
n_hit += 1
n_ext += len(ext)
+ hc0 = hcur.clone() if skip else None # hcur views the static graph output: the replay below overwrites it
_lg, amv, _x, hv = GR.step_rows(toks)
tc = pc()
amh = amv.tolist()
@@ -234,13 +246,19 @@ class Hy4Engine:
nd = len(toks) - 1
while acc < nd and toks[acc + 1] == amh[acc]:
acc += 1
- n_extacc += max(0, acc - k)
- if ext:
+ if not skip:
+ n_extacc += max(0, acc - k)
+ if ext and not skip:
since = 0
rate = 0.75 * rate + 0.25 * (max(0, acc - k) / len(ext))
new = toks[1:acc + 1] + [amh[acc]] # toks[0] = y was already emitted; the verified drafts + the trunk's own next token
GR.rewind(j + 2 + acc)
- if self.ngram_fill and acc >= k: # head rows j + k .. j + acc were never written by the draft chain: true pairs (token p + 1, trunk state h_p)
+ if skip: # the chain wrote no head rows: pairs (token m, state before it) for head positions j .. j + acc
+ MT = self.MT
+ N = ((j + acc + 1 + 3) // 4) * 4
+ sts = torch.cat([hc0, hv[:acc]]) if acc > 0 else hc0
+ MT.step(torch.tensor(toks[:acc + 1], dtype=torch.long, device=self.dev), sts, MT.ar[j:j + acc + 1], N)
+ elif self.ngram_fill and acc >= k: # head rows j + k .. j + acc were never written by the draft chain: true pairs (token p + 1, trunk state h_p)
MT = self.MT
N = ((j + acc + 1 + 3) // 4) * 4
MT.step(torch.tensor(toks[k:acc + 1], dtype=torch.long, device=self.dev), hv[k - 1:acc], MT.ar[j + k:j + acc + 1], N)
@@ -255,7 +273,7 @@ class Hy4Engine:
out_n += len(new)
stop = on_tokens(new)
st["round_ms"] = [x / max(rounds, 1) * 1000 for x in tm]
- 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}
+ 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}
else:
while out_n < max_new and not stop and not cancel():
lg = GR.step(y)