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
Verify rows 5..8: one-launch dense GEMV (row chunks side by side) and hc mixer groups, bit-identical, behind EXL3_VERIFY_ROW_SPLIT=2
YanissAmz99b89d8dd7ee
diff --git a/exllamav3/exllamav3_ext/hc_mix.cu b/exllamav3/exllamav3_ext/hc_mix.cuindex f89bebd..323eecf 100644--- a/exllamav3/exllamav3_ext/hc_mix.cu+++ b/exllamav3/exllamav3_ext/hc_mix.cu@@ -2295,6 +2295,19 @@ static bool gr_q8_onepass()return v == 1;}+// Largest R that takes the group launch (groups of GRR_MAX_RT rows, one weight pass per group, each group bit-identical to a+// 1..4 row call): EXL3_GR_MIX_Q8_MAXR, default GRR_MAX_RT; 8 makes the 5..8 row verify cost one more group instead of the per-row launches.+static int gr_q8_maxrows()+{+ static int v = -1;+ if (v < 0)+ {+ const char* e = getenv("EXL3_GR_MIX_Q8_MAXR");+ v = e ? std::max(GRR_MAX_RT, std::min(8, atoi(e))) : GRR_MAX_RT;+ }+ return v;+}+void gr_mix_q8(const at::Tensor& streams, // (R, H, D) float@@ -2359,7 +2372,7 @@ void gr_mix_q8const at::cuda::OptionalCUDAGuard device_guard(device);cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream();- if (R <= GRR_MAX_RT && gr_q8_onepass()) // measured domain: decode / MTP verify rows; larger R keeps the old launch+ if (R <= gr_q8_maxrows() && gr_q8_onepass()) // measured domain: decode / MTP verify rows; larger R keeps the old launch{grr_launch(diff --git a/exllamav3/exllamav3_ext/quant/exl3_dec.cu b/exllamav3/exllamav3_ext/quant/exl3_dec.cuindex 623ce7c..b89ff8c 100644--- a/exllamav3/exllamav3_ext/quant/exl3_dec.cu+++ b/exllamav3/exllamav3_ext/quant/exl3_dec.cu@@ -2271,6 +2271,7 @@ struct JobsRint kbs;int R;int rpb; // rows per block (chunk size); grid.y = ceil(R / rpb)+ int swap; // 1: grid = (row chunks, blocks), so the chunks of one weight block run side by side and share its readsint x_row_pitch; // half-elements between consecutive rows of x (K for contiguous x)};@@ -2283,7 +2284,7 @@ constexpr int GEMV_R_ROW_BUDGET = MOE_R_MAX * MOE_R_KTW_MAX; // 128: max rpb *#endiftemplate <int KB2, int RM> constexpr int gemv_r_ring() { return EXL3_GEMV_R_RING > 0 ? EXL3_GEMV_R_RING : RM == 1 ? ring_of<KB2>() : 1; }-template <int KB2, int CB, int RM, bool D1 = false>+template <int KB2, int CB, int RM, int MODE = 0>__global__ __launch_bounds__(THREADS)void gemv_kernel_r(const half* __restrict__ x, JobsR jobs, float* scratch, int* counters){@@ -2298,16 +2299,18 @@ void gemv_kernel_r(const half* __restrict__ x, JobsR jobs, float* scratch, int*const int wave = tid >> 5;const int lane = tid & 31;+ const int bid = jobs.swap ? (int) blockIdx.y : (int) blockIdx.x;+ const int chunk = jobs.swap ? (int) blockIdx.x : (int) blockIdx.y;int ji = 0;#pragma unroll- for (int i = 1; i < 4; ++i) if (i < jobs.count && (int) blockIdx.x >= jobs.j[i].block_base) ji = i;+ for (int i = 1; i < 4; ++i) if (i < jobs.count && bid >= jobs.j[i].block_base) ji = i;const JobR& job = jobs.j[ji];- const int local = blockIdx.x - job.block_base;+ const int local = bid - job.block_base;const int strip = local / jobs.kbs;const int kb = local % jobs.kbs;const int NT = job.N / 16;- const int row0 = blockIdx.y * jobs.rpb;+ const int row0 = chunk * jobs.rpb;const int nrows = min(jobs.rpb, jobs.R - row0);int k0, ktw;@@ -2334,8 +2337,8 @@ void gemv_kernel_r(const half* __restrict__ x, JobsR jobs, float* scratch, int*const u32x4* tiles = job.trellis + ((size_t) kt0 * NT + nt) * VEC;const half* xs_rows[RM];#pragma unroll- for (int j = 0; j < RM; ++j) xs_rows[j] = xs + (D1 ? min(j, nrows - 1) : j) * (ktw * 128) + wave * ktw * 16;- if constexpr (D1 && RM > 1)+ for (int j = 0; j < RM; ++j) xs_rows[j] = xs + (MODE ? min(j, nrows - 1) : j) * (ktw * 128) + wave * ktw * 16;+ if constexpr (MODE == 1 && RM > 1)lane_gemv_r1<KB2, CB, RM, gemv_r_ring<KB2, RM>()>(tiles, (size_t) NT * VEC, xs_rows, ktw, acc);elselane_gemv_r<KB2, CB, RM, gemv_r_ring<KB2, RM>()>(tiles, (size_t) NT * VEC, xs_rows, nrows, ktw, acc);@@ -2445,6 +2448,7 @@ static void dec_gemv_r_impljobs.kbs = kbs;jobs.R = R;jobs.rpb = rpb;+ jobs.swap = env_int("EXL3_GEMV_R_CHUNK_FAST", 0) != 0 && R > 4 && R > rpb; // 5..8 rows only: the <= 4 row launches keep their gridjobs.x_row_pitch = Kdim;int blocks = 0, part = 0, ctr = 0;for (int i = 0; i < n; ++i)@@ -2475,12 +2479,14 @@ static void dec_gemv_r_implconst half* xp = reinterpret_cast<const half*>(x.data_ptr());float* sp = scratch.data_ptr<float>();int* cp = counters.data_ptr<int>();- const dim3 grid(blocks, (R + rpb - 1) / rpb);+ const int nch = (R + rpb - 1) / rpb;+ TORCH_CHECK(!jobs.swap || blocks <= 65535, "exl3_dec_gemv_r: too many blocks for the swapped grid");+ const dim3 grid = jobs.swap ? dim3(nch, blocks) : dim3(blocks, nch);EXL3_DEC_DISPATCH_CB(mcg ? 1 : 2, EXL3_DEC_DISPATCH_RM(rpb, EXL3_DEC_DISPATCH_KB2(kb2,{// EXL3_GEMV_R_DEC1=1 decodes each tile once for all rows (bit-identical)if (RM > 1 && env_int("EXL3_GEMV_R_DEC1", 0) == 1)- { auto kfn = gemv_kernel_r<KB2, CB, RM, true>; kfn<<<grid, THREADS, 0, stream>>>(xp, jobs, sp, cp); }+ { auto kfn = gemv_kernel_r<KB2, CB, RM, 1>; kfn<<<grid, THREADS, 0, stream>>>(xp, jobs, sp, cp); }else{ auto kfn = gemv_kernel_r<KB2, CB, RM>; kfn<<<grid, THREADS, 0, stream>>>(xp, jobs, sp, cp); }})));diff --git a/exllamav3/modules/row_split.py b/exllamav3/modules/row_split.pyindex a750136..96bf12b 100644--- a/exllamav3/modules/row_split.py+++ b/exllamav3/modules/row_split.py@@ -1,4 +1,5 @@-"""Row split of the speculative verify (EXL3_VERIFY_ROW_SPLIT=1, default off).+"""Row split of the speculative verify (EXL3_VERIFY_ROW_SPLIT, default off): 1 = split the dense GEMV and hc-mixer launches here and the MoE+in moe_fused.py; 2 = split only the MoE, the GEMV and hc mixer take 5..8 rows natively (see MODE below).Several verify kernels have a fast path for up to 4 rows (one-pass hc mixer: GRR_MAX_RT = 4) or are fast only up to4 rows (exl3_dec_gemv_r / _multi: the 8-row instantiation costs about 4x per row). With 5..8 rows (one sequence,@@ -11,7 +12,14 @@ import osfrom ..ext import exllamav3_ext as extCHUNK = 4-ON = os.environ.get("EXL3_VERIFY_ROW_SPLIT", "0") != "0"+# "1": the GEMV and hc-mixer launches are split here into <= 4-row launches; "2": only the MoE is split (moe_fused.py), the GEMV and hc mixer+# take 5..8 rows natively (EXL3_GEMV_R_RPB=4 EXL3_GEMV_R_CHUNK_FAST=1 EXL3_GR_MIX_Q8_MAXR=8, one launch, bit-identical)+MODE = os.environ.get("EXL3_VERIFY_ROW_SPLIT", "0")+ON = MODE == "1"+if MODE == "2":+ # read by the extension at launch (GEMV) or at the first hc-mixer call; the caller's own values win+ for _k, _v in (("EXL3_GEMV_R_RPB", "4"), ("EXL3_GEMV_R_CHUNK_FAST", "1"), ("EXL3_GR_MIX_Q8_MAXR", "8")):+ os.environ.setdefault(_k, _v)_installed = Falsediff --git a/tests/test_gemv_r_grid_swap_cpu.py b/tests/test_gemv_r_grid_swap_cpu.pynew file mode 100644index 0000000..5c918dc--- /dev/null+++ b/tests/test_gemv_r_grid_swap_cpu.py@@ -0,0 +1,54 @@+#!/usr/bin/env python3+"""CPU proof (T80): gemv_kernel_r with jobs.swap=1 visits exactly the same (job, strip, kb, row0, nrows) work items as swap=0,+each once, and every index it derives stays in range. Emulates the kernel's index code (bid/chunk -> ji/local/strip/kb/row0/nrows)+copied from exl3_dec.cu; mutants must fail."""+import random, itertools, sys+def kernel_items(jobs_block_base, count, kbs, R, rpb, swap, grid, mut=None):+ gx, gy = grid+ items = []+ for by in range(gy):+ for bx in range(gx):+ bid = by if swap else bx+ chunk = bx if swap else by+ if mut == "nochunk": chunk = 0+ ji = 0+ for i in range(1, 4):+ if i < count and bid >= jobs_block_base[i]: ji = i+ local = bid - jobs_block_base[ji]+ strip = local // kbs; kb = local % kbs+ row0 = chunk * rpb+ if mut == "rowoff": row0 += 1+ nrows = min(rpb, R - row0)+ items.append((ji, strip, kb, row0, nrows))+ return items+def check(mut=None, trials=3000):+ random.seed(7)+ for _ in range(trials):+ count = random.randint(1, 4); kbs = random.choice([1, 2, 3, 4, 6, 8])+ strips = [random.randint(1, 40) for _ in range(count)]+ base = []; acc = 0+ for s in strips: base.append(acc); acc += s * kbs+ blocks = acc; R = random.randint(5, 8); rpb = random.choice([2, 3, 4]); nch = (R + rpb - 1) // rpb+ a = kernel_items(base, count, kbs, R, rpb, 0, (blocks, nch), mut)+ swap = nch > 1+ b = kernel_items(base, count, kbs, R, rpb, 1, (nch, blocks), mut)+ if sorted(a) != sorted(b) or len(set(b)) != len(b): return False+ if blocks > 65535: return False+ for ji, strip, kb, row0, nrows in b:+ if not (0 <= ji < count and 0 <= strip < strips[ji] and 0 <= kb < kbs and 0 <= row0 < R and 1 <= nrows <= rpb and row0 + nrows <= R): return False+ # coverage: every (job,strip,kb,row) exactly once+ cov = {}+ for ji, strip, kb, row0, nrows in b:+ for r in range(row0, row0 + nrows): cov[(ji, strip, kb, r)] = cov.get((ji, strip, kb, r), 0) + 1+ if any(v != 1 for v in cov.values()) or len(cov) != blocks * R: return False+ return True+def test_grid_swap_mapping():+ assert check(None)+ assert not check("nochunk") and not check("rowoff")+++if __name__ == "__main__":+ ok = check(None)+ mut_ok = [check(m) for m in ("nochunk", "rowoff")]+ print("original mapping equal + covering:", ok, "| mutants rejected:", [not m for m in mut_ok])+ sys.exit(0 if ok and not any(mut_ok) else 1)diff --git a/tools/decode/gemv_r_rows_bench.py b/tools/decode/gemv_r_rows_bench.pynew file mode 100644index 0000000..54edeea--- /dev/null+++ b/tools/decode/gemv_r_rows_bench.py@@ -0,0 +1,67 @@+#!/usr/bin/env python3+"""T80 microbench: exl3_dec_gemv_r(_multi) R=1..8, synthetic trellis (random int16 = valid bits), kb2=10 (5 bpw).+check: row j of the R-row call == batch-1 call on row j (bitwise). time: us per launch."""+import os, sys, time, argparse+ap = argparse.ArgumentParser()+ap.add_argument("--rows", default="1,2,3,4,5,6,7,8"); ap.add_argument("--reps", type=int, default=60)+ap.add_argument("--shapes", default="qkv,z,o,sh"); ap.add_argument("--noverify", action="store_true"); ap.add_argument("--arms", default="D1"); ap.add_argument("--kb", type=float, default=5.0)+a = ap.parse_args()+sys.path.insert(0, os.environ["EXL3_ROOT"])+import torch+from exllamav3.ext import exllamav3_ext as ext+from exllamav3.modules.quant.exl3 import dec_workspace+dev = torch.device("cuda:0")+g = torch.Generator(device=dev).manual_seed(1)+KB = a.kb+SH = { # name: (K, [N...])+ "qkv": (2560, [10240]), "z": (2560, [6144]), "o": (6144, [2560]), "sh": (2560, [640, 640]), "qkvz": (2560, [10240, 6144]), "lm": (2560, [248320]),+}+def mk(K, Ns):+ kb2 = int(KB * 2)+ tr = [torch.randint(-32768, 32767, (K // 16, N // 16, kb2 * 8), dtype=torch.int16, device=dev, generator=g) for N in Ns]+ suh = [(torch.rand(K, device=dev, generator=g) * 2 - 1).half() for _ in Ns]+ svh = [(torch.rand(N, device=dev, generator=g) * 2 - 1).half() for N in Ns]+ return tr, suh, svh+scratch1, counters1 = dec_workspace(dev)+ARMS = {+ "D1": {"EXL3_GEMV_R_DEC1": "1"},+ "D1c4": {"EXL3_GEMV_R_DEC1": "1", "EXL3_GEMV_R_RPB": "4"},+ "D1c4f": {"EXL3_GEMV_R_DEC1": "1", "EXL3_GEMV_R_RPB": "4", "EXL3_GEMV_R_CHUNK_FAST": "1"},+ "D0": {},+}+KEYS = ["EXL3_GEMV_R_DEC1", "EXL3_GEMV_R_RPB", "EXL3_GEMV_R_CHUNK_FAST", "EXL3_GEMV_R_RPB78"]+def setarm(name):+ for k in KEYS: os.environ.pop(k, None)+ os.environ.update(ARMS[name])+for name in a.shapes.split(","):+ K, Ns = SH[name]+ tr, suh, svh = mk(K, Ns)+ Ks = [KB] * len(Ns)+ for R in [int(v) for v in a.rows.split(",")]:+ x = (torch.randn(R, K, device=dev, generator=g) * 0.5).half().contiguous()+ outs = [torch.empty(R, N, dtype=torch.half, device=dev) for N in Ns]+ scr = torch.zeros(R * 8 * sum(Ns) * 2, dtype=torch.float, device=dev); ctr = torch.zeros(8192, dtype=torch.int32, device=dev)+ def call():+ if len(Ns) == 1: ext.exl3_dec_gemv_r(x, tr[0], suh[0], svh[0], outs[0], scr, ctr, KB, False)+ else: ext.exl3_dec_gemv_r_multi(x, tr, suh, svh, outs, scr, ctr, Ks, False)+ arms = a.arms.split(',')+ for arm in arms:+ setarm(arm)+ call(); torch.cuda.synchronize()+ bad = 0+ if not a.noverify:+ for j in range(R):+ o1 = [torch.empty(1, N, dtype=torch.half, device=dev) for N in Ns]+ if len(Ns) == 1: ext.exl3_dec_gemv(x[j:j+1].contiguous(), tr[0], suh[0], svh[0], o1[0], scratch1, counters1, KB, False)+ else: ext.exl3_dec_gemv_multi(x[j:j+1].contiguous(), tr, suh, svh, o1, scratch1, counters1, Ks, False)+ for i in range(len(Ns)):+ bad += int((o1[i][0].view(torch.int16) != outs[i][j].view(torch.int16)).sum().item())+ for _ in range(5): call()+ torch.cuda.synchronize()+ ts = []+ for _ in range(3):+ e0 = torch.cuda.Event(enable_timing=True); e1 = torch.cuda.Event(enable_timing=True)+ e0.record()+ for _ in range(a.reps): call()+ e1.record(); torch.cuda.synchronize(); ts.append(e0.elapsed_time(e1) * 1000 / a.reps)+ print(f"{name:5s} {arm:6s} R={R} us/launch min {min(ts):7.1f} all {[round(t,1) for t in ts]} mismatch_elems_vs_batch1={bad}", flush=True)diff --git a/tools/decode/gr_mix_rows_check.py b/tools/decode/gr_mix_rows_check.pynew file mode 100644index 0000000..826a432--- /dev/null+++ b/tools/decode/gr_mix_rows_check.py@@ -0,0 +1,34 @@+#!/usr/bin/env python3+"""T80: gr_mix_q8 with R=1..8 rows (EXL3_GR_MIX_Q8_MAXR=8) must equal R single-row calls bitwise (dots, post, mixed). gs 0 and 1."""+import os, sys, time+sys.path.insert(0, os.environ["EXL3_ROOT"])+import torch+from exllamav3.ext import exllamav3_ext as ext+dev = torch.device("cuda:0"); g = torch.Generator(device=dev).manual_seed(3)+H, D, LR = 4, 2560, 320+def run(gs, R, reps=0):+ M = LR + H+ s3 = (torch.randn(R, H, D, device=dev, generator=g)).float().contiguous()+ fq = torch.randint(-127, 128, (M, H * D), dtype=torch.int8, device=dev, generator=g)+ uq = torch.randint(-127, 128, (H, D // 4, LR, 4), dtype=torch.int8, device=dev, generator=g)+ if gs:+ fsc = (torch.rand(M * H * D // 128, device=dev, generator=g) * 0.01 + 1e-3).float()+ usc = (torch.rand(H * D * ((LR + 63) // 64), device=dev, generator=g) * 0.01 + 1e-3).float()+ else:+ fsc = (torch.rand(M, device=dev, generator=g) * 0.01 + 1e-3).float()+ usc = (torch.rand(H * D, device=dev, generator=g) * 0.01 + 1e-3).float()+ w = (torch.rand(H * D, device=dev, generator=g) + 0.5).half()+ def call(s, n):+ dots = torch.full((n, M + 1, H), 7.0, device=dev); post = torch.full((n, H), 7.0, device=dev); mixed = torch.zeros(n, D, dtype=torch.half, device=dev)+ ext.gr_mix_q8(s.contiguous(), fq, fsc, uq, usc, w, 1e-6, dots, post, mixed)+ torch.cuda.synchronize()+ return dots, post, mixed+ d, p, m = call(s3, R)+ bad = 0+ for r in range(R):+ d1, p1, m1 = call(s3[r:r + 1], 1)+ bad += int((d1[0].view(torch.int32) != d[r].view(torch.int32)).sum()) + int((p1[0].view(torch.int32) != p[r].view(torch.int32)).sum()) + int((m1[0].view(torch.int16) != m[r].view(torch.int16)).sum())+ return bad+for gs in (0, 1):+ for R in range(1, 9):+ print(f"gs={gs} R={R} mismatching words vs {R} single-row calls: {run(gs, R)}", flush=True)