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 router: fp16 resident weights for the router mat-vec (HY4_RG_F16=1, opt-in), fp32 accumulate

YanissAmzb783b0842d54
diff --git a/exllamav3/loader/hy4_forward.py b/exllamav3/loader/hy4_forward.py
index 3f88257..d569163 100644
--- a/exllamav3/loader/hy4_forward.py
+++ b/exllamav3/loader/hy4_forward.py
@@ -526,7 +526,7 @@ class Hy4Forward:
if v is not None:
L.dense[:2] = v
else:
- L.router = g.get_tensor(b + "ffn_gate_inp.weight").float().to(dev)
+ L.router = _RG.store(g.get_tensor(b + "ffn_gate_inp.weight").float().to(dev)) # HY4_RG_F16=1: fp16 resident
L.rbias = g.get_tensor(b + "exp_probs_b.bias").float().to(dev)
L.rdown, L.rup = self._w(b + "ffn_routed_down.weight"), self._w(b + "ffn_routed_up.weight")
L.shexp = [self._w(f"{b}ffn_{n}_shexp.weight") for n in ("gate", "up", "down")]
@@ -597,7 +597,7 @@ class Hy4Forward:
pf = bool(PF_MOE and T > MMVQ_MAXR and dev.type == "cuda" and rsp is not None and rsp.fu in _pk().FROM_GROUPED and rsp.fd in _pk().FROM_GROUPED)
with tm.t("router"):
if _rf.ENABLED: # HY4_REF_FUSED=1: one router kernel; the host sync (tolist) only where the pread loop needs it
- sel, w = _rf.router_select(_RG.logits(x, L.router) if _RG.usable(x, L.router) else x @ L.router.T, L.rbias, self.topk, self.w_scale)
+ sel, w = _rf.router_select(_RG.mm(x, L.router), L.rbias, self.topk, self.w_scale)
sel_l = [] if (pf or (self.res.get(i) is not None and T <= MMVQ_MAXR and dev.type == "cuda")) else sorted(set(sel.flatten().tolist()))
else:
if PF_ROUTER and T > MMVQ_MAXR and dev.type == "cuda":
@@ -605,7 +605,7 @@ class Hy4Forward:
L.router16 = L.router.half().contiguous()
p = torch.sigmoid(_pk().mm_f32(_pk().to_f16(x), L.router16.T))
else:
- p = torch.sigmoid(_RG.logits(x, L.router) if _RG.usable(x, L.router) else x @ L.router.T)
+ p = torch.sigmoid(_RG.mm(x, L.router))
sel = torch.sort(p + L.rbias, dim=-1, descending=True, stable=True).indices[:, :self.topk] # stable: tied experts resolve to the lowest id every call (torch.topk tie order varies between calls on gfx1151)
w = torch.gather(p, 1, sel)
w = w / w.sum(-1, keepdim=True).clamp(min=6.103515625e-5) * self.w_scale
@@ -727,7 +727,7 @@ class Hy4Forward:
meta=torch.zeros(8 * S * 9, dtype=torch.int32, device=dev), nometa=torch.empty(0, dtype=torch.int32, device=dev), nores=torch.empty(0, dtype=torch.float32, device=dev))
sel, w = st.sel[:T], st.w[:T]
xc = x.contiguous()
- gm.gm_route(xc, L.router, L.rbias, st.sc[:T], sel, w, 2, True, self.w_scale, 6.103515625e-5)
+ gm.gm_route(xc, L.router if L.router.dtype == torch.float32 else L.router.float(), L.rbias, st.sc[:T], sel, w, 2, True, self.w_scale, 6.103515625e-5)
z3 = st.z3[:3 * T * N]
gm.gm_qkv_decode(xc, w3[0], [3, 3, 3], z3.view(1, -1), st.qa)
z, g, u = z3[:T * N].view(T, N), z3[T * N:2 * T * N].view(T, N), z3[2 * T * N:].view(T, N)
diff --git a/exllamav3/loader/router_gemv.py b/exllamav3/loader/router_gemv.py
index 9fc6d8b..d6e654f 100644
--- a/exllamav3/loader/router_gemv.py
+++ b/exllamav3/loader/router_gemv.py
@@ -13,6 +13,7 @@ MAXT = 8
BN = int(os.environ.get("HY4_RG_BN", "4"))
BK = int(os.environ.get("HY4_RG_BK", "256"))
NW = int(os.environ.get("HY4_RG_NW", "4"))
+F16 = os.environ.get("HY4_RG_F16", "0") == "1" # router weights stored fp16 (GGUF F32 -> fp16: rel 5e-4 per weight, logits ~1e-5): half the bytes of the 41 gemvs; fp32 accumulate
@triton.jit
@@ -25,17 +26,27 @@ def _k_rg(x_ptr, w_ptr, o_ptr, N, K, T, sxt, BT: tl.constexpr, BN: tl.constexpr,
for k0 in range(0, K, BK):
cols = k0 + tl.arange(0, BK)
cm = cols < K
- w = tl.load(w_ptr + rows[:, None] * K + cols[None, :], mask=rm[:, None] & cm[None, :], other=0.0)
+ w = tl.load(w_ptr + rows[:, None] * K + cols[None, :], mask=rm[:, None] & cm[None, :], other=0.0).to(tl.float32)
xv = tl.load(x_ptr + tt[:, None] * sxt + cols[None, :], mask=tm[:, None] & cm[None, :], other=0.0)
acc += tl.sum(w[None, :, :] * xv[:, None, :], axis=2)
tl.store(o_ptr + tt[:, None] * N + rows[None, :], acc, mask=tm[:, None] & rm[None, :])
def usable(x, w):
- return (ENABLED and x.dtype == torch.float32 and w.dtype == torch.float32 and x.dim() == 2 and 1 <= x.shape[0] <= MAXT and w.is_contiguous()
+ return (ENABLED and x.dtype == torch.float32 and w.dtype in (torch.float32, torch.float16) and x.dim() == 2 and 1 <= x.shape[0] <= MAXT and w.is_contiguous()
and x.stride(-1) == 1 and (x.is_cuda or os.environ.get("TRITON_INTERPRET", "0") == "1"))
+def store(w):
+ """router weight as kept resident: fp16 when HY4_RG_F16=1 (and the gemv is on), else unchanged fp32"""
+ return w.half().contiguous() if (ENABLED and F16) else w
+
+
+def mm(x, w):
+ """x [T, K] fp32 @ w[N, K].T -> [T, N] fp32: the Triton mat-vec when usable, else the matmul (fp16 weights upcast)"""
+ return logits(x, w) if usable(x, w) else x @ w.float().T
+
+
def logits(x, w, bn=None, bk=None, nw=None):
"""x [T, K] fp32, w [N, K] fp32 (row-major) -> [T, N] fp32 = x @ w.T"""
T, K = x.shape
diff --git a/tools/hy4/step/rg_test.py b/tools/hy4/step/rg_test.py
new file mode 100644
index 0000000..e56ca6c
--- /dev/null
+++ b/tools/hy4/step/rg_test.py
@@ -0,0 +1,29 @@
+"""rg_test.py: router gemv fp32 vs fp16 weights: logits error, top-16 set agreement on random x, time on GPU (DEV=cuda)."""
+import os, statistics, importlib.util
+import torch
+tree = os.getcwd()
+sp = importlib.util.spec_from_file_location("router_gemv", os.path.join(tree, "exllamav3", "loader", "router_gemv.py")); rg = importlib.util.module_from_spec(sp); sp.loader.exec_module(rg)
+dev = os.environ.get("DEV", "cuda"); CPU = dev == "cpu"
+N, K = (64, 256) if CPU else (512, 3072)
+torch.manual_seed(0)
+W = torch.randn(N, K, device=dev) * 0.03
+W16 = W.half().contiguous()
+rg.ENABLED = True
+def bench(fn, n=50):
+ for _ in range(3): fn()
+ torch.cuda.synchronize(); ts = []
+ for _ in range(n):
+ a, b = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
+ a.record(); fn(); b.record(); torch.cuda.synchronize(); ts.append(a.elapsed_time(b) * 1000)
+ return statistics.median(ts)
+for T in (1, 2, 6):
+ x = torch.randn(T, K, device=dev)
+ ref = (x.double() @ W.double().T).float()
+ a, b = rg.mm(x, W), rg.mm(x, W16)
+ ea, eb = ((a - ref).norm() / ref.norm()).item(), ((b - ref).norm() / ref.norm()).item()
+ k = 8 if CPU else 16
+ same = (a.topk(k, -1).indices.sort(-1).values == b.topk(k, -1).indices.sort(-1).values).all().item()
+ line = f"T {T}: rel err fp32 {ea:.1e} fp16w {eb:.1e} topk same {same}"
+ if not CPU: line += f"; fp32 {bench(lambda: rg.mm(x, W)):.0f} us fp16 {bench(lambda: rg.mm(x, W16)):.0f} us"
+ print(line, flush=True)
+print("RG_DONE", flush=True)