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.

Add opt-in dense K8 decode for Qwen projections (#105)

razeth374768f1bb4a
diff --git a/exllamav3/exllamav3_ext/quant/exl3_dec.cu b/exllamav3/exllamav3_ext/quant/exl3_dec.cu
index d82a99c..27f8931 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_dec.cu
+++ b/exllamav3/exllamav3_ext/quant/exl3_dec.cu
@@ -2056,6 +2056,19 @@ inline int kb2_of(double K)
return kb2;
}
+// Keep the routed-MoE formats unchanged. K8 is an opt-in dense mul1 experiment.
+inline int dense_kb2_of(double K, bool mcg)
+{
+ if (K == 8.0)
+ {
+ const char* enabled = getenv("EXL3_DENSE_K8");
+ TORCH_CHECK(enabled && enabled[0] == '1' && enabled[1] == '\0' && !mcg,
+ "exl3_dec: dense K8 requires mul1 and EXL3_DENSE_K8=1");
+ return 16;
+ }
+ return kb2_of(K);
+}
+
#define EXL3_DEC_DISPATCH_KB2(kb2, ...) \
switch (kb2) \
{ \
@@ -2094,6 +2107,12 @@ inline void launch_gemv_cb(int kb2, int blocks, const half* xp, const Jobs& jobs
case 10: gemv_kernel<10, CB><<<blocks, THREADS, 0, stream>>>(xp, jobs, sp, cp); break;
case 12: gemv_kernel<12, CB><<<blocks, THREADS, 0, stream>>>(xp, jobs, sp, cp); break;
case 14: gemv_kernel<14, CB><<<blocks, THREADS, 0, stream>>>(xp, jobs, sp, cp); break;
+ case 16:
+ if constexpr (CB == 2)
+ gemv_kernel<16, 2><<<blocks, THREADS, 0, stream>>>(xp, jobs, sp, cp);
+ else
+ TORCH_CHECK(false, "exl3_dec_gemv: K8 requires mul1");
+ break;
default: TORCH_CHECK(false, "exl3_dec_gemv: unsupported K*2 ", kb2);
}
}
@@ -2258,7 +2277,7 @@ static void dec_gemv_impl
: x.numel() == x.size(-1), "exl3_dec_gemv: x must be fp16 [1, K] (or cover the strided groups)");
}
TORCH_CHECK(Kdim % 512 == 0, "exl3_dec_gemv: K must be a multiple of 512");
- const int kb2 = kb2_of(K[0]);
+ const int kb2 = dense_kb2_of(K[0], mcg);
int strips_total = 0;
for (int i = 0; i < n; ++i) strips_total += (out[i].size(-1) + STRIP - 1) / STRIP;
const int min_blocks = env_int("EXL3_DEC_MIN_BLOCKS", 32);
@@ -2276,7 +2295,7 @@ static void dec_gemv_impl
int blocks = 0, part = 0, ctr = CTR_GEMV;
for (int i = 0; i < n; ++i)
{
- TORCH_CHECK(kb2_of(K[i]) == kb2, "exl3_dec_gemv: all matrices must share K");
+ TORCH_CHECK(dense_kb2_of(K[i], mcg) == kb2, "exl3_dec_gemv: all matrices must share K");
const int N = out[i].size(-1);
TORCH_CHECK(N % 128 == 0 && out[i].numel() == N && out[i].is_contiguous(), "exl3_dec_gemv: out must be [1, N], N % 128 == 0");
TORCH_CHECK(trellis[i].size(0) == Kdim / 16 && trellis[i].size(1) == N / 16 && trellis[i].size(2) == kb2 * 8,
@@ -2592,7 +2611,7 @@ static void dec_gemv_r_impl
const int Kdim = (int) x.size(1);
TORCH_CHECK(R >= 1 && R <= GEMV_R_MAX_ROWS, "exl3_dec_gemv_r: R must be 1..GEMV_R_MAX_ROWS");
TORCH_CHECK(Kdim % 512 == 0, "exl3_dec_gemv_r: K must be a multiple of 512");
- const int kb2 = kb2_of(K[0]);
+ const int kb2 = dense_kb2_of(K[0], mcg);
int strips_total = 0;
for (int i = 0; i < n; ++i) strips_total += ((int) out[i].size(-1) + STRIP - 1) / STRIP;
// Identical to dec_gemv_impl's own ktw/kbs choice (same pick_ktw/kbs_of call, same args) --
@@ -2642,7 +2661,7 @@ static void dec_gemv_r_impl
int blocks = 0, part = 0, ctr = 0;
for (int i = 0; i < n; ++i)
{
- TORCH_CHECK(kb2_of(K[i]) == kb2, "exl3_dec_gemv_r: all matrices must share K");
+ TORCH_CHECK(dense_kb2_of(K[i], mcg) == kb2, "exl3_dec_gemv_r: all matrices must share K");
const int N = (int) out[i].size(-1);
TORCH_CHECK(N % 128 == 0 && out[i].size(0) == R && out[i].is_contiguous(),
"exl3_dec_gemv_r: out must be [R, N], N % 128 == 0");
@@ -2682,6 +2701,18 @@ static void dec_gemv_r_impl
cuda_check(cudaPeekAtLastError());
return;
}
+ if (kb2 == 16)
+ {
+ EXL3_DEC_DISPATCH_RM(rpb,
+ {
+ if (RM > 1 && env_int("EXL3_GEMV_R_DEC1", 0) == 1)
+ { auto kfn = gemv_kernel_r<16, 2, RM, 1>; kfn<<<grid, THREADS, 0, stream>>>(xp, jobs, sp, cp); }
+ else
+ { auto kfn = gemv_kernel_r<16, 2, RM>; kfn<<<grid, THREADS, 0, stream>>>(xp, jobs, sp, cp); }
+ });
+ cuda_check(cudaPeekAtLastError());
+ return;
+ }
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)
diff --git a/exllamav3/modules/quant/exl3.py b/exllamav3/modules/quant/exl3.py
index 22409b9..eb48a93 100644
--- a/exllamav3/modules/quant/exl3.py
+++ b/exllamav3/modules/quant/exl3.py
@@ -237,6 +237,14 @@ EXL3_DEC = os.environ.get("EXL3_DEC", "1") != "0"
_DEC_KB2 = (4, 5, 6, 8, 10, 12)
# dense projections also decode K7 (attention, linear-attention and shared-expert projections of 5 bpw packs); the routed-MoE kernels stop at K6
_DEC_KB2_DENSE = _DEC_KB2 + (14,)
+# EXL3_DENSE_K8=1 enables K8 for these Qwen attention shapes only. The list is not a kernel limit (the C++ side accepts any
+# K8 mul1 matrix once the setting is on). It is every K8 non-expert matrix of the K6-routed / K8-shared Qwen3.8 Flash-Next
+# pack that was measured: k_proj / v_proj (2560, 512), linear-attention in_proj_z (2560, 6144), in_proj_qkv (2560, 10240),
+# q_proj (2560, 12288), o_proj / out_proj (6144, 2560). The shared-expert projections (2560, 640) / (640, 2560) are left out on
+# purpose: this change keeps shared-expert and routed-MoE eligibility as it was. Add a shape only together with a real-weight
+# run of tools/qwen/check_dense_k8.py.
+_DENSE_K8_SHAPES = {(2560, 512), (2560, 6144), (2560, 10240),
+ (2560, 12288), (6144, 2560)}
# ROCm carries 9..32 rows per exl3_dec_gemv_r call: R * kbs * N partial sums of a wide dense projection (GDN qkvz at 28+ rows) outgrow 2M floats
DEC_SCRATCH_FLOATS = (8 << 20) if torch.version.hip else (2 << 20)
# arrival counters: the 8-row kernels fit 4096; a 32-row GEMV of a wide N (lm_head: 32 * ceil(N / 512)) needs up to ~16k
@@ -289,7 +297,11 @@ def dec_supported(inner) -> bool:
"""True when a LinearEXL3 can run the exl3_dec kernels (mul1 codebook, supported K, shapes)."""
return (
EXL3_DEC and bool(torch.version.hip) and hasattr(ext, "exl3_dec_gemv") and
- inner.mul1 and not inner.mcg and int(round(inner.K * 2)) in _DEC_KB2_DENSE and
+ inner.mul1 and not inner.mcg and (
+ int(round(inner.K * 2)) in _DEC_KB2_DENSE or
+ (inner.K == 8 and os.environ.get("EXL3_DENSE_K8") == "1" and
+ (inner.in_features, inner.out_features) in _DENSE_K8_SHAPES)
+ ) and
inner.K * 2 == int(round(inner.K * 2)) and
inner.in_features % 512 == 0 and inner.out_features % 128 == 0 and
tuple(inner.trellis.shape[:2]) == (inner.in_features // 16, inner.out_features // 16) and
diff --git a/tests/test_dense_k8_cpu.py b/tests/test_dense_k8_cpu.py
new file mode 100644
index 0000000..fc140d6
--- /dev/null
+++ b/tests/test_dense_k8_cpu.py
@@ -0,0 +1,111 @@
+"""Host-only checks. HIP correctness and speed still require the actual GPU."""
+import ast
+import os
+from pathlib import Path
+import re
+import subprocess
+from types import SimpleNamespace as NS
+import tempfile
+import unittest
+from unittest.mock import patch
+
+ROOT = Path(__file__).resolve().parents[1]
+CU = ROOT / 'exllamav3/exllamav3_ext/quant/exl3_dec.cu'
+
+
+def test_actual_tile_format_and_windows(tmp_path):
+ source = CU.read_text()
+ fmt = re.search(r'template <int KB2>\nstruct Fmt\n\{.*?\n\};', source, re.S).group()
+ window = re.search(r'template <int KB2, int P, bool MASK>\n.*?\n\}', source, re.S).group()
+ preamble = '''#include <cstdint>
+#include <cstdio>
+#include <cstdlib>
+#include <utility>
+#define __device__
+#define __forceinline__ inline
+static uint32_t __builtin_amdgcn_ubfe(uint32_t x,int o,int w) {return (x>>o)&((1u<<w)-1);}
+static uint32_t __builtin_amdgcn_alignbit(uint32_t h,uint32_t l,int s) {return uint32_t(((uint64_t(h)<<32)|l)>>s);}
+#ifndef PORT_UBFE16 // newer exl3_dec.cu goes through the port macros
+#define PORT_UBFE16(w, s) __builtin_amdgcn_ubfe(w, s, 16)
+#define PORT_ALIGNBIT(hi, lo, s) __builtin_amdgcn_alignbit(hi, lo, s)
+#endif
+'''
+ body = r'''
+template<int B, size_t... P> bool check(const uint32_t* w,std::index_sequence<P...>) {
+ const uint32_t got[] = {window<B,int(P),true>(w)...};
+ const uint32_t raw[] = {window<B,int(P),false>(w)...};
+ for(int p=0;p<256;p++) {
+ int end=(p+257)*(B/2), start=end-16;
+ uint32_t a=w[(start/32)%Fmt<B>::WORDS], b=w[((end-1)/32)%Fmt<B>::WORDS];
+ uint32_t want=uint32_t(((uint64_t(a)<<32)|b)>>(((end-1)/32+1)*32-end))&65535;
+ if(got[p]!=want || (raw[p]&65535)!=want) return false;
+ }
+ return true;
+}
+template<int B> bool run() {
+ uint32_t w[Fmt<B>::WORDS]; srand(11+B);
+ for(int t=0;t<1000;t++) {
+ for(auto &v:w) v=(uint32_t(rand())<<16)^uint32_t(rand());
+ if(!check<B>(w,std::make_index_sequence<256>{})) return false;
+ }
+ return true;
+}
+int main() {return !(run<10>() && run<12>() && run<14>() && run<16>());}
+'''
+ cpp = tmp_path / 'check.cpp'
+ cpp.write_text(preamble + fmt + window + body)
+ exe = tmp_path / 'check'
+ subprocess.run(['g++','-std=c++17','-O1','-fsanitize=address,undefined',
+ '-fno-sanitize-recover=all',str(cpp),'-o',str(exe)],check=True)
+ subprocess.run([str(exe)],check=True,env={**os.environ,'ASAN_OPTIONS':'detect_leaks=0'})
+
+
+def helpers():
+ tree = ast.parse((ROOT / 'exllamav3/modules/quant/exl3.py').read_text())
+ nodes = [n for n in tree.body if
+ isinstance(n, ast.FunctionDef) and n.name in ('dec_supported','dec_moe_supported') or
+ isinstance(n, ast.Assign) and any(isinstance(t,ast.Name) and t.id in
+ ('_DEC_KB2','_DEC_KB2_DENSE','_DENSE_K8_SHAPES') for t in n.targets)]
+ ns = {'os':os,'torch':NS(version=NS(hip=True)), 'EXL3_DEC':True,
+ 'ext':NS(exl3_dec_gemv=True,exl3_dec_moe=True)}
+ exec(compile(ast.Module(body=nodes,type_ignores=[]),'eligibility','exec'),ns)
+ return ns
+
+
+def inner(k=8, shape=(2560,10240)):
+ i,o=shape
+ return NS(K=k,mul1=True,mcg=False,in_features=i,out_features=o,
+ trellis=NS(shape=(i//16,o//16,128)),suh=1,svh=1)
+
+
+class DenseK8Checks(unittest.TestCase):
+ def test_tile_windows(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ test_actual_tile_format_and_windows(Path(tmp))
+
+ def test_flag_shapes_and_moe_isolation(self):
+ for flag in [None, '0', '1', 'true', '01']:
+ with self.subTest(flag=flag), patch.dict(os.environ):
+ os.environ.pop('EXL3_DENSE_K8', None)
+ if flag is not None:
+ os.environ['EXL3_DENSE_K8'] = flag
+ ns = helpers()
+ for shape in ns['_DENSE_K8_SHAPES']:
+ self.assertEqual(ns['dec_supported'](inner(shape=shape)), flag == '1')
+ self.assertFalse(ns['dec_moe_supported'](inner(shape=shape)))
+ for shape in [(640,2560),(2560,640),(512,512)]:
+ self.assertFalse(ns['dec_supported'](inner(shape=shape)))
+ for k in [2,2.5,3,4,5,6,7]:
+ self.assertTrue(ns['dec_supported'](inner(k=k)))
+ for k in [7.5,8.5,9]:
+ self.assertFalse(ns['dec_supported'](inner(k=k)))
+
+ def test_rejects_unsupported_weights(self):
+ with patch.dict(os.environ, {'EXL3_DENSE_K8':'1'}):
+ for attribute,value in [('mul1',False),('mcg',True),('suh',None),('svh',None)]:
+ x = inner()
+ setattr(x,attribute,value)
+ self.assertFalse(helpers()['dec_supported'](x))
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tools/qwen/DENSE_K8.md b/tools/qwen/DENSE_K8.md
new file mode 100644
index 0000000..17b7ace
--- /dev/null
+++ b/tools/qwen/DENSE_K8.md
@@ -0,0 +1,113 @@
+# Experimental dense K8 decode
+
+Set EXL3_DENSE_K8=1 before model load to enable direct decode for five
+Qwen attention projection shapes. Rebuild the extension before use.
+The setting is disabled by default. The weight files do not change.
+
+Supported input/output sizes are 2560/512, 2560/6144, 2560/10240,
+2560/12288, and 6144/2560. Weights must use K8 and the mul1 codebook.
+Routed MoE eligibility does not change.
+
+The list is a Python-side choice, not a kernel limit: the C++ side accepts
+any K8 mul1 matrix once the variable is set. It holds every K8 matrix of the
+tested K6-routed / K8-shared pack that is not an expert: k_proj and v_proj
+(2560/512), in_proj_z (2560/6144), in_proj_qkv (2560/10240), q_proj
+(2560/12288), and o_proj / out_proj (6144/2560). The shared-expert
+projections (2560/640 and 640/2560) are left out on purpose. Add a shape
+only together with a real-weight run of `check_dense_k8.py`.
+
+The variable must not change after the model is loaded. Python reads it once
+per projection at load time to decide whether the direct path is eligible.
+The C++ launch reads it again on every launch and refuses K8 when it is
+not `1`. Setting it after the model is loaded has no effect (the projections
+were already marked not eligible). Unsetting it or changing it after a load
+that used it makes the next K8 launch raise an error.
+
+## Checks
+
+```sh
+python -m pytest --noconftest -q tests/test_dense_k8_cpu.py
+python tools/qwen/check_dense_k8.py --model "$MODEL_DIR" --output dense-k8-results
+```
+
+The second command requires an idle ROCm GPU and the built extension.
+The output directory must not exist. The check loads selected projections,
+checks buffer bounds and dispatch, reports numerical error, and measures
+kernel time. It does not stop services or change model files.
+A successful exit does not mean that outputs are bit-identical.
+Review results.json before use.
+
+## Measured on gfx1151 (this revision)
+
+Real-weight check on the 6.05 bpw K6 routed / K8 shared pack, ten projections
+(k_proj, v_proj, q_proj, o_proj, in_proj_z, in_proj_qkv and out_proj, from
+linear-attention layers, full-attention layers and the MTP layer), rows 1 to 8, two seeds, fp16 and
+fp32 output: 320 comparisons, none bit-identical, largest relative L2 error
+5.57e-4 (the figure of the earlier prototype run). Kernel time against
+reconstruct plus half-precision GEMM: 2.4 to 2.7 times faster for 2560/512, 3.6 to 6.2 times
+for the larger shapes.
+
+Is that error normal for the dense kernels? The same check on the direct paths
+that already exist gives the same size: K4 projections (six, linear attention
+layers of a 4.0 bpw pack) 5.3e-4 to 5.6e-4, K6 projections (five, the MTP layer
+of that pack) 5.2e-4 to 6.3e-4. Against an fp64 evaluation of the dequantized
+weights, the direct kernel is the closer one for K4 and K8 alike:
+
+| Output | Direct kernel vs fp64 | Reconstruct + GEMM vs fp64 |
+| --- | ---: | ---: |
+| fp16 | 2.9e-4 to 3.0e-4 | 4.6e-4 to 4.7e-4 |
+| fp32 | 2.0e-4 to 2.1e-4 | 2.8e-4 to 3.0e-4 |
+
+(relative L2, rows 1 to 8, K8 in_proj_qkv and q_proj; the K4 projections
+give the same values to two digits). The 5e-4 difference is therefore mostly
+the rounding of the reference path, not an error of the new kernel.
+
+Full model, 6.05 bpw pack, only `EXL3_DENSE_K8=1` changed, decode medians of
+nine runs: 14.6 to 27.8 tokens/s at 4K context (1.90x) and 15.1 to 28.0 at 32K
+(1.86x). Prefill is not routed through this path and stayed within noise
+(0.95 to 1.05x). Greedy text diverged from the default on 17 of 32 prompts;
+see K6K8.md for how large such rounding-level changes are in this model
+(largest top-10 probability change 9.6 points on 5358 positions, RMS change of
+the chosen-token log-probability 0.013, mean change -0.0004).
+
+Registers and spills (hipcc `-Rpass-analysis=kernel-resource-usage`), K8 kernels
+with the K4 to K7 kernels that existed before for comparison. The last two
+numbers of `gemv_kernel_r` are the row count and a variant flag:
+
+| Kernel | VGPRs | Spilled VGPRs | Scratch (bytes/lane) |
+| --- | ---: | ---: | ---: |
+| `gemv_kernel<16, 2>` (K8, 1 row) | 256 | 100 | 212 |
+| `gemv_kernel<14, 2>` (K7, before) | 256 | 29 | 88 |
+| `gemv_kernel<8, 2>` (K4, before) | 105 | 0 | 0 |
+| `gemv_kernel_r<16, 2, 1, x>` (K8) | 256 | 73 | 152 |
+| `gemv_kernel_r<16, 2, 2, 1/0>` | 197 / 252 | 0 | 0 |
+| `gemv_kernel_r<16, 2, 4, 1/0>` | 245 / 256 | 0 / 104 | 0 / 228 |
+| `gemv_kernel_r<16, 2, 8, 1/0>` | 256 | 184 / 270 | 480 / 700 |
+| for comparison `gemv_kernel_r<8, 2, 8, 1/0>` (K4, before) | 256 | 299 / 269 | 768 / 496 |
+| for comparison `gemv_kernel_r<6, 2, 8, 1/0>` (K3, before) | 256 | 288 / 280 | 624 / 460 |
+
+K8 spills like the existing eight-row kernels and less than most of them; the
+single-row kernel spills more than the K7 one, and the timings above include that.
+No kernel that existed before changed its register or spill count.
+
+Build: the extension grows from 134.66 MB to 134.92 MB (+0.27 MB, +0.2%); a full build took 493 s
+against 490 s for the base (three parallel jobs, machine not idle). Compiling `exl3_dec` alone takes
+249 s instead of 242 s and its object grows from 14.49 MB to 14.77 MB (+2%).
+
+## Earlier hardware results
+
+The prototype ran on an EVO-X2 with 128 GB RAM and gfx1151, with a local
+Qwen3.8 Flash-Next EXL3 pack labelled 6.05 bpw. These measurements preceded
+the PR rebase and are not validation of this revision.
+
+| Prompt | Before (tokens/s) | After (tokens/s) |
+| --- | ---: | ---: |
+| Code | 24.54 | 40.92 |
+| Explanation | 19.09 | 36.50 |
+| Story | 17.30 | 32.10 |
+
+The 320 real-weight comparisons had a maximum relative L2 error of
+0.0005568. Outputs were not bit-identical. Repeat GPU validation and
+full-model benchmarks before merge. Use tools/bench.sh with the same
+machine and command for each comparison. Do not combine these numbers
+with the fused-MoE results: the test configurations differed.
diff --git a/tools/qwen/check_dense_k8.py b/tools/qwen/check_dense_k8.py
new file mode 100644
index 0000000..8375644
--- /dev/null
+++ b/tools/qwen/check_dense_k8.py
@@ -0,0 +1,172 @@
+"""Check numerical error, buffer bounds, dispatch, and speed on a ROCm GPU."""
+
+from pathlib import Path
+import gc, importlib.util, json, os, statistics, sys
+import argparse
+parser = argparse.ArgumentParser(description="Check dense K8 projections with real weights.")
+parser.add_argument("--model", required=True)
+parser.add_argument("--output", required=True)
+parser.add_argument("--bits", type=int, default=8,
+ help="K of the projections to check. 8 checks the five K8 shapes. Another value is a baseline run of the "
+ "existing direct path on dense projections of that K, picked with --match.")
+parser.add_argument("--match", default="",
+ help="with --bits other than 8: substring of the module keys to check, for example indexer.index_qk_proj")
+args = parser.parse_args()
+root = Path(__file__).resolve().parents[2]
+out = Path(args.output)
+out.mkdir(parents=True, exist_ok=False)
+sys.path.insert(0, str(root))
+spec = importlib.util.find_spec("exllamav3_ext")
+assert spec and Path(spec.origin).resolve().parent == root, "Wrong extension"
+print("Extension:", spec.origin, flush=True)
+os.environ["EXL3_DENSE_K8"] = "1"
+from tools.qwen.serve import SERVE_ENV
+for key, value in SERVE_ENV:
+ os.environ.setdefault(key, value)
+import torch
+from exllamav3 import Config, Model
+from exllamav3.modules.linear import Linear
+from exllamav3.modules.quant import exl3 as q
+from exllamav3.ext import exllamav3_ext as ext
+torch.set_grad_enabled(False)
+torch.set_num_threads(4)
+assert torch.version.hip
+assert os.environ.get("EXL3_VERIFY_GEMV_R") == "1"
+assert os.environ.get("EXL3_VERIFY_ROW_SPLIT") == "2"
+dev = torch.device("cuda:0")
+print("GPU:", torch.cuda.get_device_name(dev), flush=True)
+cfg = Config.from_directory(args.model)
+models = [Model.from_config(cfg), Model.from_config(cfg, component="mtp")]
+if args.bits == 8:
+ groups = {shape: [] for shape in q._DENSE_K8_SHAPES}
+else:
+ assert args.match, "--bits other than 8 needs --match"
+ groups = {}
+for model in models:
+ for module in model:
+ if isinstance(module, Linear) and (".self_attn." in module.key or ".linear_attn." in module.key):
+ shape = (module.in_features, module.out_features)
+ if args.bits == 8:
+ if shape in groups:
+ groups[shape].append(module)
+ elif args.match in module.key:
+ groups.setdefault(shape, []).append(module)
+assert groups and all(groups.values()), "Not all projection shapes were found"
+selected = []
+for shape in sorted(groups):
+ members = groups[shape]
+ selected.extend([members[i] for i in sorted({0, len(members)-1})])
+
+# Guard the direct kernel's scratch and counter buffers.
+scratch = torch.full((q.DEC_SCRATCH_FLOATS+256,), 12345., device=dev)
+counters = torch.full((4096+256,), 12345, dtype=torch.int32, device=dev)
+scratch[128:-128].zero_(); counters[128:-128].zero_()
+q._dec_workspaces[str(dev)] = (scratch[128:-128], counters[128:-128])
+def guards():
+ assert bool((scratch[:128] == 12345).all()) and bool((scratch[-128:] == 12345).all()), "Scratch overrun"
+ assert bool((counters[:128] == 12345).all()) and bool((counters[-128:] == 12345).all()), "Counter overrun"
+ assert int(counters[128:-128].abs().sum()) == 0, "Counters not reset"
+
+records = []
+flush = torch.zeros(64 << 20, device=dev)
+for module in selected:
+ print("Loading:", module.key, flush=True)
+ module.load(dev)
+ try:
+ inner = module.inner
+ if getattr(inner, "K", None) != args.bits: # only reachable for --bits other than 8 (fp16 or other-K projections)
+ assert args.bits != 8, f"{module.key} is not K8"
+ print("Skipping (not K%d):" % args.bits, module.key, flush=True)
+ continue
+ assert inner.mul1 and not inner.mcg
+ assert inner.dec_ok and inner.bc is None
+ if args.bits == 8:
+ os.environ["EXL3_DENSE_K8"] = "0"
+ assert not q.dec_supported(inner), "Opt-out guard failed"
+ os.environ["EXL3_DENSE_K8"] = "1"
+ calls = [0, 0]
+ originals = [ext.exl3_dec_gemv, ext.exl3_dec_gemv_r]
+ def spy(index):
+ def invoke(*a, **kw):
+ calls[index] += 1
+ return originals[index](*a, **kw)
+ return invoke
+ ext.exl3_dec_gemv, ext.exl3_dec_gemv_r = spy(0), spy(1)
+ quality = []
+ try:
+ for seed in (1234, 5678):
+ gen = torch.Generator(device=dev).manual_seed(seed)
+ base = torch.randn((9, inner.in_features), generator=gen, device=dev)
+ if seed == 1234:
+ base = base.half()
+ else:
+ base *= 8
+ base[1:8:2] = base[0:8:2].clone()
+ base = base.half() # Both paths require FP16 input; output dtype varies.
+ for rows in range(1, 9):
+ x = base[:rows].contiguous()
+ saved = x.clone()
+ for dtype in (torch.float16, torch.float32):
+ before = sum(calls)
+ ref = inner.forward(x, {"reconstruct": True}, dtype).clone()
+ assert sum(calls) == before, "Reference used candidate kernel"
+ before = calls.copy()
+ got = inner.forward(x, {"dflash_verify": True}, dtype).clone()
+ assert calls[rows > 1] > before[rows > 1], "Candidate dispatch missing"
+ repeat = inner.forward(x, {"dflash_verify": True}, dtype).clone()
+ torch.cuda.synchronize()
+ assert bool(torch.isfinite(ref).all()) and bool(torch.isfinite(got).all())
+ assert torch.equal(got, repeat), "Candidate not repeatable"
+ assert torch.equal(x, saved), "Input modified"
+ guards()
+ error = got.double() - ref.double()
+ quality.append({"rows": rows, "seed": seed, "dtype": str(dtype),
+ "exact": torch.equal(got, ref),
+ "max_abs": error.abs().max().item(),
+ "rel_l2": (error.norm()/ref.double().norm().clamp_min(1e-30)).item()})
+ # Larger batches must still use the existing path. For K8 that path is reconstruct + hgemm, so it matches the
+ # reference bit for bit. For other K the existing path can be the HIP GEMV, so only the dispatch is checked.
+ before = sum(calls)
+ ref9 = inner.forward(base, {"reconstruct": True}).clone()
+ got9 = inner.forward(base, {"dflash_verify": True}).clone()
+ torch.cuda.synchronize()
+ assert sum(calls) == before, "Nine-row fallback used the direct kernel"
+ assert args.bits != 8 or torch.equal(ref9, got9), "Nine-row fallback changed"
+ guards()
+ finally:
+ ext.exl3_dec_gemv, ext.exl3_dec_gemv_r = originals
+ worst = max(quality, key=lambda r: r["rel_l2"])
+ print("CHECK:", json.dumps({"key": module.key, "comparisons": len(quality),
+ "exact": sum(r["exact"] for r in quality), "worst_relative_error": worst}), flush=True)
+ record = {"key": module.key, "quality": quality, "bench": []}
+ records.append(record)
+ (out/"results.json").write_text(json.dumps(records, indent=2))
+
+ # Alternate order; flush GPU cache outside each timed measurement.
+ for rows in (1, 4, 8):
+ x = base[:rows].contiguous()
+ def calculate(candidate):
+ return inner.forward(x, {"dflash_verify": True} if candidate else {"reconstruct": True}, torch.float32)
+ for _ in range(3):
+ calculate(False); calculate(True)
+ torch.cuda.synchronize()
+ samples = {False: [], True: []}
+ for trial in range(7):
+ for candidate in ((False, True) if trial % 2 == 0 else (True, False)):
+ flush.add_(1)
+ start, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
+ start.record()
+ result = calculate(candidate)
+ end.record(); end.synchronize()
+ samples[candidate].append(start.elapsed_time(end))
+ old, new = (statistics.median(samples[k]) for k in (False, True))
+ timing = {"rows": rows, "existing_ms": old, "candidate_ms": new, "speedup": old/new}
+ record["bench"].append(timing)
+ print("BENCH:", json.dumps(timing), flush=True)
+ guards()
+ (out/"results.json").write_text(json.dumps(records, indent=2))
+ finally:
+ module.unload()
+ gc.collect()
+ torch.cuda.empty_cache()
+print("Structural checks passed. Review numerical differences and timings before a full-model A/B.", flush=True)