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.

tq cache: qdec.hip TQ variant (codebook in LDS, one scale per head), fused q/k/v rotation kernel, docs

YanissAmz7e9f1ef9f5ec
diff --git a/doc/kv_tq.md b/doc/kv_tq.md
new file mode 100644
index 0000000..70a3097
--- /dev/null
+++ b/doc/kv_tq.md
@@ -0,0 +1,31 @@
+# TurboQuant KV cache (`--kv-mode tq`)
+
+Per KV head vector (`head_dim` values, a power of two) the cache stores
+
+* `bits` per value: the index of the nearest Lloyd-Max centroid of `R x / ||R x||`, where `R` is an orthonormal Hadamard x random-sign rotation
+ (`cache/tq.py`) and the codebook is the one of a coordinate of a uniform random unit vector in `R^head_dim` (`cache/tq_codebooks.py`),
+* one fp16 scale per head vector: `||R x|| / ||centroid vector||`. This is the norm correction (the reconstruction has exactly the norm of
+ the input) and the only side information: `bits + 16 / head_dim` bits per value (6.06 / 5.06 at head_dim 256), against 6.5 / 5.5 for the
+ default per-32-scale cache.
+
+K and V are both stored this way. The fp16 sink-4 + window-128 ring (KVWIN) is on by default for the tq modes (`EXL3_KVWIN=0` turns it off).
+No QJL stage, no boundary-layer exceptions.
+
+```
+serve.py --k-bits 5 --v-bits 5 --kv-mode tq # tq5 (5.06 b/value); 4..6 bits, head_dim 64 / 128 / 256 / 512
+```
+
+The default (`--kv-mode quant` or nothing) is unchanged. A pack that went through `tools/qualify` has `kv_cache.json` (`kv_mode`, `k_bits`,
+`v_bits`); `serve.py` uses it when no KV flag is given.
+
+## How it fits the engine
+
+* The pool keeps `CacheLayer_quant`'s packed layout (32-value groups, power-of-two bit planes) in `qk` / `qv`; `sk` / `sv` hold one fp16 per
+ head vector. `copy_page`, save / restore, the prefix disk cache and the KVWIN stash move the same four tensors.
+* `R` is orthonormal, so `q . k = (R q) . (R k)` and `o = R^T (sum p (R v))`: `attn_dispatch` rotates q, k and v on the way in and the
+ output on the way out, and the pool, the ring and every kernel work in the rotated domain (one fused Triton launch for q, k, v).
+* Writer: `tq_triton._tq_write_kernel` (Triton, ROCm + CUDA). Decode: `qdec.hip` with `-DTQ=1` (codebook in LDS, one scale per head) on
+ ROCm; the Triton split kernel (`_qc_load_kt/v`, `TQ`) elsewhere. Prefill: the existing staging, with `tq_dequant_window` filling the fp16
+ scratch (rotated domain) before the fp16 attention kernel. The BC graph attention declines tq layers.
+* `tools/qualify` (kv stage) measures the decode-faithful 32K KL against k8v8 of k6v6, tq6 and tq5 once per model and keeps the cheapest
+ format whose KL is <= k6v6's (else k6v6); `--no-kv-modes` skips it.
diff --git a/exllamav3/cache/tq.py b/exllamav3/cache/tq.py
index 9e9f72a..0b8d47a 100644
--- a/exllamav3/cache/tq.py
+++ b/exllamav3/cache/tq.py
@@ -22,6 +22,7 @@ from ..constants import PAGE_SIZE
from .quant import CacheLayer_quant
TQ_SEED = 20240611
+_REF_ROT = os.environ.get("EXL3_TQ_REF_ROT") == "1" # torch GEMM rotation (A/B and debugging)
_REF_WRITE = os.environ.get("EXL3_TQ_REF_WRITE") == "1" # torch reference writer (A/B and debugging)
@@ -76,11 +77,18 @@ class TQState:
self.midv = ((self.cbv[1:] + self.cbv[:-1]) / 2).contiguous()
self.eye32 = torch.eye(32, dtype = torch.float16, device = device) # the kernels' H32 slot: rotation is already outside
- def rotate(self, x: torch.Tensor) -> torch.Tensor:
- """x [..., dim] fp16 -> R x"""
- return (x.reshape(-1, self.dim) @ self.rot_t).view(x.shape)
+ def rotate(self, *xs: torch.Tensor):
+ """fp16 tensors [..., dim] -> R x, same shapes (one Triton launch for all of them on a GPU)."""
+ if xs[0].is_cuda and not _REF_ROT:
+ from ..modules.attention_fn.tq_triton import tq_rotate
+ return tq_rotate(self.rot_t, *xs) if len(xs) > 1 else tq_rotate(self.rot_t, *xs)[0]
+ out = [(x.reshape(-1, self.dim) @ self.rot_t).view(x.shape) for x in xs]
+ return out if len(xs) > 1 else out[0]
def unrotate(self, y: torch.Tensor) -> torch.Tensor:
+ if y.is_cuda and not _REF_ROT:
+ from ..modules.attention_fn.tq_triton import tq_rotate
+ return tq_rotate(self.rot, y)[0]
return (y.reshape(-1, self.dim) @ self.rot).view(y.shape)
diff --git a/exllamav3/modules/attention_fn/dispatch.py b/exllamav3/modules/attention_fn/dispatch.py
index 5b5b7f6..ab93d50 100644
--- a/exllamav3/modules/attention_fn/dispatch.py
+++ b/exllamav3/modules/attention_fn/dispatch.py
@@ -133,7 +133,7 @@ def attn_dispatch(
tq = layer.get_tq() if getattr(layer, "tq", False) else None
if tq is not None:
# TurboQuant: the pool, the ring and the kernels live in the rotated domain (see cache/tq.py)
- q, k, v = tq.rotate(q), tq.rotate(k), tq.rotate(v)
+ q, k, v = tq.rotate(q, k, v)
layer.update_kv_direct(cache_seqlens, block_table, k, v, q_len)
q_cache = layer.get_qkv()
k_cache, v_cache = None, None
diff --git a/exllamav3/modules/attention_fn/qdec.hip b/exllamav3/modules/attention_fn/qdec.hip
index bdd4753..4493192 100644
--- a/exllamav3/modules/attention_fn/qdec.hip
+++ b/exllamav3/modules/attention_fn/qdec.hip
@@ -49,6 +49,9 @@ typedef u32 v8u __attribute__((ext_vector_type(8)));
#ifndef HAS_SINKS
#define HAS_SINKS 0
#endif
+#ifndef TQ
+#define TQ 0 // TurboQuant cache (cache/tq.py): codebook-LUT dequant, ONE fp16 scale per head vector, rotation done outside
+#endif
#ifndef KEY_LO
#define KEY_LO 0 // KVWIN: tokens below KEY_LO are not attended (the fp16 ring serves the sinks)
#endif
@@ -98,6 +101,13 @@ template<int B> __device__ __forceinline__ u32 dequant2(u32 raw_m, u32 s2, u32 s
return hfma2(hsub2(raw_m, c2<B>()), s2, s2h);
}
+// TurboQuant: two raw values (fp16 pair 1024 + raw) -> half2 (codebook[raw] * scale); the codebook sits in LDS as fp16 bits
+__device__ __forceinline__ u32 dequant2_tq(u32 raw_m, u32 s2, const u16* cb)
+{
+ u32 lo = cb[raw_m & 0x3FFu], hi = cb[(raw_m >> 16) & 0x3FFu];
+ return hmul2(lo | (hi << 16), s2);
+}
+
// K group plane offsets (words)
#define KO4 ((KB & 8) ? 8 : 0)
#define KO2 (KO4 + ((KB & 4) ? 4 : 0))
@@ -135,9 +145,12 @@ qdec_split(
const int* __restrict__ block_table, const int* __restrict__ cache_seqlens,
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)
+ int split_len, int num_pages_per_seq, int num_splits,
+ const u16* __restrict__ cbk, const u16* __restrict__ cbv)
{
extern __shared__ __align__(16) unsigned char smem[];
+ __shared__ u16 cbk_s[TQ ? (1 << KB) : 1];
+ __shared__ u16 cbv_s[TQ ? (1 << VB) : 1];
u16* Qs = (u16*) smem;
unsigned char* scratch = smem + ((RP * QSTR * 2 + 15) / 16) * 16;
@@ -160,8 +173,20 @@ qdec_split(
return;
}
+ if (TQ) {
+ 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];
+ }
// ---- q rows -> rotated (h32) fp16 in smem; rows >= ROWS are zero
- {
+ if (TQ) { // q arrives already rotated: plain copy
+ for (int idx = tid; idx < RP * HD; idx += NTHREADS) {
+ int r = idx / HD, d = idx % HD;
+ u16 x = 0;
+ if (r < ROWS) x = q[((size_t)((batch * QLEN + r / GROUP) * NQH + kvh * GROUP + r % GROUP)) * HD + d];
+ Qs[r * QSTR + d] = x;
+ }
+ __syncthreads();
+ } else {
float* hs = (float*) scratch; // 32x32 fp32, the scratch buffer is idle until the loop
for (int i = tid; i < 1024; i += NTHREADS) hs[i] = h2f(h32[i]);
__syncthreads();
@@ -224,9 +249,15 @@ qdec_split(
#pragma unroll
for (int c = 0; c < KWW; c++) kw[c] = kp[c];
}
- const u16* sp = k_scales + row * GPT + kvh * G + dw * GWV;
- #pragma unroll
- for (int c = 0; c < GWV; c++) ksc[c] = sp[c];
+ if (TQ) {
+ u16 s1 = k_scales[row * NKV + kvh];
+ #pragma unroll
+ for (int c = 0; c < GWV; c++) ksc[c] = s1;
+ } else {
+ const u16* sp = k_scales + row * GPT + kvh * G + dw * GWV;
+ #pragma unroll
+ for (int c = 0; c < GWV; c++) ksc[c] = sp[c];
+ }
};
if (nslabs > sw) { slab_rows(0); load_k(); }
@@ -242,7 +273,7 @@ qdec_split(
// ---- S (partial over this wave's k-steps) = Kdeq x q^T
#pragma unroll
for (int gl = 0; gl < GWV; gl++) {
- u32 sc = scale2<KB>(ksc[gl]);
+ u32 sc = TQ ? ((u32) ksc[gl] * 0x10001u) : scale2<KB>(ksc[gl]);
u32 sch = hmul2(sc, 0x38003800u); // 0x3800 = 0.5
#pragma unroll
for (int h = 0; h < 2; h++) {
@@ -250,7 +281,8 @@ qdec_split(
v8u a;
#pragma unroll
for (int i = 0; i < 8; i++)
- a[i] = dequant2<KB>(raw_pair_m<KB>(kw + gl * KB, 16 * h + 2 * i, 0, KO4, KO2, KO1), sc, sch);
+ a[i] = TQ ? dequant2_tq(raw_pair_m<KB>(kw + gl * KB, 16 * h + 2 * i, 0, KO4, KO2, KO1), sc, cbk_s)
+ : dequant2<KB>(raw_pair_m<KB>(kw + gl * KB, 16 * h + 2 * i, 0, KO4, KO2, KO1), sc, sch);
v16h af = __builtin_bit_cast(v16h, a);
#pragma unroll
for (int j = 0; j < NT; j++) {
@@ -347,7 +379,7 @@ qdec_split(
for (int e = 0; e < 16; e++) {
size_t row = (size_t) cur_row0 + min(e, cur_lim);
load_run(vr[e], v_cache + row * (GPT * VB) + kvh * VCHW + gi_v * VB, p0);
- vsc[e] = scale2<VB>(v_scales[row * GPT + kvh * G + gi_v]);
+ vsc[e] = TQ ? ((u32) v_scales[row * NKV + kvh] * 0x10001u) : scale2<VB>(v_scales[row * GPT + kvh * G + gi_v]);
}
// next slab's K (kw is dead now)
if (it + 1 < iters && (sw + (it + 1) * NSW) < nslabs) { slab_rows(it + 1); load_k(); }
@@ -357,7 +389,8 @@ qdec_split(
#pragma unroll
for (int e = 0; e < 16; e++) {
u32 sh = hmul2(vsc[e], 0x38003800u);
- dq[e] = dequant2<VB>(raw_pair_m<VB>(vr[e], 2 * u, 0, RUN_W8, RUN_W8 + RUN_W4, RUN_W8 + RUN_W4 + RUN_W2), vsc[e], sh);
+ dq[e] = TQ ? dequant2_tq(raw_pair_m<VB>(vr[e], 2 * u, 0, RUN_W8, RUN_W8 + RUN_W4, RUN_W8 + RUN_W4 + RUN_W2), vsc[e], cbv_s)
+ : dequant2<VB>(raw_pair_m<VB>(vr[e], 2 * u, 0, RUN_W8, RUN_W8 + RUN_W4, RUN_W8 + RUN_W4 + RUN_W2), vsc[e], sh);
}
v8u b0, b1;
#pragma unroll
@@ -462,7 +495,7 @@ qdec_combine(
const int pid = blockIdx.x, r = blockIdx.y, d = threadIdx.x;
const int batch = pid / NKV, kvh = pid % NKV;
const int row_q = r / GROUP, hl = r % GROUP;
- for (int i = d; i < 1024; i += HD) hs[i] = h2f(h32[i]);
+ if (!TQ) for (int i = d; i < 1024; i += HD) hs[i] = h2f(h32[i]);
float M = NEG_INF;
for (int s = 0; s < num_splits; s++) M = fmaxf(M, partial_ml[(((size_t) pid * num_splits + s) * RP + r) * 2]);
@@ -483,7 +516,10 @@ qdec_combine(
__syncthreads();
const int g = d >> 5, c = d & 31;
float y = 0.f;
+ if (TQ) y = xs[d]; // the output is un-rotated outside
+ else {
#pragma unroll
for (int k = 0; k < 32; k++) y += xs[g * 32 + k] * hs[k * 32 + c];
+ }
out[((size_t)((batch * QLEN + row_q) * NQH + kvh * GROUP + hl)) * HD + d] = __builtin_bit_cast(u16, (half_t) y);
}
diff --git a/exllamav3/modules/attention_fn/qdec_hip.py b/exllamav3/modules/attention_fn/qdec_hip.py
index 53d1c46..e6b021c 100644
--- a/exllamav3/modules/attention_fn/qdec_hip.py
+++ b/exllamav3/modules/attention_fn/qdec_hip.py
@@ -56,7 +56,7 @@ def geometry(hd, nqh, nkv, qlen, nw, dw):
def make_cfg(q_len, n_q_heads, n_kv_heads, head_dim, k_bits, v_bits, page_size, causal, sm_scale,
- window_left, window_right, softcap, kv_append_len, has_sinks, key_lo = 0):
+ window_left, window_right, softcap, kv_append_len, has_sinks, 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 not (2 <= k_bits <= 8) or not (2 <= v_bits <= 8)):
@@ -72,13 +72,13 @@ def make_cfg(q_len, n_q_heads, n_kv_heads, head_dim, k_bits, v_bits, page_size,
if shared > 64 * 1024:
return None
return dict(hd=head_dim, kb=k_bits, vb=v_bits, nkv=n_kv_heads, nqh=n_q_heads, qlen=q_len, page=page_size, nw=nw, dw=dw,
- causal=bool(causal), scale=float(sm_scale), sinks=bool(has_sinks), key_lo=int(key_lo))
+ causal=bool(causal), scale=float(sm_scale), sinks=bool(has_sinks), key_lo=int(key_lo), tq=bool(tq))
def _compile(cfg, arch):
from exllamav3.util import hip_compiler
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"], DW=cfg["dw"], CAUSAL=int(cfg["causal"]), HAS_SINKS=int(cfg["sinks"]), KEY_LO=cfg["key_lo"], SCALE=repr(float(cfg["scale"])) + "f")
+ NW=cfg["nw"], DW=cfg["dw"], CAUSAL=int(cfg["causal"]), HAS_SINKS=int(cfg["sinks"]), KEY_LO=cfg["key_lo"], TQ=int(cfg.get("tq", False)), SCALE=repr(float(cfg["scale"])) + "f")
extra = [f"-D{k}={v}" for k, v in defs.items()] + os.environ.get("EXL3_QDEC_HIP_FLAGS", "").split()
flags = ["--genco", f"--offload-arch={arch}", "-O3", "-ffp-contract=off", "--no-gpu-bundle-output"] + extra
gcc = os.environ.get("EXL3_GCC_INSTALL_DIR", "/usr/lib/gcc/x86_64-linux-gnu/13")
@@ -152,7 +152,7 @@ def num_splits(cfg, device, programs, max_k_len):
return max(1, min(-(-waves // (programs * cfg["nw"])), -(-max_k_len // 16 // cfg["nw"]), 128))
-def decode(cfg, q, k_cache, v_cache, block_table, cache_seqlens, k_scales, v_scales, h32, sinks, out, max_k_len, ring = None):
+def decode(cfg, q, k_cache, v_cache, block_table, cache_seqlens, k_scales, v_scales, h32, sinks, out, max_k_len, ring = None, tq = None):
"""q [bsz, q_len, n_q_heads, hd] fp16 -> out (same shape, fp16); caches are the packed int32 words.
ring (KVWIN, cfg built with key_lo = S): the split kernel attends [S, q - W] (cache_seqlens shifted by W) and one more
partial, written by the fp16 ring kernel after the last split, carries the sinks and the window."""
@@ -170,12 +170,13 @@ def decode(cfg, q, k_cache, v_cache, block_table, cache_seqlens, k_scales, v_sca
kern._launch(kern.split, (programs, splits), 32 * cfg["nw"], kern.shared,
[P(q.data_ptr()), P(k_cache.data_ptr()), P(v_cache.data_ptr()), P(block_table.data_ptr()), P(pool_seqlens.data_ptr()),
P(po.data_ptr()), P(pml.data_ptr()), P(k_scales.data_ptr()), P(v_scales.data_ptr()), P(h32.data_ptr()),
- I(split_len), I(block_table.shape[1]), I(ns_total)])
+ I(split_len), I(block_table.shape[1]), I(ns_total),
+ P(tq.cbk16.data_ptr() if tq is not None else None), P(tq.cbv16.data_ptr() if tq is not None else None)])
if ring is not None:
import triton
from .kvwin_triton import ring_split
ring_split(ring, q, cache_seqlens, h32, po, pml, ns_total, programs, cfg["qlen"], cfg["nqh"], cfg["nkv"], cfg["hd"],
- cfg["hd"], cfg["scale"], True, 2, 1, 1, max(16, triton.next_power_of_2(kern.rp)), rpp = kern.rp)
+ cfg["hd"], cfg["scale"], tq is None, 2, 1, 1, max(16, triton.next_power_of_2(kern.rp)), rpp = kern.rp)
kern._launch(kern.combine, (programs, rows), cfg["hd"], 0,
[P(po.data_ptr()), P(pml.data_ptr()), P(out.data_ptr()), P(h32.data_ptr()),
P(sinks.data_ptr() if cfg["sinks"] else None), I(ns_total)])
diff --git a/exllamav3/modules/attention_fn/tq_triton.py b/exllamav3/modules/attention_fn/tq_triton.py
index 69c1bce..8d75af1 100644
--- a/exllamav3/modules/attention_fn/tq_triton.py
+++ b/exllamav3/modules/attention_fn/tq_triton.py
@@ -135,3 +135,50 @@ def tq_write(x, words, scales, cb, mid, cache_seqlens, block_table, bits, n_kv_h
bits, page_size, n_kv_heads, head_dim,
num_warps = 2, num_stages = 1,
)
+
+
+def _tq_rotate_kernel(
+ x0, x1, x2, y0, y1, y2, rot_t,
+ n0, n1, n2,
+ D: tl.constexpr,
+ BM: tl.constexpr,
+ BN: tl.constexpr,
+):
+ """y = x @ rot_t (rows of D fp16) for up to three tensors in one launch: program (row block over the concatenated rows,
+ BN-wide column slice). Replaces three tiny GEMMs per attention call."""
+ pid = tl.program_id(0)
+ cb = tl.program_id(1)
+ nb0 = tl.cdiv(n0, BM)
+ nb1 = tl.cdiv(n1, BM)
+ if pid < nb0:
+ xp, yp, nr, blk = x0, y0, n0, pid
+ elif pid < nb0 + nb1:
+ xp, yp, nr, blk = x1, y1, n1, pid - nb0
+ else:
+ xp, yp, nr, blk = x2, y2, n2, pid - nb0 - nb1
+ rows = blk * BM + tl.arange(0, BM)
+ rmask = rows < nr
+ ks = tl.arange(0, D)
+ cols = cb * BN + tl.arange(0, BN)
+ xt = tl.load(xp + rows[:, None].to(tl.int64) * D + ks[None, :], mask = rmask[:, None], other = 0.0)
+ rt = tl.load(rot_t + ks[:, None] * D + cols[None, :])
+ acc = tl.dot(xt, rt)
+ tl.store(yp + rows[:, None].to(tl.int64) * D + cols[None, :], acc.to(tl.float16), mask = rmask[:, None])
+
+
+def tq_rotate(rot_t, *xs):
+ """Rotate each fp16 tensor (any leading shape, last dim = head_dim) with one launch; returns the rotated tensors (same shapes)."""
+ D = rot_t.shape[0]
+ cnt = len(xs)
+ xs = [x.contiguous() for x in xs]
+ ys = [torch.empty_like(x) for x in xs]
+ ns = [x.numel() // D for x in xs]
+ while len(xs) < 3:
+ xs.append(xs[0]); ys.append(ys[0]); ns.append(0)
+ bm = 16
+ nblk = sum(triton.cdiv(n, bm) for n in ns)
+ with torch.cuda.device(rot_t.device):
+ _tq_rotate_kernel[(nblk, D // 64)](xs[0], xs[1], xs[2], ys[0], ys[1], ys[2], rot_t, ns[0], ns[1], ns[2], D, bm, 64,
+ num_warps = 4, num_stages = 1)
+ return ys[:cnt]
diff --git a/exllamav3/modules/attention_fn/triton_paged.py b/exllamav3/modules/attention_fn/triton_paged.py
index bfd3485..2b143a3 100644
--- a/exllamav3/modules/attention_fn/triton_paged.py
+++ b/exllamav3/modules/attention_fn/triton_paged.py
@@ -1143,7 +1143,7 @@ if _QDEC_HIP_DEBUG:
def _qdec_hip_decode(q, k_cache, v_cache, block_table, cache_seqlens, causal, softmax_scale, window_size, softcap, sinks, out,
- num_splits, max_kv_len, qc, kv_append_len, n_kv_heads, ring = None):
+ num_splits, max_kv_len, qc, kv_append_len, n_kv_heads, ring = None, tq = None):
"""The qdec.hip path of paged_attn_triton_decode, or None when the call is outside its shapes (the Triton kernels then run it).
ring (KVWIN): the pool pass of qdec_hip over [S, q-W] plus the fp16 ring partial"""
k_scales, v_scales, qck, qcv = qc
@@ -1163,7 +1163,7 @@ def _qdec_hip_decode(q, k_cache, v_cache, block_table, cache_seqlens, causal, so
window_left, window_right = _normalize_window(window_size)
sinks, has_sinks = _prep_sinks(sinks, n_q_heads, q)
cfg = _qh.make_cfg(q_len, n_q_heads, n_kv_heads, head_dim, qck, qcv, k_cache.shape[1], causal, softmax_scale,
- window_left, window_right, softcap, kv_append_len, has_sinks, ring.cfg.S if ring is not None else 0)
+ window_left, window_right, softcap, kv_append_len, has_sinks, ring.cfg.S if ring is not None else 0, tq is not None)
if cfg is None:
if _QDEC_HIP_DEBUG: _qdec_hip_note(("no", f"cfg q_len {q_len} hd {head_dim} {n_q_heads}/{n_kv_heads} bits {qck},{qcv} window {window_left},{window_right} softcap {softcap} append {kv_append_len}"))
return None
@@ -1181,7 +1181,8 @@ def _qdec_hip_decode(q, k_cache, v_cache, block_table, cache_seqlens, causal, so
if out is None:
out = torch.empty_like(q)
with torch.cuda.device(q.device):
- return _qh.decode(cfg, q, k_cache, v_cache, block_table, cache_seqlens, k_scales, v_scales, _get_h32(q.device), sinks, out, max_k_len, ring)
+ return _qh.decode(cfg, q, k_cache, v_cache, block_table, cache_seqlens, k_scales, v_scales, tq.eye32 if tq is not None else _get_h32(q.device),
+ sinks, out, max_k_len, ring, tq)
# A/B switch, read once at import: CUDA decode runs the upstream exllamav3 1.6.0 (MIT) kernels in triton_paged_cu.py;
# EXL3_ATTN16=0 keeps the kernels in this file. ROCm always keeps them
@@ -1235,9 +1236,9 @@ def paged_attn_triton_decode(
_k = (tuple(q.shape), tuple(k_cache.shape), str(window_size), qc is not None, split_batch)
if _k not in _ATTN16_SEEN:
_ATTN16_SEEN.add(_k); print(" -- attn16 eager decode", _k, "new" if ATTN16 and (qc is not None or _normalize_window(window_size)[0] >= 0) else "old", flush = True)
- if qc is not None and _QDEC_HIP and k is None and tq is None:
+ if qc is not None and _QDEC_HIP and k is None:
out_hip = _qdec_hip_decode(q, k_cache, v_cache, block_table, cache_seqlens, causal, softmax_scale, window_size, softcap,
- sinks, out, num_splits, max_kv_len, qc, pre_appended_len, n_kv_heads_override, ring)
+ 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):
diff --git a/tests/test_tq_cache.py b/tests/test_tq_cache.py
index f9da18c..197222d 100644
--- a/tests/test_tq_cache.py
+++ b/tests/test_tq_cache.py
@@ -19,6 +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"])
+def impl(request, monkeypatch):
+ """Decode path: the Triton split kernel (any device) or qdec_hip (ROCm GPU only, the ROCm default)."""
+ 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")
+ monkeypatch.setattr(triton_paged, "_QDEC_HIP", request.param == "hip")
+ return request.param
+
+
@pytest.fixture(autouse = True)
def cpu_env(monkeypatch):
if not CPU:
@@ -142,3 +152,17 @@ def test_dispatch_matches_dequantized_reference(hd, bits):
r = rig.ref(q, L)
err = ((o.float() - r).norm() / r.norm()).item()
assert err < 6e-3, (hd, bits, n, L, err)
+
+
+@needs_gpu
[email protected]("D", [128, 256])
+def test_fused_rotation_matches_gemm(D):
+ from exllamav3.modules.attention_fn.tq_triton import _tq_rotate_kernel
+ st = tq.TQState.get(D, 6, 6, DEV)
+ xs = [torch.randn(n, D, device = DEV).half() for n in (24, 4, 37)]
+ ys = [torch.empty_like(x) for x in xs]
+ nblk = sum(-(-x.shape[0] // 16) for x in xs)
+ _tq_rotate_kernel[(nblk, D // 64)](xs[0], xs[1], xs[2], ys[0], ys[1], ys[2], st.rot_t, 24, 4, 37, D, 16, 64)
+ for x, y in zip(xs, ys):
+ ref = x.float() @ st.rot_t.float()
+ assert ((y.float() - ref).norm() / ref.norm()) < 1e-3