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.

TurboQuant KV: CUDA qdec.cu variant (codebook LUT, one scale per head), KVWIN ring on the CUDA decode path, tests for the CUDA kernel, qualify glue test

YanissAmzfbfa66ce0010
diff --git a/exllamav3/modules/attention_fn/cu/qdec.cu b/exllamav3/modules/attention_fn/cu/qdec.cu
index d45f16a..cd113cf 100644
--- a/exllamav3/modules/attention_fn/cu/qdec.cu
+++ b/exllamav3/modules/attention_fn/cu/qdec.cu
@@ -23,6 +23,12 @@
#define NTHREADS (NW * 32)
#define LOG2E 1.4426950408889634f
#define NSL (HD / 16)
+#ifndef TQ
+#define TQ 0 // TurboQuant cache (cache/tq.py): codebook LUT dequant, ONE fp16 scale per head vector, q / output rotated outside
+#endif
+#if TQ && !FASTDQ
+#error "TQ needs the FASTDQ unpack"
+#endif
// dynamic smem layout: [Qs fp16 NT*8 x QSTR][ring: NW x ST x STAGE_B] (epilogue reuses the ring for the cross-warp merge)
@@ -52,6 +58,24 @@ __device__ __forceinline__ u32 magic_mask(u32 x, u32 m) { return hsub2((x & m) |
template<int B> __device__ __forceinline__ u32 negbias2() { return (u32)(0x8000 | ((15 + B - 1) << 10)) * 0x10001u; }
__device__ __forceinline__ u32 bytesel(int b) { return (u32)b | ((u32)(4 + b) << 8); }
+// TurboQuant: packed raw pair (1024 + raw in each half) -> half2 (codebook[raw] * scale); the codebook sits in smem as fp16 bits
+#ifndef TQ_LUT
+#define TQ_LUT 0 // 0: u16 table in smem | 1: timing experiment, no table (wrong values) | 2: table replicated per lane (u32 slots, bank = lane)
+#endif
+__device__ __forceinline__ u32 lut2(u32 x, u32 s2, const u16* cb)
+{
+#if TQ_LUT == 1
+ return hmul2(hsub2(x, 0x64006400u), s2);
+#elif TQ_LUT == 2
+ const u32* cw = (const u32*)cb + (threadIdx.x & 31); // entry e of this lane's copy at word e * 32 + lane
+ u32 lo = cw[(x & 0x3FFu) << 5], hi = cw[((x >> 16) & 0x3FFu) << 5];
+ return hmul2(lo | (hi << 16), s2);
+#else
+ u32 lo = cb[x & 0x3FFu], hi = cb[(x >> 16) & 0x3FFu];
+ return hmul2(lo | (hi << 16), s2);
+#endif
+}
+
struct DqK { u32 sel8, sh4, sh2, sel2[2], sh1, mu8, mu4, mu2; };
template<int B> __device__ __forceinline__ DqK make_dqk(int t)
{
@@ -63,13 +87,14 @@ template<int B> __device__ __forceinline__ DqK make_dqk(int t)
// K pair register: dims (16U + 8S + t, 16U + 8S + t + 4) of one token row (kr = row words of this 32-dim group). The pair stays
// inside the 8-dim half (slots 0-7 / 8-15) of the mma k range it belongs to: permuting k inside a half is bit-neutral on
// the tensor core (tested), so the scores stay bit-identical to the plain dim order
-template<int B, int U, int S> __device__ __forceinline__ u32 kdq(const u32* kr, const DqK& c, u32 sc)
+template<int B, int U, int S> __device__ __forceinline__ u32 kdq(const u32* kr, const DqK& c, u32 sc, const u16* cb)
{
- u32 x = negbias2<B>();
+ u32 x = TQ ? 0x64006400u : negbias2<B>(); // TQ: 1024 + raw in both halves, the low 10 bits are the codebook index
if constexpr (B & 1) { u32 y = (kr[B & ~1] >> (c.sh1 + 16 * U + 8 * S)) & 0x11u; x = hfma2(magic_mask(y * 0x1001u, 0x00010001u), 0x3C003C00u, x); }
if constexpr (B & 2) { u32 w = kr[(B & ~3) + U] >> c.sh2; x = hfma2(magic_mask(prmt(w, w, c.sel2[S]), 0x00030003u), c.mu2, x); }
if constexpr (B & 4) { x = hfma2(magic_mask(kr[(B & ~7) + 2 * U + S] >> c.sh4, 0x000F000Fu), c.mu4, x); }
if constexpr (B & 8) { x = hfma2(magic_mask(prmt(kr[4 * U + 2 * S], kr[4 * U + 2 * S + 1], c.sel8), 0x00FF00FFu), c.mu8, x); }
+ if (TQ) return lut2(x, sc, cb);
return hfma2(x, sc, hmul2(sc, 0x38003800u));
}
@@ -92,13 +117,14 @@ template<int B> __device__ __forceinline__ DqV make_dqv(int g)
return c;
}
// V pair register: dim 16 il + g + 8 rh of two tokens (wA, wB = their row words of this 32-dim group)
-template<int B, int IL, int RH> __device__ __forceinline__ u32 vdq(const u32* wA, const u32* wB, const DqV& c, u32 sc)
+template<int B, int IL, int RH> __device__ __forceinline__ u32 vdq(const u32* wA, const u32* wB, const DqV& c, u32 sc, const u16* cb)
{
- u32 x = negbias2<B>();
+ u32 x = TQ ? 0x64006400u : negbias2<B>();
if constexpr (B & 1) { const int o = B & ~1; x = hfma2(magic_mask(prmt(wA[o], wB[o], c.sel1[IL][RH]), c.m1), c.mu1, x); }
if constexpr (B & 2) { const int o = (B & ~3) + IL; x = hfma2(magic_mask(prmt(wA[o], wB[o], c.sel2[RH]), c.m2), c.mu2, x); }
if constexpr (B & 4) { const int o = (B & ~7) + 2 * IL + RH; x = hfma2(magic_mask(prmt(wA[o], wB[o], c.sel4), c.m4), c.mu4, x); }
if constexpr (B & 8) { const int o = 4 * IL + 2 * RH; x = hfma2(magic_mask(prmt(wA[o + c.gq], wB[o + c.gq], c.sel8), c.m8), c.mu8, x); }
+ if (TQ) return lut2(x, sc, cb);
return hfma2(x, sc, hmul2(sc, 0x38003800u));
}
#endif
@@ -109,8 +135,16 @@ qdec_split(
float* __restrict__ partial_o, float* __restrict__ partial_ml,
const u16* __restrict__ k_scales, const u16* __restrict__ v_scales, const u16* __restrict__ h32,
int split_len, int num_pages_per_seq, int num_splits, const float* sinks_unused,
- void* s0, void* s1)
+ const u16* __restrict__ cbk, const u16* __restrict__ cbv)
{
+#if TQ && TQ_LUT == 2
+ __shared__ __align__(16) u32 cbk_r[(1 << KB) * 32];
+ __shared__ __align__(16) u32 cbv_r[(1 << VB) * 32];
+ const u16* cbk_s = (const u16*)cbk_r; const u16* cbv_s = (const u16*)cbv_r;
+#else
+ __shared__ u16 cbk_s[TQ ? (1 << KB) : 1];
+ __shared__ u16 cbv_s[TQ ? (1 << VB) : 1];
+#endif
extern __shared__ __align__(16) unsigned char smem[];
u16* Qs = (u16*)smem;
unsigned char* ring = smem + ((NT * 8 * QSTR * 2 + 15) / 16) * 16;
@@ -126,7 +160,22 @@ qdec_split(
const int n_end = min(n_start + split_len, total_k);
// ---- q rows -> rotated (h32) fp16 in smem
- {
+ if (TQ) { // q arrives already rotated: plain copy (K dim order permuted like below)
+#if TQ_LUT == 2
+ for (int i = tid; i < (1 << KB) * 32; i += NTHREADS) cbk_r[i] = cbk[i >> 5];
+ for (int i = tid; i < (1 << VB) * 32; i += NTHREADS) cbv_r[i] = cbv[i >> 5];
+#else
+ for (int i = tid; i < (1 << KB); i += NTHREADS) cbk_s[i] = cbk[i];
+ for (int i = tid; i < (1 << VB); i += NTHREADS) cbv_s[i] = cbv[i];
+#endif
+ for (int idx = tid; idx < NT * 8 * HD; idx += NTHREADS) {
+ int r = idx / HD, d = idx % HD;
+ u16 x = 0;
+ if (r < ROWS) x = q[((size_t)((batch * QLEN + r % QLEN) * NQH + kvh * GROUP + r / QLEN)) * HD + d];
+ Qs[r * QSTR + ((d & ~15) | (d & 8) | ((d & 3) << 1) | ((d >> 2) & 1))] = x;
+ }
+ __syncthreads();
+ } else {
float* hs = (float*)(ring); // 32x32 fp32 scratch, ring is idle until the loop
for (int i = tid; i < 1024; i += NTHREADS) hs[i] = h2f(h32[i]);
__syncthreads();
@@ -206,8 +255,14 @@ qdec_split(
cp16(vsm + tk * VSTRW + pt * 4, v_cache + (row0 + tk) * (GPT * VB) + kvh * VCHW + pt * 4, n0 + tk < n_end);
#endif
}
+#if TQ
+ // one fp16 per (token, kv head): fetch the 4-byte word holding it (NKV is even), the pair's parity picks the half
+ if (lane < 16) cp4h(ksc + lane * 2, k_scales + (row0 + lane) * NKV + (kvh & ~1), n0 + lane < n_end, pol_l);
+ else cp4h(vsc + (lane - 16) * 2, v_scales + (row0 + lane - 16) * NKV + (kvh & ~1), n0 + lane - 16 < n_end, pol_l);
+#else
if (lane < 16) cp_sc(ksc + lane * G, k_scales + (row0 + lane) * GPT + kvh * G, n0 + lane < n_end, pol_l);
else cp_sc(vsc + (lane - 16) * G, v_scales + (row0 + lane - 16) * GPT + kvh * G, n0 + lane - 16 < n_end, pol_l);
+#endif
}
asm volatile("cp.async.commit_group;");
};
@@ -242,18 +297,18 @@ qdec_split(
#if FASTDQ
#pragma unroll
for (int gi = 0; gi < G; gi++) {
- u32 sc0 = scale2<KB>(ksc[g * G + gi], ksc[g * G + gi]);
- u32 sc1 = scale2<KB>(ksc[(g + 8) * G + gi], ksc[(g + 8) * G + gi]);
+ u32 sc0 = TQ ? (u32)ksc[g * 2 + (kvh & 1)] * 0x10001u : scale2<KB>(ksc[g * G + gi], ksc[g * G + gi]);
+ u32 sc1 = TQ ? (u32)ksc[(g + 8) * 2 + (kvh & 1)] * 0x10001u : scale2<KB>(ksc[(g + 8) * G + gi], ksc[(g + 8) * G + gi]);
#pragma unroll
for (int h = 0; h < 2; h++) {
int ks = gi * 2 + h;
u32 a0, a1, a2, a3;
if (h == 0) {
- a0 = kdq<KB, 0, 0>(kr0 + gi * KB, dk, sc0); a1 = kdq<KB, 0, 0>(kr1 + gi * KB, dk, sc1);
- a2 = kdq<KB, 0, 1>(kr0 + gi * KB, dk, sc0); a3 = kdq<KB, 0, 1>(kr1 + gi * KB, dk, sc1);
+ a0 = kdq<KB, 0, 0>(kr0 + gi * KB, dk, sc0, cbk_s); a1 = kdq<KB, 0, 0>(kr1 + gi * KB, dk, sc1, cbk_s);
+ a2 = kdq<KB, 0, 1>(kr0 + gi * KB, dk, sc0, cbk_s); a3 = kdq<KB, 0, 1>(kr1 + gi * KB, dk, sc1, cbk_s);
} else {
- a0 = kdq<KB, 1, 0>(kr0 + gi * KB, dk, sc0); a1 = kdq<KB, 1, 0>(kr1 + gi * KB, dk, sc1);
- a2 = kdq<KB, 1, 1>(kr0 + gi * KB, dk, sc0); a3 = kdq<KB, 1, 1>(kr1 + gi * KB, dk, sc1);
+ a0 = kdq<KB, 1, 0>(kr0 + gi * KB, dk, sc0, cbk_s); a1 = kdq<KB, 1, 0>(kr1 + gi * KB, dk, sc1, cbk_s);
+ a2 = kdq<KB, 1, 1>(kr0 + gi * KB, dk, sc0, cbk_s); a3 = kdq<KB, 1, 1>(kr1 + gi * KB, dk, sc1, cbk_s);
}
#pragma unroll
for (int j = 0; j < NT; j++) {
@@ -331,16 +386,16 @@ qdec_split(
#if FASTDQ
#pragma unroll
for (int gi = 0; gi < G; gi++) {
- u32 sAB = scale2<VB>(vsc[(2 * t) * G + gi], vsc[(2 * t + 1) * G + gi]);
- u32 sCD = scale2<VB>(vsc[(2 * t + 8) * G + gi], vsc[(2 * t + 9) * G + gi]);
+ u32 sAB = TQ ? ((u32)vsc[(2 * t) * 2 + (kvh & 1)] | ((u32)vsc[(2 * t + 1) * 2 + (kvh & 1)] << 16)) : scale2<VB>(vsc[(2 * t) * G + gi], vsc[(2 * t + 1) * G + gi]);
+ u32 sCD = TQ ? ((u32)vsc[(2 * t + 8) * 2 + (kvh & 1)] | ((u32)vsc[(2 * t + 9) * 2 + (kvh & 1)] << 16)) : scale2<VB>(vsc[(2 * t + 8) * G + gi], vsc[(2 * t + 9) * G + gi]);
const u32 *pA = vA + gi * VB, *pB = vB + gi * VB, *pC = vC + gi * VB, *pD = vD + gi * VB;
u32 a0, a1, a2, a3;
- a0 = vdq<VB, 0, 0>(pA, pB, dv, sAB); a1 = vdq<VB, 0, 1>(pA, pB, dv, sAB);
- a2 = vdq<VB, 0, 0>(pC, pD, dv, sCD); a3 = vdq<VB, 0, 1>(pC, pD, dv, sCD);
+ a0 = vdq<VB, 0, 0>(pA, pB, dv, sAB, cbv_s); a1 = vdq<VB, 0, 1>(pA, pB, dv, sAB, cbv_s);
+ a2 = vdq<VB, 0, 0>(pC, pD, dv, sCD, cbv_s); a3 = vdq<VB, 0, 1>(pC, pD, dv, sCD, cbv_s);
#pragma unroll
for (int j = 0; j < NT; j++) mma16816(O[gi * 2][j], a0, a1, a2, a3, plo[j], phi[j]);
- a0 = vdq<VB, 1, 0>(pA, pB, dv, sAB); a1 = vdq<VB, 1, 1>(pA, pB, dv, sAB);
- a2 = vdq<VB, 1, 0>(pC, pD, dv, sCD); a3 = vdq<VB, 1, 1>(pC, pD, dv, sCD);
+ a0 = vdq<VB, 1, 0>(pA, pB, dv, sAB, cbv_s); a1 = vdq<VB, 1, 1>(pA, pB, dv, sAB, cbv_s);
+ a2 = vdq<VB, 1, 0>(pC, pD, dv, sCD, cbv_s); a3 = vdq<VB, 1, 1>(pC, pD, dv, sCD, cbv_s);
#pragma unroll
for (int j = 0; j < NT; j++) mma16816(O[gi * 2 + 1][j], a0, a1, a2, a3, plo[j], phi[j]);
}
diff --git a/exllamav3/modules/attention_fn/qdec_cuda.py b/exllamav3/modules/attention_fn/qdec_cuda.py
index 81f5734..0d4f00a 100644
--- a/exllamav3/modules/attention_fn/qdec_cuda.py
+++ b/exllamav3/modules/attention_fn/qdec_cuda.py
@@ -74,9 +74,10 @@ def _compile(cfg):
from cuda.bindings import nvrtc
defs = dict(HD=cfg["hd"], KB=cfg["kb"], VB=cfg["vb"], NKV=cfg["nkv"], NQH=cfg["nqh"], QLEN=cfg["qlen"],
PAGE=cfg["page"], NW=cfg["nw"], ST=cfg["st"], CAUSAL=int(cfg["causal"]), BLOCK_ROWS=cfg["block_rows"],
- HD_PAD=triton.next_power_of_2(cfg["hd"]), SCALE=repr(float(cfg["scale"])) + "f", KEY_LO=cfg.get("key_lo", 0))
+ HD_PAD=triton.next_power_of_2(cfg["hd"]), SCALE=repr(float(cfg["scale"])) + "f", KEY_LO=cfg.get("key_lo", 0),
+ TQ=int(cfg.get("tq", False)), TQ_LUT=int(os.environ.get("EXL3_QDEC_TQ_LUT", "0")))
defs["L2HINT"] = int(os.environ.get("EXL3_QDEC_L2HINT", "1")) # L2 evict_first on K/V, evict_last on the scales
- defs["FASTDQ"] = int(os.environ.get("EXL3_QDEC_FASTDQ", "1")) # permuted-order PRMT/LOP3 bit-plane unpack (qdec.cu)
+ defs["FASTDQ"] = 1 if cfg.get("tq") else int(os.environ.get("EXL3_QDEC_FASTDQ", "1")) # permuted-order PRMT/LOP3 bit-plane unpack (qdec.cu)
if os.environ.get("EXL3_QDEC_ABL"):
defs["ABL"] = int(os.environ["EXL3_QDEC_ABL"])
src = "#define INFINITY __int_as_float(0x7f800000)\n" + open(_COMMON).read() + "\n" + \
@@ -134,11 +135,12 @@ class _Kernel:
self._bps = max(1, n)
return self._bps
- def launch(self, grid, ptrs, ints):
- """ptrs: 11 device pointer ints (q .. h32 incl. out), ints: split_len, num_pages_per_seq, num_splits"""
+ def launch(self, grid, ptrs, ints, tq = None):
+ """ptrs: 11 device pointer ints (q .. h32 incl. out), ints: split_len, num_pages_per_seq, num_splits;
+ tq: the cache's TQState (codebook pointers)"""
import ctypes
from cuda.bindings import driver
- vals = list(ptrs) + list(ints) + [0, 0, 0] # + sinks, 2 scratch slots (unused)
+ vals = list(ptrs) + list(ints) + ([0, tq.cbk16.data_ptr(), tq.cbv16.data_ptr()] if tq is not None else [0, 0, 0]) # + sinks (unused), codebooks
types = [ctypes.c_void_p] * len(ptrs) + [ctypes.c_int] * len(ints) + [ctypes.c_void_p] * 3
stream = torch.cuda.current_stream().cuda_stream
r, = driver.cuLaunchKernel(self.fn, grid[0], grid[1], 1, 32 * self.cfg["nw"], 1, 1, self.shared, stream, (tuple(vals), tuple(types)), 0)
@@ -158,6 +160,13 @@ def rows_nw(hd):
return int(os.environ.get("EXL3_QDEC_RNW", "0")) or (4 if (hd // 32) % 4 == 0 else 2)
+def _tq_static(cfg):
+ """static smem of the TurboQuant codebooks: 2^bits u16 each, or 2^bits x 32 u32 each with the per-lane replicated table (EXL3_QDEC_TQ_LUT=2)"""
+ if os.environ.get("EXL3_QDEC_TQ_LUT", "0") == "2":
+ return ((1 << cfg["kb"]) + (1 << cfg["vb"])) * 128 + 1024
+ return 1024
+
+
def pick_nw_st(cfg):
"""(warps per CTA, ring depth), measured on a 3090 at 128K context (K/V bits 4/4, 6/6, 8/8): 8 x 2 for hd128 with
narrow codes, 4 x 2 otherwise; shrinks until the shared memory fits the opt-in limit"""
@@ -172,7 +181,7 @@ def pick_nw_st(cfg):
narrow = cfg["hd"] == 128 and cfg["kb"] + cfg["vb"] <= 8
for nw, st in (((8, 2), (4, 2), (4, 1), (2, 2), (2, 1)) if narrow else ((4, 2), (4, 1), (2, 2), (2, 1))):
c.update(nw=nw, st=st)
- if geometry(c)["shared"] <= 99 * 1024:
+ if geometry(c)["shared"] <= 99 * 1024 - (_tq_static(cfg) if cfg.get("tq") else 0): # + the static codebooks
return nw, st
raise QdecUnsupported("no ring configuration fits")
@@ -184,7 +193,7 @@ _sm = {}
def make_cfg(q_len, n_q_heads, n_kv_heads, head_dim, k_bits, v_bits, page_size, causal, sm_scale, block_rows,
- window_left, window_right, softcap, kv_append_len, key_lo = 0):
+ window_left, window_right, softcap, kv_append_len, key_lo = 0, tq = False):
"""Kernel config for a call, or None when the Triton kernels must run it. key_lo: KVWIN, positions below it are not attended"""
if (not ENABLED or window_left >= 0 or window_right >= 0 or softcap or kv_append_len != q_len
or k_bits == 0 or v_bits == 0):
@@ -193,6 +202,18 @@ def make_cfg(q_len, n_q_heads, n_kv_heads, head_dim, k_bits, v_bits, page_size,
nw=4, st=2, causal=bool(causal), scale=float(sm_scale), block_rows=block_rows)
if key_lo:
cfg["key_lo"] = int(key_lo)
+ if tq:
+ # TurboQuant: qdec.cu only (no many-row kernel); the per-head scale is fetched as a 4-byte word, so the kv head count is even
+ if n_kv_heads % 2 or cfg["hd"] % 64 != 0:
+ return None
+ cfg["tq"] = True
+ if not (supported(cfg) and geometry(cfg)["nt"] * 8 <= block_rows):
+ return None
+ try:
+ cfg["nw"], cfg["st"] = pick_nw_st(cfg)
+ except QdecUnsupported:
+ return None
+ return cfg
old_ok = supported(cfg) and geometry(cfg)["nt"] * 8 <= block_rows
# the many-row kernel also serves 2-row hd256 steps (qdec.cu needs 74 KB there: one CTA per SM)
if ROWS_MODE == "2" or (ROWS_MODE == "1" and (not old_ok or (cfg["hd"] >= 256 and cfg["qlen"] == 2))):
diff --git a/exllamav3/modules/attention_fn/triton_paged.py b/exllamav3/modules/attention_fn/triton_paged.py
index 2b143a3..a13e162 100644
--- a/exllamav3/modules/attention_fn/triton_paged.py
+++ b/exllamav3/modules/attention_fn/triton_paged.py
@@ -1241,13 +1241,13 @@ def paged_attn_triton_decode(
sinks, out, num_splits, max_kv_len, qc, pre_appended_len, n_kv_heads_override, ring, tq)
if out_hip is not None:
return out_hip
- if ATTN16 and tq is None and (qc is not None or _normalize_window(window_size)[0] >= 0):
+ if ATTN16 and (qc is not None or _normalize_window(window_size)[0] >= 0):
from .triton_paged_cu import paged_attn_triton_decode_cu, NoFittingConfig
try:
return paged_attn_triton_decode_cu(
q, k, v, k_cache, v_cache, block_table, cache_seqlens, causal, softmax_scale, window_size,
softcap, sinks, out, block_n, num_splits, max_kv_len, qc, pre_appended_len,
- n_kv_heads_override, num_warps, num_stages, split_batch, ring)
+ n_kv_heads_override, num_warps, num_stages, split_batch, ring, tq)
except NoFittingConfig:
if _ATTN16_DEBUG: print(" -- attn16 NoFittingConfig -> pre-1.6 kernels", flush = True)
pass # nothing fits this device's shared memory: the pre-1.6 kernels below
diff --git a/exllamav3/modules/attention_fn/triton_paged_cu.py b/exllamav3/modules/attention_fn/triton_paged_cu.py
index eeb9e1a..fa40368 100644
--- a/exllamav3/modules/attention_fn/triton_paged_cu.py
+++ b/exllamav3/modules/attention_fn/triton_paged_cu.py
@@ -700,6 +700,7 @@ def paged_attn_triton_decode_cu(
num_stages: int | None = None,
split_batch: int | None = None, # batch size the split count is derived from (default: bsz)
ring = None, # KVWIN: KVWinCtx; pool pass over [S, q-W], fp16 ring partial for the sinks + window
+ tq = None, # TurboQuant (cache.tq.TQState): CUDA qdec kernel only, NoFittingConfig for anything else
) -> torch.Tensor:
"""Flash-decoding paged attention for short queries: the kv sequence is split across
programs (sized from the block table, so no host sync on cache_seqlens) and reduced in a
@@ -754,7 +755,7 @@ def paged_attn_triton_decode_cu(
if qc is not None:
k_scales, v_scales, qck, qcv = qc
- h32 = _get_h32(q.device)
+ h32 = tq.eye32 if tq is not None else _get_h32(q.device)
else:
k_scales, v_scales, qck, qcv = q, q, 0, 0
h32 = q
@@ -798,7 +799,9 @@ def paged_attn_triton_decode_cu(
if qc is not None and qck > 0 and qcv > 0:
from . import qdec_cuda
qcfg = qdec_cuda.make_cfg(q_len, n_q_heads, n_kv_heads, head_dim, qck, qcv, page_size, causal, softmax_scale,
- block_rows, window_left, window_right, softcap, kv_append_len, key_lo)
+ block_rows, window_left, window_right, softcap, kv_append_len, key_lo, tq is not None)
+ if tq is not None and (qcfg is None or h_blocks != 1):
+ raise NoFittingConfig("TurboQuant: qdec.cu shapes only")
if qcfg is not None and (h_blocks == 1 or qcfg.get("rows_kernel")):
if qcfg.get("rows_kernel"):
# many-row kernel (cu/qdec_rows.cu): all of a kv head's (query, head) rows in one program
@@ -818,11 +821,11 @@ def paged_attn_triton_decode_cu(
[q.data_ptr(), k_cache.data_ptr(), v_cache.data_ptr(), block_table.data_ptr(), pool_seqlens.data_ptr(),
out.data_ptr(), partial_o.data_ptr(), partial_ml.data_ptr(), k_scales.data_ptr(), v_scales.data_ptr(),
h32.data_ptr()],
- [qsplit_len, num_pages_per_seq, ns_total])
+ [qsplit_len, num_pages_per_seq, ns_total], tq)
if ring is not None:
from .kvwin_triton import ring_split
ring_split(ring, q, cache_seqlens, h32, partial_o, partial_ml, ns_total, programs,
- q_len, n_q_heads, n_kv_heads, head_dim, hd_pad, softmax_scale, True, 0, 1, 1, block_rows)
+ q_len, n_q_heads, n_kv_heads, head_dim, hd_pad, softmax_scale, tq is None, 0, 1, 1, block_rows)
rows_sub, d_sub = combine_subtiles(block_rows, hd_pad)
_paged_attn_decode_combine_kernel[(programs, (block_rows // rows_sub) * (hd_pad // d_sub))](
partial_o, partial_ml, out, h32,
diff --git a/tests/test_tq_cache.py b/tests/test_tq_cache.py
index 197222d..f8ebdf0 100644
--- a/tests/test_tq_cache.py
+++ b/tests/test_tq_cache.py
@@ -19,13 +19,16 @@ PAGE = 256
needs_gpu = pytest.mark.skipif(not CPU and not torch.cuda.is_available(), reason = "needs a GPU (or TQ_TEST_CPU=1)")
[email protected](autouse = True, params = ["legacy", "hip"])
[email protected](autouse = True, params = ["legacy", "hip", "cu"])
def impl(request, monkeypatch):
- """Decode path: the Triton split kernel (any device) or qdec_hip (ROCm GPU only, the ROCm default)."""
+ """Decode path: the Triton split kernels (any device), qdec_hip (ROCm GPU only, the ROCm default) or qdec.cu (CUDA, the default there)"""
from exllamav3.modules.attention_fn import triton_paged
if request.param == "hip" and (CPU or not triton_paged._QDEC_HIP):
pytest.skip("qdec_hip needs a ROCm GPU")
+ if request.param == "cu" and (CPU or torch.version.hip):
+ pytest.skip("qdec.cu needs a CUDA GPU")
monkeypatch.setattr(triton_paged, "_QDEC_HIP", request.param == "hip")
+ monkeypatch.setattr(triton_paged, "ATTN16", request.param == "cu")
return request.param
@@ -118,7 +121,7 @@ class Rig:
q, k, v = self.rnd(1, n, self.qh, self.hd), self.rnd(1, n, self.kvh, self.hd), self.rnd(1, n, self.kvh, self.hd)
sl = torch.tensor([self.len], dtype = torch.int32, device = DEV)
o = attn_dispatch(q, k, v, cache = self.cl, causal = True, block_table = self.bt, cache_seqlens = sl,
- max_kv_len = self.len + n, ov = KVWinCtx(self.st, self.slots))
+ max_kv_len = self.len, ov = KVWinCtx(self.st, self.slots))
L = self.len
self.K = torch.cat([self.K, k[0]]); self.V = torch.cat([self.V, v[0]]); self.len += n
return q[0], o[0], L
diff --git a/tools/qualify/tests/test_plan.py b/tools/qualify/tests/test_plan.py
index ab9501c..4016dbc 100644
--- a/tools/qualify/tests/test_plan.py
+++ b/tools/qualify/tests/test_plan.py
@@ -248,6 +248,29 @@ class KvModeRule(unittest.TestCase):
# a model without tq support (head_dim not a power of two): only the baseline was measured
self.assertEqual(rules.choose_kv_mode({"k6v6": 0.002}, {"k6v6": 6.5}), "k6v6")
+ def test_job_kvmode_glue(self):
+ """kv stage -> job_kvmode -> kv_cache.json: the winner is written as the lane preset, serve flags follow it"""
+ import contextlib
+ from types import SimpleNamespace
+ with tempfile.TemporaryDirectory() as t:
+ t = Path(t)
+ out = t / "out"; out.mkdir(); (t / "pack").mkdir()
+ raw = {"tq6": dict(kl_vs_k8=0.004, top1_vs_k8=0.99, bits_per_val=6.0625), "tq5": dict(kl_vs_k8=0.020, top1_vs_k8=0.97, bits_per_val=5.0625),
+ "k6v6": dict(kl_vs_k8=0.010, top1_vs_k8=0.98, bits_per_val=6.5)}
+ def py(script, *a, **kw):
+ self.assertEqual((script, a[0]), ("gpu_eval.py", "kvmode"))
+ (out / "kvmode_raw.json").write_text(json.dumps({k: v for k, v in raw.items()}))
+ c = SimpleNamespace(out=out, args=dict(kvmode_steps=64), meta=dict(path=str(t / "pack"), index_sha="x"), py=py, locks=contextlib.nullcontext,
+ repo=t, data={})
+ stages._git = lambda repo: "deadbeef"
+ kv = stages.job_kvmode(c, out / "docs.pt")
+ self.assertEqual((kv["mode"], kv["chosen"]), ("tq", [6, 6]))
+ stages.write_kv_choice(c, kv)
+ j = json.loads((t / "pack" / "kv_cache.json").read_text())
+ self.assertEqual((j["kv_mode"], j["k_bits"], j["v_bits"]), ("tq", 6, 6))
+ c.data = dict(kv=kv)
+ self.assertEqual(stages.chosen_kv_mode(c), "tq")
+
def test_serve_flags_kv_mode(self):
meta = dict(serve_entry="tools/qwen/serve.py", path="/p", vision=False, template=None, mtp_layers=0, kv_layers=16, kv_heads=4, head_dim=256)
f = packmod.serve_flags(meta, port=1, ctx=4096, sessions=1, k_bits=5, v_bits=5, kv_mode="tq")