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: group the FFN projections that read one activation into one dense GEMV (flag HY4_FFN_GROUPED, load time)

YanissAmzd177506fcc76
diff --git a/exllamav3/loader/attn_grouped.py b/exllamav3/loader/attn_grouped.py
index 6bc812e..edba632 100644
--- a/exllamav3/loader/attn_grouped.py
+++ b/exllamav3/loader/attn_grouped.py
@@ -10,7 +10,6 @@ from __future__ import annotations
import torch
from .hy4_forward import QLinear, DENSE_MAXR
-from . import q8_soa as _SOA
# attribute names of the MLA object that read the layer input `cur` (wq_a, wkv_a, wgate); keyed by role, not by model
INPUT_SHARED = ("wq_a", "wkv_a", "wgate")
@@ -21,8 +20,7 @@ class _Group:
self.sizes = [q.shape[0] for q in lins]
self.offs = [sum(self.sizes[:i]) for i in range(len(lins))]
self.K, self.gemv, self.stats = lins[0].shape[1], lins[0].gemv, lins[0].stats
- self.soa = _SOA.Q8Soa.cat([q.soa for q in lins]) if all(getattr(q, "soa", None) is not None for q in lins) else None
- self.packed = torch.cat([q.packed for q in lins], 0) if self.soa is None else _SOA.Meta((sum(self.sizes),) + tuple(lins[0].packed.shape[1:]), lins[0].packed.device)
+ self.packed = torch.cat([q.packed for q in lins], 0)
self.ref = None # (x, x._version, outs)
def run(self, x):
@@ -31,11 +29,8 @@ class _Group:
return r[2]
x2 = x.reshape(-1, self.K)
xf = x2.float().contiguous()
- if self.soa is not None:
- out = self.soa.mv(xf) if xf.shape[0] == 1 else xf @ self.soa.dense().T
- else:
- out = torch.empty(xf.shape[0], sum(self.sizes), dtype=torch.float32, device=x.device)
- self.gemv(xf, self.packed, out)
+ out = torch.empty(xf.shape[0], sum(self.sizes), dtype=torch.float32, device=x.device)
+ self.gemv(xf, self.packed, out)
if self.stats is not None:
self.stats["dense_gemv"] = self.stats.get("dense_gemv", 0) + 1
self.stats["attn_grouped_calls"] = self.stats.get("attn_grouped_calls", 0) + 1
@@ -59,8 +54,6 @@ class GroupedView(QLinear):
def __init__(self, lin, group, idx, packed_view):
super().__init__(packed_view, lin.ty, lin.spec, lin.gemv, lin.stats)
self.group, self.idx, self.orig_call = group, idx, QLinear.__call__
- if group.soa is not None:
- self.soa = group.soa.slice(group.offs[idx], group.sizes[idx])
@property
def T(self):
diff --git a/exllamav3/loader/attn_grouped.py.pre_soa b/exllamav3/loader/attn_grouped.py.pre_soa
deleted file mode 100644
index edba632..0000000
--- a/exllamav3/loader/attn_grouped.py.pre_soa
+++ /dev/null
@@ -1,87 +0,0 @@
-"""HY4_ATTN_GROUPED=1: attention projections that read the SAME input row run as ONE dense GEMV launch on the stored bytes.
-
-Generic by shape / stored type: any set of QLinear (hy4_forward.py) with equal K, stored ggml type and GEMV is concatenated along N
-(rows of the stored [N, K/blk, bb] bytes; the per-row dot never depends on N, so each output row is bit-identical to the separate
-launch). The originals are re-pointed to slices of the concatenated buffer (no extra resident bytes). One activation quantisation
-and one launch replace n. Results are cached per input tensor (identity + version), so a later projection of the same row
-(wkv_a, wgate, the indexer's repeated wq_a) is a cache hit. Rows > DENSE_MAXR (prefill) use each member's own path unchanged.
-"""
-from __future__ import annotations
-import torch
-
-from .hy4_forward import QLinear, DENSE_MAXR
-
-# attribute names of the MLA object that read the layer input `cur` (wq_a, wkv_a, wgate); keyed by role, not by model
-INPUT_SHARED = ("wq_a", "wkv_a", "wgate")
-
-
-class _Group:
- def __init__(self, lins):
- self.sizes = [q.shape[0] for q in lins]
- self.offs = [sum(self.sizes[:i]) for i in range(len(lins))]
- self.K, self.gemv, self.stats = lins[0].shape[1], lins[0].gemv, lins[0].stats
- self.packed = torch.cat([q.packed for q in lins], 0)
- self.ref = None # (x, x._version, outs)
-
- def run(self, x):
- r = self.ref
- if r is not None and r[0] is x and r[1] == x._version:
- return r[2]
- x2 = x.reshape(-1, self.K)
- xf = x2.float().contiguous()
- out = torch.empty(xf.shape[0], sum(self.sizes), dtype=torch.float32, device=x.device)
- self.gemv(xf, self.packed, out)
- if self.stats is not None:
- self.stats["dense_gemv"] = self.stats.get("dense_gemv", 0) + 1
- self.stats["attn_grouped_calls"] = self.stats.get("attn_grouped_calls", 0) + 1
- lead = x.shape[:-1]
- outs = [out[:, o:o + n].to(x.dtype).reshape(*lead, n) for o, n in zip(self.offs, self.sizes)]
- self.ref = (x, x._version, outs)
- return outs
-
-
-class _GT:
- def __init__(self, v):
- self.v = v
-
- def __rmatmul__(self, x):
- return self.v(x)
-
-
-class GroupedView(QLinear):
- """a member of a group: same attributes as the QLinear, decode rows go through the shared launch"""
-
- def __init__(self, lin, group, idx, packed_view):
- super().__init__(packed_view, lin.ty, lin.spec, lin.gemv, lin.stats)
- self.group, self.idx, self.orig_call = group, idx, QLinear.__call__
-
- @property
- def T(self):
- return _GT(self)
-
- def __call__(self, x):
- if x.numel() // self.shape[1] <= DENSE_MAXR and self.gemv is not None:
- return self.group.run(x)[self.idx]
- return QLinear.__call__(self, x)
-
-
-def group_linears(lins):
- """list of QLinear reading the same input -> list of GroupedView (same order), or None when they cannot share one launch"""
- if len(lins) < 2 or not all(isinstance(q, QLinear) and q.gemv is not None for q in lins):
- return None
- k = (lins[0].shape[1], lins[0].ty, lins[0].gemv)
- if any((q.shape[1], q.ty, q.gemv) != k for q in lins) or len({q.packed.device for q in lins}) != 1:
- return None
- grp = _Group(lins)
- return [GroupedView(q, grp, i, grp.packed[o:o + n]) for i, (q, o, n) in enumerate(zip(lins, grp.offs, grp.sizes))]
-
-
-def install(mla, names=INPUT_SHARED):
- """regroup mla.<names> in place; returns True when grouped (originals' bytes are freed, the views share one buffer)"""
- lins = [getattr(mla, n, None) for n in names]
- views = group_linears(lins) if all(l is not None for l in lins) else None
- if views is None:
- return False
- for n, v in zip(names, views):
- setattr(mla, n, v)
- return True
diff --git a/exllamav3/loader/hy4_forward.py b/exllamav3/loader/hy4_forward.py
index 8390cc3..2086696 100644
--- a/exllamav3/loader/hy4_forward.py
+++ b/exllamav3/loader/hy4_forward.py
@@ -28,7 +28,6 @@ from .engram_rows import F8Rows, Hy4Engram, load_dense, _dequant_q8_0, rms
from .mla_hy4 import Hy4MLA
from . import ref_fused as _rf
from . import step_nosync as _ns
-from . import q8_soa as _SOA
from . import mla_bgemv as _BGM
from . import head_bf16 as _HB
from . import attn_eager as _AE
@@ -180,27 +179,19 @@ class QLinear:
def __init__(self, packed, ty, spec, gemv, stats=None):
self.packed, self.ty, self.spec, self.gemv, self.stats = packed, int(ty), spec, gemv, stats
self.shape = (packed.shape[0], packed.shape[1] * spec[0])
- self.soa = None
- if _SOA.ENABLED and isinstance(packed, torch.Tensor) and packed.is_cuda and spec[2] == "fq_gemv_q8_0": # HY4_Q8_SOA=1: repack, free the stored bytes
- self.soa = _SOA.Q8Soa(packed)
- self.packed = _SOA.Meta(packed.shape, packed.device)
@property
def T(self):
return _QT(self)
def dense(self):
- return self.soa.dense() if self.soa is not None else self.spec[3](self.packed)
+ return self.spec[3](self.packed)
def __call__(self, x):
K, N = self.shape[1], self.shape[0]
lead = x.shape[:-1]
x2 = x.reshape(-1, K)
- if self.soa is not None and x2.shape[0] == 1:
- out = self.soa.mv(x2.float().contiguous())
- if self.stats is not None:
- self.stats["dense_soa"] = self.stats.get("dense_soa", 0) + 1
- elif x2.shape[0] <= DENSE_MAXR and self.gemv is not None and self.soa is None:
+ if x2.shape[0] <= DENSE_MAXR and self.gemv is not None:
xf = x2.float().contiguous()
out = torch.empty(xf.shape[0], N, dtype=torch.float32, device=x.device)
self.gemv(xf, self.packed, out)
@@ -409,11 +400,21 @@ class Hy4Forward:
L.attn_norm, L.ffn_norm, L.post_ffw = (load_dense(g, b + n).to(dev) for n in ("attn_norm.weight", "ffn_norm.weight", "post_ffw_norm.weight"))
if i < self.n_dense:
L.dense = [self._w(f"{b}ffn_{n}.weight") for n in ("gate", "up", "down")]
+ if os.environ.get("HY4_FFN_GROUPED", "0") == "1":
+ from .attn_grouped import group_linears
+ v = group_linears(L.dense[:2])
+ if v is not None:
+ L.dense[:2] = v
else:
L.router = g.get_tensor(b + "ffn_gate_inp.weight").float().to(dev)
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")]
+ if os.environ.get("HY4_FFN_GROUPED", "0") == "1":
+ from .attn_grouped import group_linears
+ v = group_linears([L.rdown, L.shexp[0], L.shexp[1]])
+ if v is not None:
+ L.rdown, L.shexp[0], L.shexp[1] = v
L.ety = g.infos[b + "ffn_gate_exps.weight"][0]
L.ety_down = g.infos[b + "ffn_down_exps.weight"][0]
L.ix = bool(self.use_indexer and self.idx_types[i] and not self.swa[i] and (b + "indexer.attn_k.weight") in g.infos)
diff --git a/exllamav3/loader/hy4_forward.py.pre_soa b/exllamav3/loader/hy4_forward.py.pre_ffng
similarity index 100%
rename from exllamav3/loader/hy4_forward.py.pre_soa
rename to exllamav3/loader/hy4_forward.py.pre_ffng
diff --git a/exllamav3/loader/q8_soa.py b/exllamav3/loader/q8_soa.py
deleted file mode 100644
index e17aef5..0000000
--- a/exllamav3/loader/q8_soa.py
+++ /dev/null
@@ -1,101 +0,0 @@
-"""HY4_Q8_SOA=1: dense Q8_0 decode GEMV on a structure-of-arrays repack (int8 q [N, K] + fp16 block scales [N, K/32]), Triton.
-
-The stored Q8_0 layout is 34-byte blocks (fp16 d + 32 int8): not 4-byte aligned, so the C++ kernel (fq_gemv_q8_0) reads every weight through
-16-bit loads (16 loads per 34 bytes). Repacked, a weight row is one contiguous int8 run: the kernel below reads 16-byte vectors and keeps
-many bytes in flight. Same maths as fq_gemv_q8_0 (llama.cpp mmvq order): x is quantised to Q8_1 per 32-block (d = amax / 127 in fp32, q =
-round-half-away(x / d), the scale USED in the dot is d rounded to fp16), integer block dot, acc += (dw * da) * isum. Only the summation
-order over blocks differs. Rows M == 1 only (decode); callers keep the old path for M > 1."""
-import os
-
-import torch
-import triton
-import triton.language as tl
-
-ENABLED = os.environ.get("HY4_Q8_SOA", "0") == "1"
-BN = int(os.environ.get("HY4_Q8_BN", "16"))
-BB = int(os.environ.get("HY4_Q8_BB", "16"))
-
-
-def _k_xq(x_ptr, q_ptr, d_ptr, NB):
- b = tl.program_id(0)
- offs = b * 32 + tl.arange(0, 32)
- x = tl.load(x_ptr + offs)
- amax = tl.max(tl.abs(x), axis=0)
- d = amax / 127.0
- ds = tl.where(amax == 0.0, 1.0, d)
- v = x / ds
- a = tl.abs(v)
- r = tl.floor(a)
- r = tl.where(a - r >= 0.5, r + 1.0, r) # roundf: half away from zero
- r = tl.where(v < 0, -r, r)
- r = tl.minimum(tl.maximum(r, -127.0), 127.0)
- r = tl.where(amax == 0.0, 0.0, r)
- tl.store(q_ptr + offs, r.to(tl.int8))
- tl.store(d_ptr + b, d.to(tl.float16).to(tl.float32))
-
-
-def _k_q8(q_ptr, d_ptr, xq_ptr, xd_ptr, o_ptr, N, K, NB, BN: tl.constexpr, BB: tl.constexpr):
- rows = tl.program_id(0) * BN + tl.arange(0, BN)
- rm = rows < N
- acc = tl.zeros([BN], dtype=tl.float32)
- lane = tl.arange(0, 32)
- for b0 in range(0, NB, BB):
- blks = b0 + tl.arange(0, BB)
- bm = blks < NB
- cols = blks[:, None] * 32 + lane[None, :] # [BB, 32]
- w = tl.load(q_ptr + rows[:, None, None] * K + cols[None, :, :], mask=rm[:, None, None] & bm[None, :, None], other=0)
- xq = tl.load(xq_ptr + cols, mask=bm[:, None], other=0)
- isum = tl.sum(w.to(tl.int32) * xq.to(tl.int32)[None, :, :], axis=2) # [BN, BB]
- dw = tl.load(d_ptr + rows[:, None] * NB + blks[None, :], mask=rm[:, None] & bm[None, :], other=0.0).to(tl.float32)
- da = tl.load(xd_ptr + blks, mask=bm, other=0.0)
- acc += tl.sum(dw * da[None, :] * isum.to(tl.float32), axis=1)
- tl.store(o_ptr + rows, acc, mask=rm)
-
-
-class Meta:
- """shape / device stand-in for freed stored bytes (callers only read .shape / .device)"""
-
- def __init__(self, shape, device):
- self.shape, self.device = tuple(shape), device
-
- def __getitem__(self, sl):
- n = len(range(*sl.indices(self.shape[0])))
- return Meta((n,) + self.shape[1:], self.device)
-
-
-class Q8Soa:
- """a [N, K] Q8_0 matrix as int8 q [N, K] + fp16 d [N, K/32] on a device (from the stored [N, nb, 34] bytes)"""
-
- def __init__(self, packed):
- N, nb, _ = packed.shape
- self.d = packed[:, :, 0:2].contiguous().view(torch.float16).reshape(N, nb).contiguous()
- self.q = packed[:, :, 2:].contiguous().view(torch.int8).reshape(N, nb * 32).contiguous()
- self.N, self.K, self.nb = N, nb * 32, nb
-
- @staticmethod
- def cat(parts):
- o = object.__new__(Q8Soa)
- o.q = torch.cat([p.q for p in parts], 0)
- o.d = torch.cat([p.d for p in parts], 0)
- o.N, o.K, o.nb = o.q.shape[0], parts[0].K, parts[0].nb
- return o
-
- def slice(self, o, n):
- r = object.__new__(Q8Soa)
- r.q, r.d, r.N, r.K, r.nb = self.q[o:o + n], self.d[o:o + n], n, self.K, self.nb
- return r
-
- def dense(self):
- return (self.q.float().reshape(self.N, self.nb, 32) * self.d.float()[:, :, None]).reshape(self.N, self.K)
-
- def mv(self, x, out=None):
- """x [1, K] fp32 contiguous -> [1, N] fp32"""
- xq = torch.empty(self.K, dtype=torch.int8, device=x.device)
- xd = torch.empty(self.nb, dtype=torch.float32, device=x.device)
- _k_xq[(self.nb,)](x, xq, xd, self.nb, num_warps=1)
- if out is None:
- out = torch.empty(1, self.N, dtype=torch.float32, device=x.device)
- _k_q8[(triton.cdiv(self.N, BN),)](self.q, self.d, xq, xd, out, self.N, self.K, self.nb, BN=BN, BB=BB, num_warps=4)
- return out