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.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
Hy4 k_b / v_b: verify rows on tl.dot (HY4_BG_DOT=1, opt-in): exact int8 -> fp16, block scale on the fp32 partial
YanissAmz7f65c8138c2f
diff --git a/exllamav3/loader/mla_bgemv.py b/exllamav3/loader/mla_bgemv.pyindex 5f4dfa6..4039ba0 100644--- a/exllamav3/loader/mla_bgemv.py+++ b/exllamav3/loader/mla_bgemv.py@@ -15,6 +15,9 @@ 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"))ROW_TILES = os.environ.get("HY4_ROW_TILES", "0") == "1" # 1 = tile sizes tuned on the Strix for verify rows (T >= 4: BN 32, BK 32; box microbench 19/11)+DOT = os.environ.get("HY4_BG_DOT", "0") == "1" # 1 = verify rows (T >= 2) on tl.dot: int8 -> fp16 exact, x = hi + lo fp16, block scale applied to the fp32 partial (rel ~1e-7)+DOT_BN = int(os.environ.get("HY4_BG_DOT_BN", "64"))+DOT_NW = int(os.environ.get("HY4_BG_DOT_NW", "4"))MAXT = 8 # rows served by the batched kernels (verify rows)@@ -58,6 +61,31 @@ def _k_bgt(q_ptr, d_ptr, x_ptr, o_ptr, N, K, NB, sxt, sxh, T, BT: tl.constexpr,tl.store(o_ptr + (tt[:, None] * (tl.num_programs(0) * N)) + h * N + rows[None, :], acc, mask=tm[:, None] & rm[None, :])+def _k_bgd(q_ptr, d_ptr, x_ptr, o_ptr, N, K, NB, sxt, sxh, T, BT: tl.constexpr, BN: tl.constexpr):+ """T rows on the matrix units. One fp16 dot per 32-wide Q8_0 block: int8 -> fp16 is exact, x (fp32) = hi + lo fp16 pieces, the fp16 block scale multiplies the fp32 partial+ sum, so the result matches sum_k (q * d)[n, k] * x[t, k] to ~1e-7. Each weight tile is read once for all T rows."""+ h = tl.program_id(0)+ rows = tl.program_id(1) * BN + tl.arange(0, BN)+ rm = rows < N+ tt = tl.arange(0, BT)+ tm = tt < T+ c32 = tl.arange(0, 32)+ acc = tl.zeros([BT, BN], dtype=tl.float32)+ qrow = (h * N + rows)[:, None] * K+ drow = (h * N + rows) * NB+ for kb in range(0, NB):+ cols = kb * 32 + c32+ q = tl.load(q_ptr + qrow + cols[None, :], mask=rm[:, None], other=0).to(tl.float16)+ d = tl.load(d_ptr + drow + kb, mask=rm, other=0.0).to(tl.float32)+ xv = tl.load(x_ptr + tt[:, None] * sxt + h * sxh + cols[None, :], mask=tm[:, None], other=0.0)+ xh = xv.to(tl.float16)+ xl = (xv - xh.to(tl.float32)).to(tl.float16)+ qt = tl.trans(q)+ acc += (tl.dot(xh, qt) + tl.dot(xl, qt)) * d[None, :]+ tl.store(o_ptr + (tt[:, None] * (tl.num_programs(0) * N)) + h * N + rows[None, :], acc, mask=tm[:, None] & rm[None, :])++class Q8Batched:"""[H, N, K] Q8_0 matrix as int8 + fp16 scales on a device"""@@ -72,6 +100,9 @@ class Q8Batched: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)+ if DOT and T <= 16 and self.K % 32 == 0:+ _k_bgd[(self.H, triton.cdiv(self.N, DOT_BN))](self.q, self.d, x, out, self.N, self.K, self.K // 32, x.stride(0), x.stride(1), T, BT=16, BN=DOT_BN, num_warps=DOT_NW)+ return outbn, bk = (32, 32) if (ROW_TILES and T >= 4) else (BN, min(BK, 64))_k_bgt[(self.H, triton.cdiv(self.N, bn))](self.q, self.d, x, out, self.N, self.K, self.K // 32, x.stride(0), x.stride(1), T,BT=triton.next_power_of_2(T), BN=bn, BK=bk, num_warps=4)diff --git a/tools/hy4/step/bg_dot_test.py b/tools/hy4/step/bg_dot_test.pynew file mode 100644index 0000000..cfe2022--- /dev/null+++ b/tools/hy4/step/bg_dot_test.py@@ -0,0 +1,34 @@+"""bg_dot_test.py: HY4_BG_DOT kernel (k_b: H 64, N 512, K 128; v_b: H 64, N 128, K 512) vs the shipped fp32 row-batched kernel and an fp64 reference. Error always, time on GPU (DEV=cuda)."""+import os, statistics, importlib.util+import numpy as np, torch+tree = os.getcwd()+sp = importlib.util.spec_from_file_location("mla_bgemv", os.path.join(tree, "exllamav3", "loader", "mla_bgemv.py")); bg = importlib.util.module_from_spec(sp); sp.loader.exec_module(bg)+dev = os.environ.get("DEV", "cuda"); CPU = dev == "cpu"+torch.manual_seed(0); rng = np.random.default_rng(0)+def bench(fn, n=30):+ 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 name, H, N, K in (("k_b", 8 if CPU else 64, 64 if CPU else 512, 128), ("v_b", 8 if CPU else 64, 32 if CPU else 128, 256 if CPU else 512)):+ raw = np.zeros((H * N, K // 32, 34), dtype=np.uint8)+ raw[:, :, 0:2] = (rng.standard_normal((H * N, K // 32)) * 0.02).astype(np.float16).view(np.uint8).reshape(H * N, K // 32, 2)+ raw[:, :, 2:] = rng.integers(-127, 128, (H * N, K // 32, 32), dtype=np.int16).astype(np.int8).view(np.uint8)+ m = bg.Q8Batched(raw, H, N, K, dev)+ w = (m.q.double() * m.d.double().repeat_interleave(32, dim=2))+ for T in (2, 3, 6):+ x = torch.randn(T, H, K, device=dev)+ ref = torch.einsum("hnk,thk->thn", w, x.double()).float()+ bg.DOT = False; a = m.mv(x)+ for bn, nw in (((16, 4),) if CPU else ((64, 4), (32, 4), (128, 4), (64, 8), (16, 2))):+ bg.DOT, bg.DOT_BN, bg.DOT_NW = True, bn, nw+ try: b = m.mv(x)+ except Exception as e: print(f"{name} T {T} BN {bn} NW {nw}: FAIL {type(e).__name__} {str(e)[:80]}", flush=True); continue+ ea = ((a - ref).norm() / ref.norm()).item(); eb = ((b - ref).norm() / ref.norm()).item()+ line = f"{name} T {T} BN {bn} NW {nw}: rel err old {ea:.1e} dot {eb:.1e}"+ if not CPU:+ bg.DOT = False; ta = bench(lambda: m.mv(x)); bg.DOT = True; tb = bench(lambda: m.mv(x)); line += f"; old {ta:.0f} us dot {tb:.0f} us"+ print(line, flush=True)+print("BG_DOT_DONE", flush=True)