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 levers (DENSE_V2, MOE_V2, DRAFT_*): fires counters, no_grad fix, CPU tests, docs, scrubbed tool defaults

YanissAmzeefa4e077504
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ffb4616..a07675f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,13 @@
# Changelog
+## Unreleased (1.9.3)
+
+- Decode levers, all opt-in (`=1` to enable, code default `0`), each with a fires counter printed after the load warm-up (`FIRES <name> {...}`, `loader/lever_fires.py`) and a CPU test (`tests/test_hy4_seta_levers_cpu.py`):
+ `HY4_DENSE_V2` (column-tiled few-row Q8_0 dense GEMV, `gm_dense_q8`, bit-identical to the stock kernel; rebuild `exl3_gm_ext` with `tools/hy4/install_strix.sh`),
+ `HY4_MOE_V2` (routed experts through the HIP code object `moe_dec.co`, built by `install_strix.sh` step 2b, `MOE_DEC_CO` overrides the path),
+ `HY4_DRAFT_MOE_TILES`, `HY4_DRAFT_MLA_BG`, `HY4_DRAFT_IX_GV` (draft MTP layer: int8 expert tile retune, Q8 absorb matrices, indexer mat-vec).
+- New tools: `tools/hy4/step/opbench.py` (per-op decode microbench, no server boot) and the paired A/B drivers `ab_dend.py`, `ab_exp.py`, `mtp_items.py`, `mtp_micro.py`, `mtp_arms.sh`; model and data paths come from `GGUF` / `WIKI` (no default path).
+
## 1.9.2
Hy4-flash server hotfix: tool calling, a quiet exit when the client leaves, request-parser fixes, Strix install fixes, docs.
diff --git a/doc/env_vars.md b/doc/env_vars.md
index 22740e3..43c81e5 100644
--- a/doc/env_vars.md
+++ b/doc/env_vars.md
@@ -1079,6 +1079,16 @@ Hy4-flash server only. `tools/hy4/serve.py` sets these in `SHIPPED_ENV` without
| `HY4_RG_TUNE` | `1` | decode: router mat-vec with K block 1024 (was 256) | `HY4_RG_TUNE=0` |
| `HY4_BG_V2` | `1` | decode: block-wise absorb kernels (absorb v2) | `HY4_BG_V2=0` |
+Hy4-flash 1.9.3 decode levers: all five are opt-in (code default `0`, not in `SHIPPED_ENV`). Each one has a fires counter (`loader/lever_fires.py`), printed as one `FIRES <name> {...}` line after the load warm-up; a flagged lever that shows no hit, or any fallback reason, is not in effect (counters are python-side: they count graph capture and eager call sites).
+
+| Flag | Default | Effect | Fires counter |
+|---|---|---|---|
+| `HY4_DENSE_V2` | `0` | decode: 2..16 rows with K <= 8192 through the column-tiled Q8_0 GEMV `gm_dense_q8` (bit-identical to `fq_gemv_q8_0`); needs `exl3_gm_ext.so` rebuilt by `tools/hy4/install_strix.sh` | `dense_v2 {v2, stock: {reason: n}}` |
+| `HY4_MOE_V2` | `0` | decode: routed experts (16 per row, K = 1536, Q3_K / Q4_K gate-up) through the HIP code object `moe_dec.co` (bit-equal to the shipped grouped kernels); built by `install_strix.sh` step 2b, path override `MOE_DEC_CO` | `moe_v2 {calls, fallback: {reason: n}}` |
+| `HY4_DRAFT_MOE_TILES` | `0` | draft layer: int8 expert tile retune (gate-up 8 x 512, 8 warps; down 16 x 512, 4 warps) | `draft_moe_tiles {calls}` |
+| `HY4_DRAFT_MLA_BG` | `0` | draft layer: absorb matrices `wk_b` / `wv_b` as int8 + fp16 block scales on the batched mat-vec (needs `HY4_MLA_BG=1` and `HY4_MTP_FAST=1`, both shipped on) | `draft_mla_bg {calls}` |
+| `HY4_DRAFT_IX_GV` | `0` | draft layer: indexer fp32 matrices on the router mat-vec (needs `HY4_MTP_FAST=1`) | `draft_ix_gv {gv, gemm: {reason: n}}` |
+
The warm-up clamp has no switch. The start-up warm-up prompt (`HY4_WARMUP_TOKENS`, default the smaller of 8493 and `-c` minus 128, also when you set it) is cut to what the context window accepts, and skipped with one log line when that is under 256 tokens. `HY4_WARMUP_TOKENS=0` skips the warm-up.
#### `EXL3_ABLIT_TORCH` (default: `0`)
diff --git a/exllamav3/loader/hy4_forward.py b/exllamav3/loader/hy4_forward.py
index 9c3e475..ae201a9 100644
--- a/exllamav3/loader/hy4_forward.py
+++ b/exllamav3/loader/hy4_forward.py
@@ -35,6 +35,7 @@ from . import attn_eager as _AE
from . import router_gemv as _RG
from . import mla_hy4 as _mla_mod
from . import dense_req as _DR
+from . import lever_fires as _LVF
from . import ablit_hy4 as _AB # decensor edit hook (inert while _AB.ST is None)
_HCF = None
@@ -203,11 +204,18 @@ def _ext():
MOE_V2 = os.environ.get("HY4_MOE_V2", "0") == "1" # routed experts through loader/moe_dec_hip.py (HIP code object, bit-equal to the shipped grouped kernels, fewer waits per row); default off
_MD = []
+MOE_V2_FIRES = _LVF.Fires("moe_v2", hit="calls") # calls = layer calls (graph capture / eager sites) that took the code object; fallback = {reason: n} of the calls that did not (only counted with the flag on)
-def _moe_v2(rs, T, K):
+def _moe_v2(rs, T, K, S=16):
"""the MoeDec scratch holder for this layer shape, or None (flag off / code object missing / shape or alignment outside the kernels' contract)"""
- if not MOE_V2 or T > MMVQ_MAXR:
+ if not MOE_V2:
+ return None
+ if S != 16:
+ MOE_V2_FIRES.miss("topk!=16")
+ return None
+ if T > MMVQ_MAXR:
+ MOE_V2_FIRES.miss("T>maxr")
return None
if not _MD:
try:
@@ -219,12 +227,20 @@ def _moe_v2(rs, T, K):
_MD.extend([None, {}])
md, cache = _MD[0], _MD[1]
fmt = {0: "q4_k", 8: "q3_k"}.get(rs.fu)
- if md is None or fmt is None or rs.fd != 0 or rs.nout != K or K % 256 or rs.nff % 256 or K != 1536 or rs.nff != 1536 or any(st % 16 for st in rs.strides) or (rs.bufs["gate"].data_ptr() % 16):
+ why = ("no_code_object" if md is None else "gate_up_fmt" if fmt is None else "down_fmt" if rs.fd != 0 else "nout!=K" if rs.nout != K
+ else "shape" if (K % 256 or rs.nff % 256 or K != 1536 or rs.nff != 1536) else "stride_align" if any(st % 16 for st in rs.strides)
+ else "ptr_align" if (rs.bufs["gate"].data_ptr() % 16) else None)
+ if why is not None:
+ MOE_V2_FIRES.miss(why)
return None
key = (T, fmt, K, rs.nff)
if key not in cache:
cache[key] = md.MoeDec(rs.bufs["gate"].device, T, 16, K, rs.nff, fmt, rs.E)
- return cache[key] if cache[key].topk == 16 else None
+ if cache[key].topk != 16:
+ MOE_V2_FIRES.miss("topk")
+ return None
+ MOE_V2_FIRES.hit()
+ return cache[key]
def mmvq_fn(ty, K):
@@ -295,19 +311,31 @@ _TM_HOLD = [None] # the live _Tm (stage timers inside prefill dense cal
DENSE_V2 = [os.environ.get("HY4_DENSE_V2", "0") == "1"] # 1 = 2..16 decode rows with K <= 8192 through gm_ext gm_dense_q8 (column-tiled Q8_0 GEMV, activations in registers; bit-identical to fq_gemv_q8_0); read at call time (graph re-capture flips it)
+DENSE_FIRES = _LVF.Fires("dense_v2", hit="v2", miss="stock") # v2 = dense_gemv calls that took gm_dense_q8; stock = {reason: n} of the calls that kept the stock launch (only counted with the flag on)
DENSE_V2_KMAX = 8192 # above this (wo K=16384, layer-0 FFN down) the stock launch is as fast (opbench / dend_test 20/11)
def dense_gemv(gemv, xf, packed, out):
"""out = Q8_0 GEMV of the [R, K] float rows xf: the stock launch, or (HY4_DENSE_V2, R >= 2) quantise once + the column-tiled kernel (1 / 2 / 3 columns per block at R <= 4 / <= 8 / more: measured best)"""
- if DENSE_V2[0] and xf.shape[0] >= 2 and xf.shape[1] <= DENSE_V2_KMAX and getattr(gemv, "__name__", "") == "fq_gemv_q8_0":
- g, e = _gm(), _ext()
- if g is not None and e is not None and hasattr(g, "gm_dense_q8"):
- R, K = xf.shape
- qb = e.fq_q8_scratch(xf.device.index, R, K)
- e.fq_quant_q8_1_rows(xf, qb)
- if g.gm_dense_q8(qb, packed, out, 1 if R <= 4 else (2 if R <= 8 else 3)):
- return
+ if DENSE_V2[0]:
+ if xf.shape[0] < 2:
+ DENSE_FIRES.miss("rows<2")
+ elif xf.shape[1] > DENSE_V2_KMAX:
+ DENSE_FIRES.miss("K>kmax")
+ elif getattr(gemv, "__name__", "") != "fq_gemv_q8_0":
+ DENSE_FIRES.miss("not_q8_0")
+ else:
+ g, e = _gm(), _ext()
+ if g is None or e is None or not hasattr(g, "gm_dense_q8"):
+ DENSE_FIRES.miss("no_gm_ext")
+ else:
+ R, K = xf.shape
+ qb = e.fq_q8_scratch(xf.device.index, R, K)
+ e.fq_quant_q8_1_rows(xf, qb)
+ if g.gm_dense_q8(qb, packed, out, 1 if R <= 4 else (2 if R <= 8 else 3)):
+ DENSE_FIRES.hit()
+ return
+ DENSE_FIRES.miss("kernel_rejected")
gemv(xf, packed, out)
@@ -772,7 +800,7 @@ class Hy4Forward:
if getattr(self, "_gpart", None) is None or self._gpart.shape[1] != N:
self._gpart = torch.empty(MMVQ_MAXR * S, N, dtype=torch.float32, device=dev)
self._gout = torch.empty(MMVQ_MAXR, N, dtype=torch.float32, device=dev)
- mv2 = _moe_v2(rs, T, z.shape[1]) if S == 16 else None
+ mv2 = _moe_v2(rs, T, z.shape[1], S)
if mv2 is not None:
out2 = mv2.run(z.half().contiguous(), sel.reshape(-1).contiguous(), w.half().reshape(-1).contiguous(), rs.ptrs, rs.strides, lim, "v3", "v3")
lat = out2 if (self.hook is None and not NO_ALIAS_LAT) else out2.clone()
diff --git a/exllamav3/loader/lever_fires.py b/exllamav3/loader/lever_fires.py
new file mode 100644
index 0000000..449880e
--- /dev/null
+++ b/exllamav3/loader/lever_fires.py
@@ -0,0 +1,33 @@
+"""fires counters of the Hy4 decode levers (HY4_DENSE_V2, HY4_MOE_V2, HY4_DRAFT_MOE_TILES, HY4_DRAFT_MLA_BG, HY4_DRAFT_IX_GV).
+A lever that silently falls back (shape, alignment, missing code object) must be visible: an A/B arm whose flagged lever shows 0 hits, or any fallback reason, fails the cell.
+Counters are python-side: a HIP graph replay does not re-run python, so they count the capture and eager call sites, not the replays."""
+import threading
+
+REG = {}
+_LOCK = threading.Lock()
+
+
+class Fires:
+ def __init__(self, name, hit="hit", miss="fallback"):
+ self.name, self.hit_key, self.miss_key = name, hit, miss
+ self.hits, self.fallback = 0, {}
+ REG[name] = self
+
+ def hit(self):
+ self.hits += 1
+
+ def miss(self, reason):
+ with _LOCK:
+ self.fallback[reason] = self.fallback.get(reason, 0) + 1
+
+ def reset(self):
+ self.hits, self.fallback = 0, {}
+
+ def snapshot(self):
+ return {self.hit_key: self.hits, self.miss_key: dict(self.fallback)}
+
+
+def line():
+ """one printable line with every registered counter that was touched: FIRES name {hit: n, fallback: {...}} ..."""
+ parts = [f"FIRES {n} {f.snapshot()}" for n, f in sorted(REG.items()) if f.hits or f.fallback]
+ return " | ".join(parts) if parts else "FIRES none (no lever flag on, or no call yet)"
diff --git a/exllamav3/loader/mla_bgemv.py b/exllamav3/loader/mla_bgemv.py
index 08be83a..f2e114d 100644
--- a/exllamav3/loader/mla_bgemv.py
+++ b/exllamav3/loader/mla_bgemv.py
@@ -11,6 +11,9 @@ import torch
import triton
import triton.language as tl
+from . import lever_fires as _LVF
+
+DRAFT_FIRES = _LVF.Fires("draft_mla_bg", hit="calls") # calls = mat-vec launches (capture / eager sites) of the draft layer's Q8Batched.from_float matrices (HY4_DRAFT_MLA_BG)
ENABLED = os.environ.get("HY4_MLA_BG", "0") == "1"
BN = int(os.environ.get("HY4_BG_BN", "16"))
BK = int(os.environ.get("HY4_BG_BK", "128"))
@@ -144,6 +147,8 @@ class Q8Batched:
self.q = b[:, :, 2:].contiguous().view(torch.int8).reshape(H, N, K).contiguous()
self.H, self.N, self.K = H, N, K
+ draft = False # set on the matrices built by from_float (the draft layer's): their mat-vec launches are counted in DRAFT_FIRES
+
@classmethod
def from_float(cls, w):
"""[H, N, K] float tensor (K % 32 == 0) -> Q8_0-style int8 + fp16 block scales (the draft layer's GGUF tensors are bf16: no stored Q8_0 bytes to read)"""
@@ -153,10 +158,13 @@ class Q8Batched:
q = torch.round(blk / d.float()[..., None]).clamp(-127, 127).to(torch.int8)
o = cls.__new__(cls)
o.d, o.q, o.H, o.N, o.K = d.reshape(H, N, K // 32).contiguous(), q.reshape(H, N, K).contiguous(), H, N, K
+ o.draft = True
return o
def mv(self, x):
"""x [T, H, K] fp32 -> [T, H, N] fp32 (T == 1: the single-row kernel; T > 1: one kernel, weights read once)"""
+ if self.draft:
+ DRAFT_FIRES.hit()
if x.dim() == 3 and x.shape[0] > 1 and x.stride(-1) == 1:
T = x.shape[0]
out = torch.empty(T, self.H, self.N, dtype=torch.float32, device=x.device)
diff --git a/exllamav3/loader/moe_i8.py b/exllamav3/loader/moe_i8.py
index 8d53e45..a869bf4 100644
--- a/exllamav3/loader/moe_i8.py
+++ b/exllamav3/loader/moe_i8.py
@@ -12,6 +12,8 @@ import torch
import triton
import triton.language as tl
+from . import lever_fires as _LVF
+
class Int8Stack:
def __init__(self, g, name, dev, chunk_experts=16):
@@ -81,10 +83,12 @@ def _k_down(wd_ptr, sd_ptr, sel_ptr, h_ptr, w_ptr, o_ptr, N, K, S: tl.constexpr,
TILES = os.environ.get("HY4_DRAFT_MOE_TILES", "0") == "1"
GU_T = (8, 512, 8) if TILES else (16, 128, 4)
DN_T = (16, 512, 4) if TILES else (8, 128, 4)
+FIRES = _LVF.Fires("draft_moe_tiles", hit="calls") # calls = experts_forward launches with the retuned tiles (HY4_DRAFT_MOE_TILES=1; capture / eager sites); with the flag off each launch counts as fallback flag_off, so two identical arms never both read as fired
def experts_forward(gate, up, down, z, sel, w, lim):
"""z [K] fp32, sel [S] int64 device, w [S] fp32 -> lat [N] fp32 (K = gate/up K, N = gate/up N = down K, down N = latent)"""
+ FIRES.hit() if TILES else FIRES.miss("flag_off")
S = sel.numel()
h = torch.empty(S, gate.N, dtype=torch.float32, device=z.device)
_k_gu[(S, triton.cdiv(gate.N, GU_T[0]))](gate.q, up.q, gate.s, up.s, sel, z, h, gate.N, gate.K, lim, BN=GU_T[0], BK=GU_T[1], num_warps=GU_T[2])
diff --git a/exllamav3/loader/mtp_head.py b/exllamav3/loader/mtp_head.py
index c78dbe1..bf3154e 100644
--- a/exllamav3/loader/mtp_head.py
+++ b/exllamav3/loader/mtp_head.py
@@ -103,6 +103,7 @@ class Hy4MTP:
self.kbuf = torch.zeros(self.cap, mla.R + mla.rope_dim, device=dev)
SG.indexer_static_init(self.ix, self.cap)
self.ix.gv = self.fast and os.environ.get("HY4_DRAFT_IX_GV", "0") == "1" # indexer fp32 matrices on the mat-vec
+ print(f"mtp_head: draft cfg fast={self.fast} moe_tiles={MI.GU_T}/{MI.DN_T} (flag {int(MI.TILES)}) mla_bg={getattr(mla, 'bg_kb', None) is not None and getattr(mla.bg_kb, 'draft', False)} (wk_b/wv_b int8) ix_gv={self.ix.gv}", flush=True)
try:
from . import attn_eager as _AE
_AE.ensure(self.cap)
diff --git a/exllamav3/loader/step_graph.py b/exllamav3/loader/step_graph.py
index e57d9ee..927fb83 100644
--- a/exllamav3/loader/step_graph.py
+++ b/exllamav3/loader/step_graph.py
@@ -24,6 +24,7 @@ from . import step_nosync as _ns
from .engram_rows import QB, E4M3, E8M0
from . import attn_eager as _ae
from . import router_gemv as _RG
+from . import lever_fires as _LVF
from .engram_stage import EngramStager
BUCKET = int(os.environ.get("HY4_GRAPH_BUCKET", "512"))
@@ -73,13 +74,23 @@ def indexer_static_init(ix, cap):
ix._table(cap)
+IX_GV_FIRES = _LVF.Fires("draft_ix_gv", hit="gv", miss="gemm") # draft indexer matrices (ix has the gv attribute): gv = mat-vec calls, gemm = {reason: n} of the calls that kept the GEMM (the trunk's indexer has no gv attribute and is not counted)
+
+
def _mmw(ix, a, name):
"""a @ ix.w[name].T; the draft layer's indexer (ix.gv, HY4_DRAFT_IX_GV=1) runs its small fp32 matrices through the router mat-vec (rocBLAS SGEMM at M = 1 runs these at 12-60 GB/s)"""
w = ix.w[name]
- return _RG.logits(a, w) if (getattr(ix, "gv", False) and _RG.usable(a, w)) else a @ w.T
+ gv = getattr(ix, "gv", None)
+ if gv is None:
+ return a @ w.T
+ if gv and _RG.usable(a, w):
+ IX_GV_FIRES.hit()
+ return _RG.logits(a, w)
+ IX_GV_FIRES.miss("flag_off" if not gv else "unusable_shape")
+ return a @ w.T
def indexer_keys_static(ix, x, pos, ar):
"""key side of indexer_forward_static: the per-position (value | gate) rows and the pool groups they complete (x [T, E], pos [T] long device, ascending). Needs no query and no selection."""
k, d = ix.k, ix.d
diff --git a/tests/test_hy4_seta_levers_cpu.py b/tests/test_hy4_seta_levers_cpu.py
new file mode 100644
index 0000000..5e089a1
--- /dev/null
+++ b/tests/test_hy4_seta_levers_cpu.py
@@ -0,0 +1,293 @@
+"""zero-GPU checks of the Strix decode levers HY4_DENSE_V2, HY4_MOE_V2, HY4_DRAFT_MOE_TILES, HY4_DRAFT_MLA_BG, HY4_DRAFT_IX_GV:
+env switches default off ("0"), the fallback paths are the stock ones, every fallback reason and every hit is counted (loader/lever_fires.py),
+the draft layer's quantiser follows the Q8_0 scale rule, and indexer_keys_static keeps its @torch.no_grad()."""
+import ast
+import importlib
+import os
+import re
+import sys
+import types
+from types import SimpleNamespace
+
+import pytest
+import torch
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+TREE = os.path.dirname(HERE)
+LOADER = os.path.join(TREE, "exllamav3", "loader")
+os.environ.setdefault("HY4_ALLOW_SLOW", "1")
+
+
+def _src(name):
+ return open(os.path.join(LOADER, name)).read()
+
+
[email protected](scope="module")
+def mods():
+ """the loader modules by path, without the exllamav3 package import (which builds the extension); the stub entries are removed again"""
+ added = []
+ if "exllamav3" not in sys.modules:
+ for n, s in (("exllamav3", ""), ("exllamav3.loader", "loader")):
+ m = types.ModuleType(n)
+ m.__path__ = [os.path.join(TREE, "exllamav3", s)]
+ sys.modules[n] = m
+ added.append(n)
+ before = set(sys.modules)
+ out = SimpleNamespace(**{k: importlib.import_module(f"exllamav3.loader.{k}") for k in ("lever_fires", "hy4_forward", "moe_i8", "mla_bgemv", "step_graph")})
+ yield out
+ if added:
+ for n in set(sys.modules) - before | set(added):
+ if n.startswith("exllamav3"):
+ sys.modules.pop(n, None)
+
+
[email protected](autouse=True)
+def fresh(mods):
+ for f in mods.lever_fires.REG.values():
+ f.reset()
+ yield
+
+
+# ---- switches ----------------------------------------------------------------------------------------------------------------------------
+
[email protected]("flag,path", [("HY4_DENSE_V2", "hy4_forward.py"), ("HY4_MOE_V2", "hy4_forward.py"), ("HY4_DRAFT_MOE_TILES", "moe_i8.py"),
+ ("HY4_DRAFT_MLA_BG", "mtp_head.py"), ("HY4_DRAFT_IX_GV", "mtp_head.py")])
+def test_flag_is_an_env_switch_defaulting_off(flag, path):
+ assert re.search(r'environ\.get\("%s", "0"\) == "1"' % flag, _src(path)), flag
+
+
+def test_lever_flags_unset_means_off(mods):
+ if not any(k in os.environ for k in ("HY4_DENSE_V2", "HY4_MOE_V2", "HY4_DRAFT_MOE_TILES")):
+ assert mods.hy4_forward.DENSE_V2 == [False] and mods.hy4_forward.MOE_V2 is False and mods.moe_i8.TILES is False
+
+
+def test_draft_moe_tiles_follow_the_flag(mods, monkeypatch):
+ try:
+ monkeypatch.delenv("HY4_DRAFT_MOE_TILES", raising=False)
+ m = importlib.reload(mods.moe_i8)
+ assert (m.GU_T, m.DN_T) == ((16, 128, 4), (8, 128, 4))
+ m.FIRES.reset()
+ with pytest.raises(Exception): # no GPU: the launch fails after the counter
+ m.experts_forward(SimpleNamespace(N=16, K=32, q=None, s=None), SimpleNamespace(q=None, s=None), SimpleNamespace(N=16, K=16, q=None, s=None), torch.zeros(32), torch.zeros(2, dtype=torch.long), torch.zeros(2), 10.0)
+ assert m.FIRES.hits == 0 and m.FIRES.fallback == {"flag_off": 1}
+ monkeypatch.setenv("HY4_DRAFT_MOE_TILES", "1")
+ m = importlib.reload(mods.moe_i8)
+ assert (m.GU_T, m.DN_T) == ((8, 512, 8), (16, 512, 4))
+ m.FIRES.reset()
+ with pytest.raises(Exception):
+ m.experts_forward(SimpleNamespace(N=16, K=32, q=None, s=None), SimpleNamespace(q=None, s=None), SimpleNamespace(N=16, K=16, q=None, s=None), torch.zeros(32), torch.zeros(2, dtype=torch.long), torch.zeros(2), 10.0)
+ assert m.FIRES.hits == 1 and m.FIRES.fallback == {}
+ finally:
+ monkeypatch.undo()
+ importlib.reload(mods.moe_i8)
+
+
+# ---- DENSE_V2 ----------------------------------------------------------------------------------------------------------------------------
+
+def _stock(calls):
+ def fq_gemv_q8_0(xf, packed, out):
+ calls.append("stock")
+ return fq_gemv_q8_0
+
+
+class _Gm:
+ def __init__(self, ok=True):
+ self.ok, self.n = ok, 0
+
+ def gm_dense_q8(self, qb, packed, out, cpb):
+ self.n += 1
+ return self.ok
+
+
+class _Ext:
+ def fq_q8_scratch(self, dev, R, K):
+ return object()
+
+ def fq_quant_q8_1_rows(self, xf, qb):
+ pass
+
+
+def test_dense_gemv_flag_off_is_stock_and_silent(mods, monkeypatch):
+ hf, calls = mods.hy4_forward, []
+ monkeypatch.setattr(hf, "DENSE_V2", [False])
+ hf.dense_gemv(_stock(calls), torch.zeros(4, 256), None, None)
+ assert calls == ["stock"] and hf.DENSE_FIRES.snapshot() == {"v2": 0, "stock": {}}
+
+
[email protected]("shape,name,reason", [((1, 256), "fq_gemv_q8_0", "rows<2"), ((4, 8192 + 32), "fq_gemv_q8_0", "K>kmax"), ((4, 256), "other_gemv", "not_q8_0")])
+def test_dense_gemv_stock_reasons(mods, monkeypatch, shape, name, reason):
+ hf, calls = mods.hy4_forward, []
+ monkeypatch.setattr(hf, "DENSE_V2", [True])
+ g = _stock(calls)
+ g.__name__ = name
+ hf.dense_gemv(g, torch.zeros(*shape), None, None)
+ assert calls == ["stock"] and hf.DENSE_FIRES.snapshot() == {"v2": 0, "stock": {reason: 1}}
+
+
+def test_dense_gemv_no_extension_falls_back(mods, monkeypatch):
+ hf, calls = mods.hy4_forward, []
+ monkeypatch.setattr(hf, "DENSE_V2", [True])
+ monkeypatch.setattr(hf, "_gm", lambda: None)
+ monkeypatch.setattr(hf, "_ext", lambda: None)
+ hf.dense_gemv(_stock(calls), torch.zeros(4, 256), None, None)
+ assert calls == ["stock"] and hf.DENSE_FIRES.snapshot()["stock"] == {"no_gm_ext": 1}
+
+
[email protected]("ok", [True, False])
+def test_dense_gemv_v2_and_rejected(mods, monkeypatch, ok):
+ hf, calls, gm = mods.hy4_forward, [], _Gm(ok)
+ monkeypatch.setattr(hf, "DENSE_V2", [True])
+ monkeypatch.setattr(hf, "_gm", lambda: gm)
+ monkeypatch.setattr(hf, "_ext", lambda: _Ext())
+ hf.dense_gemv(_stock(calls), torch.zeros(4, 256), None, None)
+ assert gm.n == 1
+ if ok:
+ assert calls == [] and hf.DENSE_FIRES.snapshot() == {"v2": 1, "stock": {}}
+ else:
+ assert calls == ["stock"] and hf.DENSE_FIRES.snapshot() == {"v2": 0, "stock": {"kernel_rejected": 1}}
+
+
+# ---- MOE_V2 ------------------------------------------------------------------------------------------------------------------------------
+
+class _MoeDec:
+ def __init__(self, dev, T, topk, K, nff, fmt, E):
+ self.topk, self.args = topk, (T, K, nff, fmt, E)
+
+
+def _rs(**kw):
+ d = dict(fu=8, fd=0, nout=1536, nff=1536, strides=(1536, 2048, 4096), bufs={"gate": torch.zeros(64)}, E=512)
+ d.update(kw)
+ return SimpleNamespace(**d)
+
+
+def moe(mods, monkeypatch):
+ hf = mods.hy4_forward
+ md = SimpleNamespace(MoeDec=_MoeDec)
+ monkeypatch.setattr(hf, "MOE_V2", True)
+ monkeypatch.setattr(hf, "_MD", [md, {}])
+ return hf
+
+
+def test_moe_v2_flag_off_is_silent(mods, monkeypatch):
+ hf = mods.hy4_forward
+ monkeypatch.setattr(hf, "MOE_V2", False)
+ assert hf._moe_v2(_rs(), 1, 1536) is None and hf.MOE_V2_FIRES.snapshot() == {"calls": 0, "fallback": {}}
+
+
+def test_moe_v2_happy_path(moe):
+ h = moe._moe_v2(_rs(), 2, 1536)
+ assert h is not None and h.args == (2, 1536, 1536, "q3_k", 512)
+ assert moe._moe_v2(_rs(fu=0), 2, 1536).args[3] == "q4_k"
+ assert moe.MOE_V2_FIRES.snapshot() == {"calls": 2, "fallback": {}}
+ assert moe._moe_v2(_rs(), 2, 1536) is moe._MD[1][(2, "q3_k", 1536, 1536)] # one holder per (T, fmt, K, nff)
+
+
[email protected]("args,rs,reason", [
+ ((1, 1536, 8), {}, "topk!=16"),
+ ((99, 1536, 16), {}, "T>maxr"),
+ ((1, 1536, 16), {"fu": 5}, "gate_up_fmt"),
+ ((1, 1536, 16), {"fd": 1}, "down_fmt"),
+ ((1, 1536, 16), {"nout": 1024}, "nout!=K"),
+ ((1, 1024, 16), {"nout": 1024}, "shape"),
+ ((1, 1536, 16), {"nff": 2048}, "shape"),
+ ((1, 1536, 16), {"strides": (1536, 2050, 4096)}, "stride_align"),
+])
+def test_moe_v2_fallback_reasons(moe, args, rs, reason):
+ T, K, S = args
+ assert moe._moe_v2(_rs(**rs), T, K, S) is None
+ assert moe.MOE_V2_FIRES.snapshot() == {"calls": 0, "fallback": {reason: 1}}
+
+
+def test_moe_v2_pointer_alignment_and_missing_code_object(moe, monkeypatch):
+ t = torch.zeros(64)
+ odd = t[1:] # 4-byte offset: not 16-byte aligned
+ assert moe._moe_v2(_rs(bufs={"gate": odd}), 1, 1536) is None
+ monkeypatch.setattr(moe, "_MD", [None, {}])
+ assert moe._moe_v2(_rs(), 1, 1536) is None
+ assert moe.MOE_V2_FIRES.snapshot()["fallback"] == {"ptr_align": 1, "no_code_object": 1}
+
+
+def test_moe_v2_topk_other_than_16_is_refused(moe, monkeypatch):
+ class Odd(_MoeDec):
+ def __init__(self, *a):
+ super().__init__(*a)
+ self.topk = 8
+ monkeypatch.setattr(moe._MD[0], "MoeDec", Odd)
+ assert moe._moe_v2(_rs(), 1, 1536) is None and moe.MOE_V2_FIRES.snapshot()["fallback"] == {"topk": 1}
+
+
+# ---- DRAFT_MLA_BG ------------------------------------------------------------------------------------------------------------------------
+
+def test_from_float_follows_the_q8_0_rule(mods):
+ BG = mods.mla_bgemv
+ torch.manual_seed(0)
+ w = torch.randn(3, 5, 64) * 2
+ o = BG.Q8Batched.from_float(w)
+ assert (o.H, o.N, o.K) == (3, 5, 64) and o.q.shape == (3, 5, 64) and o.d.shape == (3, 5, 2)
+ assert o.q.dtype == torch.int8 and o.d.dtype == torch.float16 and int(o.q.abs().max()) <= 127
+ blk = w.reshape(3, 5, 2, 32)
+ assert torch.equal(o.d.float(), (blk.abs().amax(-1) / 127.0).half().float()) # scale = amax / 127, stored fp16
+ deq = o.q.float().reshape(3, 5, 2, 32) * o.d.float()[..., None]
+ assert float((deq - blk).abs().max()) <= float(o.d.float().max()) * 0.51 # round-trip error <= half a step (+ fp16 scale rounding)
+ assert o.draft is True and BG.Q8Batched.draft is False
+
+
+def test_from_float_zero_block_is_finite(mods):
+ o = mods.mla_bgemv.Q8Batched.from_float(torch.zeros(1, 2, 32))
+ assert torch.isfinite(o.d.float()).all() and int(o.q.abs().max()) == 0
+
+
+def test_draft_matrix_mv_is_counted(mods):
+ BG = mods.mla_bgemv
+ o = BG.Q8Batched.from_float(torch.randn(2, 4, 32))
+ with pytest.raises(Exception): # no GPU: the Triton launch fails; the counter is incremented before it
+ o.mv(torch.randn(1, 2, 32))
+ assert BG.DRAFT_FIRES.hits == 1
+
+
+def test_mtp_head_sets_the_draft_matrices_only_with_the_flag():
+ src = _src("mtp_head.py")
+ assert re.search(r'if self\.fast and os\.environ\.get\("HY4_DRAFT_MLA_BG", "0"\) == "1":\s*#?[^\n]*\n\s+from \. import mla_bgemv as _BGM\n\s+mla\.bg_kb, mla\.bg_vb = ', src)
+
+
+# ---- DRAFT_IX_GV + the no_grad regression ------------------------------------------------------------------------------------------------
+
+def test_mmw_without_gv_is_the_gemm_bit_for_bit(mods):
+ SG = mods.step_graph
+ a, w = torch.randn(3, 16), torch.randn(8, 16)
+ ix = SimpleNamespace(w={"x": w})
+ assert torch.equal(SG._mmw(ix, a, "x"), a @ w.T) and SG.IX_GV_FIRES.snapshot() == {"gv": 0, "gemm": {}} # the trunk's indexer: not counted
+ ix.gv = False
+ assert torch.equal(SG._mmw(ix, a, "x"), a @ w.T) and SG.IX_GV_FIRES.snapshot() == {"gv": 0, "gemm": {"flag_off": 1}}
+
+
+def test_mmw_with_gv_takes_the_matvec(mods, monkeypatch):
+ SG = mods.step_graph
+ a, w = torch.randn(1, 16), torch.randn(8, 16)
+ ix = SimpleNamespace(w={"x": w}, gv=True)
+ monkeypatch.setattr(SG, "_RG", SimpleNamespace(usable=lambda a, w: True, logits=lambda a, w: "mv"))
+ assert SG._mmw(ix, a, "x") == "mv"
+ monkeypatch.setattr(SG, "_RG", SimpleNamespace(usable=lambda a, w: False, logits=lambda a, w: "mv"))
+ assert torch.equal(SG._mmw(ix, a, "x"), a @ w.T)
+ assert SG.IX_GV_FIRES.snapshot() == {"gv": 1, "gemm": {"unusable_shape": 1}}
+
+
+def test_indexer_keys_static_keeps_no_grad(mods):
+ SG = mods.step_graph
+ assert hasattr(SG.indexer_keys_static, "__wrapped__") # torch.no_grad() decorates it (b2 619c92f put it on _mmw by mistake)
+ tree = ast.parse(_src("step_graph.py"))
+ deco = {n.name: [ast.unparse(d) for d in n.decorator_list] for n in tree.body if isinstance(n, ast.FunctionDef)}
+ assert "torch.no_grad()" in deco["indexer_keys_static"] and deco["_mmw"] == []
+
+
+# ---- the fires line ----------------------------------------------------------------------------------------------------------------------
+
+def test_fires_line(mods):
+ LF = mods.lever_fires
+ assert "none" in LF.line()
+ mods.hy4_forward.DENSE_FIRES.hit()
+ mods.hy4_forward.DENSE_FIRES.miss("rows<2")
+ mods.moe_i8.FIRES.hit()
+ ln = LF.line()
+ assert "FIRES dense_v2 {'v2': 1, 'stock': {'rows<2': 1}}" in ln and "FIRES draft_moe_tiles {'calls': 1, 'fallback': {}}" in ln
diff --git a/tools/hy4/engine.py b/tools/hy4/engine.py
index 99c352e..c81c982 100644
--- a/tools/hy4/engine.py
+++ b/tools/hy4/engine.py
@@ -47,6 +47,8 @@ def _stub_package(tree: str):
class Hy4Engine:
+ LF = None # loader.lever_fires, set by load()
+
def __init__(self, tree: str, gguf: str, ctx: int = 16384, k: int = 3, chunk: int = CHUNK_DEFAULT, prime_rows: int = 0):
self.tree, self.gguf, self.k, self.chunk = tree, gguf, k, chunk
self.ctx = ctx
@@ -95,7 +97,9 @@ class Hy4Engine:
from exllamav3.loader import mla_hy4 as mh
from exllamav3.loader import step_graph as SG
from exllamav3.loader import mtp_head as MH
- self.hf, self.mh, self.SG, self.MH = hf, mh, SG, MH
+ from exllamav3.loader import lever_fires as LF
+ from exllamav3.loader import moe_i8, mla_bgemv # noqa: F401 (register their counters)
+ self.hf, self.mh, self.SG, self.MH, self.LF = hf, mh, SG, MH, LF
self._decode_flags()
self.phase("prefill") # the prefill kernels are selected at layer load time too (as in the prefill harness)
t0 = time.time()
@@ -171,6 +175,8 @@ class Hy4Engine:
self.SG.PRIME_IX_BLK = old
self.reset()
print(f"warm-up {n} tokens: {time.perf_counter() - t0:.1f} s", flush=True)
+ if self.LF is not None:
+ print(self.LF.line(), flush=True) # lever fires after the warm-up captured every graph: an arm whose flagged lever shows no hit (or a fallback reason) fails
if os.environ.get("HY4_WARMUP_TAILS", "1") == "1":
self.warmup_tails()
diff --git a/tools/hy4/install_strix.sh b/tools/hy4/install_strix.sh
index f64943e..fda74e4 100755
--- a/tools/hy4/install_strix.sh
+++ b/tools/hy4/install_strix.sh
@@ -29,6 +29,9 @@ echo "install_strix: [1/3] sparse prefill attention (hipsp/libspmla.so)"
bash hipsp/build.sh hipsp/sp_mla.cu hipsp/libspmla.so
echo "install_strix: [2/3] MoE expert kernels (exl3_gm_ext)"
EXL3_GM_BUILD=1 python -c "from exllamav3 import gm_ext; assert gm_ext.get() is not None, \"gm_ext build failed\""
+echo "install_strix: [2b/3] decode expert code object (moe_dec.co, used only with HY4_MOE_V2=1; a failure here is not fatal: the lever then falls back and says so)"
+MOE_CO=${MOE_DEC_CO:-$ROOT/exllamav3/exllamav3_ext/hip_kq/moe_dec.co}
+KYOJIN_ENGINE_DIR=$ROOT bash exllamav3/exllamav3_ext/hip_kq/build_moe.sh exllamav3/exllamav3_ext/hip_kq/moe_dec.cu "$MOE_CO" >/dev/null 2>&1; [ -s "$MOE_CO" ] || echo "install_strix: WARNING moe_dec.co not built: HY4_MOE_V2=1 will fall back to the shipped kernels (see the FIRES moe_v2 line)" >&2
echo "install_strix: [3/3] CK latent attention (libckmla.so)"
bash tools/strix_halo/ck_fmha/build_mla.sh
GM=${EXL3_GM_BUILD_DIR:-$HOME/.cache/exl3_gm_ext}; CK=${EXL3_CKMLA_OUT:-${XDG_CACHE_HOME:-$HOME/.cache}/kyojin/ck-fmha/libckmla.so}
diff --git a/tools/hy4/mu_engine.py b/tools/hy4/mu_engine.py
index a9072dc..e6fce0e 100644
--- a/tools/hy4/mu_engine.py
+++ b/tools/hy4/mu_engine.py
@@ -331,3 +331,5 @@ 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)
+ if eng.LF is not None:
+ print(eng.LF.line(), flush=True)
diff --git a/tools/hy4/step/ab_dend.py b/tools/hy4/step/ab_dend.py
index bdf56aa..8d3075d 100644
--- a/tools/hy4/step/ab_dend.py
+++ b/tools/hy4/step/ab_dend.py
@@ -1,5 +1,5 @@
"""ab_dend.py: ONE load; paired ABBA graph-replay verify-round wall, T = 1..6, ctx 1000 / 4000, arm A = stock dense Q8_0 GEMV, arm B = HY4_DENSE_V2 (gm_ext gm_dense_q8 for 2..16 rows, K <= 8192).
-cwd = tree. Env: EXL3_GM_BUILD_DIR (the gm_ext build holding gm_dense_q8), PCTXS, PTS. Arm flip = fwm.DENSE_V2[0] + GR.clear() (graphs re-captured). Prints per-T ms for both arms, the logit equality (bit-identical expected) and the dense launch count."""
+cwd = tree. Env: GGUF (model path), WIKI (json list of token ids), EXL3_GM_BUILD_DIR (the gm_ext build holding gm_dense_q8), PCTXS, PTS. Arm flip = fwm.DENSE_V2[0] + GR.clear() (graphs re-captured). Prints per-T ms for both arms, the logit equality (bit-identical expected) and the dense launch count."""
import json, os, statistics, sys, time
tree = os.getcwd()
sys.path.insert(0, os.path.join(tree, "tools", "hy4"))
@@ -7,7 +7,7 @@ import serve
serve.apply_env(16384)
import torch
from engine import Hy4Engine
-GGUF = os.environ.get("GGUF", "/home/kamel/models/hy4-flash-gguf/Hy4-flash-Q3_K-00001-of-00002.gguf")
+GGUF = os.environ["GGUF"]
e = Hy4Engine(tree, GGUF, ctx=16384, k=3)
e.load(print)
GR, M = e.GR, e.M
@@ -15,7 +15,7 @@ fwm = sys.modules[type(M).__module__]
g = fwm._gm()
print("gm_ext", None if g is None else (g.__file__, hasattr(g, "gm_dense_q8")), flush=True)
assert g is not None and hasattr(g, "gm_dense_q8"), "gm_dense_q8 missing: set EXL3_GM_BUILD_DIR to the build holding it"
-wiki = json.load(open(os.environ.get("WIKI", "/home/kamel/scratch_w5/wiki_ids.json")))
+wiki = json.load(open(os.environ["WIKI"]))
pc, sync = time.perf_counter, torch.cuda.synchronize
diff --git a/tools/hy4/step/ab_exp.py b/tools/hy4/step/ab_exp.py
index cf7d8cf..654ea8c 100644
--- a/tools/hy4/step/ab_exp.py
+++ b/tools/hy4/step/ab_exp.py
@@ -1,7 +1,7 @@
"""ab_exp.py: ONE load (HY4_MOE_V2=1 in the environment, code object exllamav3_ext/hip_kq/moe_dec.co built by hip_kq/build_moe.sh); cwd = tree.
Paired ABBA graph-replay step wall, T = 1..6, ctx 1000 / 4000 (PCTXS, PTS): arm A = shipped grouped kernel (fq_moe_kq_grouped_mixed_q8), arm B = HY4_MOE_V2 stages.
Prints head_ab.log style lines (ARM ... done, AB ctx T: A [...] B [...] ms delta, KL_mean top1_agree: the arms are bit-equal where the code object is bit-equal, so KL 0 is expected;
-a nonzero KL is a kernel bug, not noise). cwd = tree."""
+a nonzero KL is a kernel bug, not noise). cwd = tree. Env: GGUF (model path), WIKI (json list of token ids)."""
import json, os, statistics, sys, time
tree = os.getcwd()
sys.path.insert(0, os.path.join(tree, "tools", "hy4"))
@@ -9,13 +9,13 @@ import serve
serve.apply_env(16384)
import torch
from engine import Hy4Engine
-GGUF = os.environ.get("GGUF", "/home/kamel/models/hy4-flash-gguf/Hy4-flash-Q3_K-00001-of-00002.gguf")
+GGUF = os.environ["GGUF"]
e = Hy4Engine(tree, GGUF, ctx=16384, k=3)
e.load(print)
GR, M = e.GR, e.M
fwm = sys.modules[type(M).__module__]
assert fwm.MOE_V2, "run with HY4_MOE_V2=1"
-wiki = json.load(open(os.environ.get("WIKI", "/home/kamel/scratch_w5/wiki_ids.json")))
+wiki = json.load(open(os.environ["WIKI"]))
pc, sync = time.perf_counter, torch.cuda.synchronize
diff --git a/tools/hy4/step/mtp_arms.sh b/tools/hy4/step/mtp_arms.sh
index 44fd853..f270f97 100644
--- a/tools/hy4/step/mtp_arms.sh
+++ b/tools/hy4/step/mtp_arms.sh
@@ -1,6 +1,6 @@
#!/bin/bash
# arms.sh "ARMNAME:K=V,K=V" ...: one mtp_items round timing per arm (same process env otherwise), step-1 output checked against arm A
-cd ~/hermes-work/relay1114/hy4s/wt_mtp
+cd "${TREE:-$(git rev-parse --show-toplevel)}" # env: GGUF (model path) + the HY4_DRAFT_* arms
REF=/tmp/mtp_ref_$$.pt
for arm in "$@"; do
n=${arm%%:*}; kv=${arm#*:}; envs=""; [ -n "$kv" ] && envs=$(echo $kv | tr ',' ' ')
diff --git a/tools/hy4/step/opbench.py b/tools/hy4/step/opbench.py
index f73b174..70d8bfc 100644
--- a/tools/hy4/step/opbench.py
+++ b/tools/hy4/step/opbench.py
@@ -26,7 +26,7 @@ def shipped_env():
ENV = shipped_env()
for _k, _v in ENV.items():
os.environ.setdefault(_k, _v)
-EXTRA_FLAGS = ("HY4_DENSE_V2", "HY4_DENSE_V2_CPB", "HY4_FFN_GROUPED", "BOLT_FQ_Q8_MROWS") # op-agent flags outside SHIPPED_ENV: hashed only when set, so the existing point keys stay valid
+EXTRA_FLAGS = ("HY4_DENSE_V2", "HY4_MOE_V2", "HY4_DENSE_V2_CPB", "HY4_FFN_GROUPED", "BOLT_FQ_Q8_MROWS") # op-agent flags outside SHIPPED_ENV: hashed only when set, so the existing point keys stay valid
FLAGHASH = hashlib.sha1(json.dumps({**{k: os.environ.get(k) for k in sorted(ENV)}, **{k: os.environ[k] for k in EXTRA_FLAGS if k in os.environ}}, sort_keys=True).encode()).hexdigest()[:8]
sys.path.insert(0, os.path.join(TREE, "tools", "hy4"))