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.

Release 1.8.3 (#132)

Yaniss Amazouz2132bd248e3b
diff --git a/doc/env_vars.md b/doc/env_vars.md
index 316be72..2a9b4bb 100644
--- a/doc/env_vars.md
+++ b/doc/env_vars.md
@@ -1247,6 +1247,8 @@ latch the value at import.
| `EXL3_HC_FN_HALF_PF` | `1` | Reads the hyper-connection weights in fp16 at any row count, not only small ones, which halves the dominant traffic of that kernel. |
| `EXL3_HC_1PASS_PF` | `1` | The one-pass prefill kernel for the hyper-connection mix and norm, above the decode row cap. |
| `EXL3_DEC_DSA_FAST` | `1` | A tuned tile and split preset for the DSA decode kernel, for 2 or more rows. A list of numbers overrides the pieces. |
+| `EXL3_DSA_TQ_GATHER` | `1` | On a TurboQuant latent cache, decode first dequantizes only the gathered rows, then runs the fp16 DSA decode kernels. `0` = read the packed pages inside the kernel. |
+| `EXL3_DSA_TQ_GATHER_MAX_R` | `8` | Largest row count that takes the gathered dequantize path. |
| `EXL3_MIDCHUNK_CKPT` | `2` | A prefill chunk that crosses a recurrent checkpoint boundary also saves the recurrent state there, so the follow-up turn can resume from it. |
| `EXL3_PREFILL_BIG_TAIL` | `1` | Allows the big-chunk tail path. Honored only with `EXL3_MIDCHUNK_CKPT=2`. |
| `EXL3_BIG_TAIL_DENSE` | `1` | On a sparse single-session decode pass longer than the query-length cap, lets the tail attend densely instead of sparsely. |
diff --git a/doc/kv_tq.md b/doc/kv_tq.md
index 3b1dee3..ee76093 100644
--- a/doc/kv_tq.md
+++ b/doc/kv_tq.md
@@ -15,7 +15,7 @@ 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`,
+TurboQuant is opt-in: no flag = `--kv-mode quant` (per-32 scale pages with `--k-bits/--v-bits`, fp16 pages with no bits); `--kv-mode tq` selects TurboQuant (6 bits on ROCm, K4V4 on the NVIDIA preset), `--kv-mode fp16` forces unquantized pages. 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
@@ -37,8 +37,9 @@ The default (`--kv-mode quant` or nothing) is unchanged. A pack that went throug
* `tools/qualify` (kv stage) measures the decode-faithful 32K KL against k8v8 of k6v6, kw6 (k6v6 + the fp16 sink-4 / window-128 ring) and
tq6 / tq5 once per model. The default format is kw6 when its KL is <= 0.9 x k6v6's (a 256-step doc scatters 10-30 %: a tie stays on
k6v6), written to `kv_cache.json` as `kvwin: "4:128"` (`serve.py --kvwin`, sets `EXL3_KVWIN` before the model is built). tq6 / tq5 are
- measured and reported but stay opt-in (`--kv-mode tq`); `QUALIFY_KV_TQ=1` lets them win (fewest bytes among the formats within the
- margin, a narrower one only if every wider one qualifies). `--no-kv-modes` skips the stage. The report also lists decode s/token per format.
+ measured and reported but opt-in (`--kv-mode tq`); `QUALIFY_KV_TQ=1` lets them win (fewest bytes among the formats within the
+ margin, a narrower one only if every wider one qualifies). A model whose attention cannot hold a TurboQuant cache (QSA sparse attention, see below)
+ records tq6 / tq5 as `unsupported` and never picks them. The log-probs of the stage are kept in fp32 so close formats stay apart. `--no-kv-modes` skips the stage. The report also lists decode s/token per format.
Qualify cells, RTX 3090, one 256-step 32K doc, KL vs k8v8 (decode s/tok): Nanbeige k6v6 .00495 (.0356) | kw6 .00267 (.0361) | tq6 .00251 | tq5 .00456
-> kw6. Qwen27 k6v6 .00515 | kw6 .0478 | tq6 .0293 | tq5 .0061 -> k6v6 (one doc, noisy: the same doc gave tq6 .0125 before the kernel change).
@@ -62,3 +63,30 @@ production k6v6 on that model is the ring, not the codebook; k6v6 + ring is as g
Served A/B, same session (decode tok/s, median of 3): 4K / 32K / 120K k6v6 46.29 / 44.20 / 37.45 | kw6 46.13 / 43.75 / 38.02 | tq6 45.68 / 43.33 / 37.24
(tq6 vs kw6: -1.0 / -1.0 / -2.1 %). One 32K decode step is 27.2 ms of GPU time; tq6 adds ~0.32 ms over the same ring (q/k/v rotation 0.14, writer 0.10
more than the quant writer, qdec 0.08), the ring itself ~0.30 ms in both kw6 and tq6.
+
+## Default status (29/10): opt-in
+
+Rule for a TurboQuant default: KL no worse than k6v6 (top-1 within noise) AND decode / TTFT at least the 1.8.2 default at 4K / 32K / 128K. Qwen3.8-Flash-Next fails both on the 12-cut long-prompt probe (tq6 KL 1.14e-2 vs k6v6 8.98e-3, decode .92-.97 of the fp16 default), Qwen3.8-27B tq4 pays +5 % TTFT at 32K, so the 1.8.2 defaults stay everywhere on the Qwen path and the qualify choice stays k6v6 / kw6 (`QUALIFY_KV_TQ=1` lets tq6 / tq5 win). Qualify always passes `--kv-mode` explicitly.
+GLM-5.3 MLA latent (`CacheLayer_MLA_tq`, 28/10, real pack, 32K prefix, 32 teacher-forced decode steps, KL vs the fp16 cache): tq6 .00403, k6 .00525;
+decode 48.4 vs 49.9 ms/token (fp16 cache 44.7). The 512-wide gamma-free latent is rotated once after kv_a_layernorm (R diag(1/gamma) is one matrix), the
+rotation and gamma live in W_UK / W_UV (so q, the kernels and the output never rotate per token), DSA indexer planes stay fp16. The decode kernels read codes
+through an fp16 codebook with 32 heads per program (the expansion is paid once per head block). The first version read a zeroed norm weight (deferred
+tensor read at fold time) and gave NaN latents (KL .85): the fold now reads the weight with `no_defer`.
+
+Known limits:
+* QSA models (Qwen3.8-Flash-Next family): `Attention.cache_layer_type` maps a TQ layer to `CacheLayer_qsa_tq` (TQ pool + fp16 indexer planes). The dense
+ regime goes through the normal dispatch; the sparse regime rotates q and K/V itself and reads the codes through the codebook in the QSA split kernel
+ (BC graphs stay off for tq). Measured 28/10 on qwen38-yamz-v2-bal, 256 teacher-forced decode steps after a long doc, KL vs k8v8: k6v6 .00229,
+ tq6 .00177 (top-1 .977 vs .980), tq5 .00281; decode 41.8 vs 41.9 ms/token. CUDA must re-check the sparse split kernel with codebook loads.
+* MLA/DSA (GLM) holds `CacheLayer_MLA_tq` (eager path; the BC graph path for tq is not validated, the box runs with BC off). Head dim 192 (MiMo) has no codebook and keeps the quant cache.
+
+HIP decode kernel (box, Strix Halo, per layer at 128K, hd 256, 2 KV heads, 24 q heads): verify steps of 5..8 rows now run as row chunks on
+`qdec_hip` (before: the Triton split kernels, 32 ms; after 2.2 ms at T5, 3.3 ms at T8), and the TQ V prefetch is limited to 2 q tiles (T3 / T4 spilled
+72-79 VGPRs: tq6 3.5 -> 1.7 ms). tq6 split-kernel time is now at or below k6v6's at every row count; what is left at T1 is launch work (rotate
+q, unrotate o, ring launch): +0.06 ms vs k6v6 at 128K, +0.08 ms at 8K per layer. `tools/bench_kv_attn.py` reproduces the table. CUDA must
+re-check the same >4-row verify fallback and the TQ spills in `qdec.cu` / `qdec_rows.cu`.
+
+Prefill rotation (28/10): rotations of more than 1024 rows (prefill chunks) run as one library GEMM instead of the Triton kernel (hd 256, 2048-row
+chunk, 24 q heads 2.51 -> 0.40 ms, 2 kv heads 0.26 -> 0.02 ms; hd 128 24 heads 0.19 -> 0.06 ms); the KV write of a 2048-row chunk drops 0.73 -> 0.12 ms.
+T1 gap: GPU time per T1 call is the same as k6v6 (split 535-584 vs 543 us); the rest is host launch gaps of the 6 small eager launches (rotate x2,
+write x2, ring, ov write), which a captured graph removes.
diff --git a/exllamav3/cache/__init__.py b/exllamav3/cache/__init__.py
index 934e240..d6ffd8c 100644
--- a/exllamav3/cache/__init__.py
+++ b/exllamav3/cache/__init__.py
@@ -1,7 +1,7 @@
from .cache import Cache, CacheLayer
from .fp16 import CacheLayer_fp16
from .quant import CacheLayer_quant
-from .mla import CacheLayer_MLA_fp16, CacheLayer_MLA_quant
+from .mla import CacheLayer_MLA_fp16, CacheLayer_MLA_quant, CacheLayer_MLA_tq
from .dsa import CacheLayer_dsa
from .recurrent import RecurrentCache
from .tq import CacheLayer_tq
diff --git a/exllamav3/cache/kvwin.py b/exllamav3/cache/kvwin.py
index 3df9ab5..20f0f34 100644
--- a/exllamav3/cache/kvwin.py
+++ b/exllamav3/cache/kvwin.py
@@ -149,7 +149,7 @@ class KVWinLayerState:
self.cache_layer = cache_layer
global ANY_ACTIVE
ANY_ACTIVE = True
- cache_layer.kvwin = self # BC_Attention (per-layer graph decode) declines such layers: they run the Python path
+ cache_layer.kvwin = self # BC_Attention (per-layer graph decode) runs the ring in-graph on CUDA (bc_attn.py); on ROCm it declines such layers
@property
def active(self) -> bool:
diff --git a/exllamav3/cache/mla.py b/exllamav3/cache/mla.py
index 53fe0ab..851efa3 100644
--- a/exllamav3/cache/mla.py
+++ b/exllamav3/cache/mla.py
@@ -406,3 +406,60 @@ class CacheLayer_MLA_quant(CacheLayer):
"v_bits": self.v_bits,
}
}
+
+
+class CacheLayer_MLA_tq(CacheLayer_MLA_quant):
+ """
+ TurboQuant MLA cache layer: the normalized latent (kv_lora_rank values, a power of two) is stored as
+ Lloyd-Max codebook indices of its rotated, unit-normalized vector plus ONE fp16 scale per token
+ (norm / ||centroids||), i.e. `bits + 16 / kv_lora_rank` bits per latent value. The pool keeps
+ CacheLayer_MLA_quant's packed plane layout; `sk` is (pages, PAGE_SIZE, 1).
+
+ The rotation R (cache/tq.py, Hadamard x random signs, orthonormal) is folded into the module: the MLA
+ attention keeps its latent in the ROTATED domain end to end (kv_b's W_UK / W_UV are stored left-multiplied
+ by R, the normalized latent is rotated once after kv_a_layernorm), so the cache, the query absorption, the
+ kernels and the output un-folding never rotate anything per token. The rope key stays fp16.
+ """
+
+ tq = True
+
+ def __init__(self, config, attention, cache_id: int, max_num_tokens: int, k_bits: int, v_bits: int | None = None,
+ compand_a: float = 0.0):
+ super().__init__(config, attention, cache_id, max_num_tokens, k_bits, k_bits, 0.0)
+ from .tq import supported
+ if attention:
+ assert supported(self.kv_lora_rank, k_bits), \
+ f"tq cache: kv_lora_rank {self.kv_lora_rank} with {k_bits} bits is not supported"
+ self.sshape = (max_num_tokens // PAGE_SIZE, PAGE_SIZE, 1)
+ self.state = None
+
+ @override
+ def alloc(self, device: torch.device):
+ super().alloc(device)
+ from .tq import TQState
+ self.state = TQState.get(self.kv_lora_rank, self.k_bits, self.k_bits, device)
+
+ @override
+ def free(self):
+ super().free()
+ self.state = None
+
+ def get_tq(self):
+ return self.state
+
+ @override
+ def update_kv_direct(self, cache_seqlens, block_table, k, v, length: int):
+ """k: the ROTATED latent rows (bsz, length, kv_lora_rank) fp16; v: rope keys."""
+ from ..modules.attention_fn.tq_triton import tq_write
+ from ..modules.attention_fn.mla_triton import mla_plane_append
+ st = self.state
+ bsz = k.shape[0] if k.dim() == 3 else block_table.shape[0]
+ x = k.reshape(bsz, length, 1, self.kv_lora_rank).contiguous()
+ tq_write(x, self.qk, self.sk, st.cbk, st.midk, cache_seqlens, block_table, self.bits, 1, self.kv_lora_rank, PAGE_SIZE)
+ if self.qk_rope_head_dim:
+ mla_plane_append(v.reshape(bsz, length, self.qk_rope_head_dim),
+ self.v.view(self.v.shape[0], PAGE_SIZE, self.qk_rope_head_dim), block_table, cache_seqlens)
+
+ @override
+ def tp_export(self, plan):
+ raise NotImplementedError("the tq MLA cache does not support tensor parallel loading")
diff --git a/exllamav3/cache/qsa.py b/exllamav3/cache/qsa.py
index dad79e3..e6776a2 100644
--- a/exllamav3/cache/qsa.py
+++ b/exllamav3/cache/qsa.py
@@ -5,6 +5,7 @@ import torch
from .cache import CacheLayer
from .fp16 import CacheLayer_fp16
from .quant import CacheLayer_quant
+from .tq import CacheLayer_tq
from ..constants import PAGE_SIZE
@@ -42,6 +43,10 @@ class QSAPlanes:
self.raw_k = None
self.pooled = None
+ def update_kv_sparse(self, cache_seqlens, block_table, k, v, length: int):
+ """Write new K/V from the sparse-attention call sites (natural-domain k, v, no dispatch in front)."""
+ self.update_kv_direct(cache_seqlens, block_table, k, v, length)
+
@override
def copy_page(self, source, from_page: int, to_page: int, num_tokens: int):
super().copy_page(source, from_page, to_page, num_tokens)
@@ -111,3 +116,30 @@ class CacheLayer_qsa_quant(QSAPlanes, CacheLayer_quant):
"v_bits": self.v_bits,
}
}
+
+
+class CacheLayer_qsa_tq(QSAPlanes, CacheLayer_tq):
+ """TurboQuant KV pool (rotated domain, Lloyd-Max codes, one fp16 norm per head vector) with the fp16 QSA indexer
+ planes. The planes are the indexer's own keys and stay outside the rotation. The dense regime goes through the
+ normal dispatch (which rotates); the sparse regime rotates q and K/V itself (attn.py, QSAIndexer.sparse_attend)."""
+
+ def __init__(self, config, attention, cache_id: int, max_num_tokens: int, k_bits: int, v_bits: int, compand_a: float = 0.0):
+ super().__init__(config, attention, cache_id, max_num_tokens, k_bits, v_bits, compand_a)
+ self._init_planes(attention, max_num_tokens)
+
+ @override
+ def update_kv_sparse(self, cache_seqlens, block_table, k, v, length: int):
+ k, v = self.get_tq().rotate(k, v)
+ self.update_kv_direct(cache_seqlens, block_table, k, v, length)
+
+ @override
+ def tp_export(self, plan):
+ return {
+ "cls": CacheLayer_qsa_tq,
+ "args": {
+ "cache_id": self.cache_id,
+ "max_num_tokens": self.max_num_tokens,
+ "k_bits": self.k_bits,
+ "v_bits": self.v_bits,
+ }
+ }
diff --git a/exllamav3/cache/tq.py b/exllamav3/cache/tq.py
index 0b8d47a..21129c1 100644
--- a/exllamav3/cache/tq.py
+++ b/exllamav3/cache/tq.py
@@ -23,6 +23,7 @@ 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)
+_MM_ROWS = int(os.environ.get("EXL3_TQ_ROT_MM_ROWS", "1024")) # rotations of more rows than this run as one library GEMM (prefill chunks); fewer rows use the one-launch Triton kernel (decode / verify)
_REF_WRITE = os.environ.get("EXL3_TQ_REF_WRITE") == "1" # torch reference writer (A/B and debugging)
@@ -34,6 +35,14 @@ def codebook(dim: int, bits: int) -> torch.Tensor:
return torch.tensor(CODEBOOKS[dim, bits], dtype = torch.float32)
+def cache_is_tq(cache) -> bool:
+ """True when every attention layer of `cache` is a TurboQuant layer. A model whose attention maps the requested layer type to its own
+ variant (QSA sparse attention: CacheLayer_qsa_quant) keeps the plain quant layer, so `--kv-mode tq` there is the quant cache."""
+ from .mla import CacheLayer_MLA_quant
+ layers = [l for l in cache.layers.values() if isinstance(l, (CacheLayer_quant, CacheLayer_MLA_quant))]
+ return bool(layers) and all(getattr(l, "tq", False) for l in layers)
+
+
def supported(dim: int, bits: int) -> bool:
from .tq_codebooks import CODEBOOKS
return (dim, bits) in CODEBOOKS
@@ -79,14 +88,14 @@ class TQState:
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:
+ if xs[0].is_cuda and not _REF_ROT and sum(x.numel() for x in xs) // self.dim <= _MM_ROWS:
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:
+ if y.is_cuda and not _REF_ROT and y.numel() // self.dim <= _MM_ROWS:
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)
@@ -109,7 +118,9 @@ def decode_ref(words: torch.Tensor, scale: torch.Tensor, cb: torch.Tensor, bits:
from ..ext_fallbacks import _unpack_cache_codes
n = words.shape[0]
codes = _unpack_cache_codes(words.view(n, dim // 32, bits).to(torch.int64) & 0xffffffff, bits)
- return (cb[codes.reshape(n, dim)] * scale.float().unsqueeze(-1)).to(torch.float16)
+ # float64 product: one rounding to fp16, like the fused multiply-convert of the kernels (fp32 then fp16 rounds twice and
+ # differs where the fp32 product lands exactly on an fp16 tie)
+ return (cb[codes.reshape(n, dim)].double() * scale.double().unsqueeze(-1)).to(torch.float16)
class CacheLayer_tq(CacheLayer_quant):
diff --git a/exllamav3/exllamav3_ext/bindings.cpp b/exllamav3/exllamav3_ext/bindings.cpp
index 48794ee..d6d7aab 100644
--- a/exllamav3/exllamav3_ext/bindings.cpp
+++ b/exllamav3/exllamav3_ext/bindings.cpp
@@ -298,6 +298,7 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)
m.def("g_get_num_sms", &g_get_num_sms, "g_get_num_sms");
m.def("exl3_gemv_int8_max_k", &exl3_gemv_int8_max_k, "exl3_gemv_int8_max_k");
m.def("exl3_gemv_int8_pair", &exl3_gemv_int8_pair_eager, "exl3_gemv_int8_pair");
+ m.def("exl3_gemv_int8_tri", &exl3_gemv_int8_tri_eager, "exl3_gemv_int8_tri");
m.def("exl3_moe_cpu_make_layer", &exl3_moe_cpu_make_layer, "exl3_moe_cpu_make_layer");
m.def("exl3_moe_cpu_free_layer", &exl3_moe_cpu_free_layer, "exl3_moe_cpu_free_layer");
m.def("exl3_moe_cpu_forward", &exl3_moe_cpu_forward, "exl3_moe_cpu_forward",
@@ -457,6 +458,7 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)
m.def("exl3_moe_fused_tile_test", &exl3_moe_fused_tile_test, "exl3_moe_fused_tile_test");
m.def("exl3_gemv_int8_max_k", &exl3_gemv_int8_max_k, "exl3_gemv_int8_max_k");
m.def("exl3_gemv_int8_pair", &exl3_gemv_int8_pair_eager, "exl3_gemv_int8_pair");
+ m.def("exl3_gemv_int8_tri", &exl3_gemv_int8_tri_eager, "exl3_gemv_int8_tri");
m.def("exl3_moe_gfx12_k3", &exl3_moe_gfx12_k3, "exl3_moe_gfx12_k3");
bind_exl3_dec(m);
m.def("fused_gated_rms_norm", &fused_gated_rms_norm, "fused_gated_rms_norm");
diff --git a/exllamav3/exllamav3_ext/graph.cuh b/exllamav3/exllamav3_ext/graph.cuh
index 5fa1872..470ad1a 100644
--- a/exllamav3/exllamav3_ext/graph.cuh
+++ b/exllamav3/exllamav3_ext/graph.cuh
@@ -101,7 +101,9 @@ enum GraphedParams
GP_moe_bias_add_sel,
GP_moe_bias_add_weighted_sel,
- GP_moe_bias_add_weighted_weights
+ GP_moe_bias_add_weighted_weights,
+
+ GP_kvwin_slots
};
#if !defined(USE_ROCM)
diff --git a/exllamav3/exllamav3_ext/libtorch/attention.cpp b/exllamav3/exllamav3_ext/libtorch/attention.cpp
index 6a4c9f7..ae899f3 100644
--- a/exllamav3/exllamav3_ext/libtorch/attention.cpp
+++ b/exllamav3/exllamav3_ext/libtorch/attention.cpp
@@ -6,6 +6,7 @@
#include "../util.h"
#include "../util.cuh"
#include "../quant/exl3_gemm.cuh"
+#include "../quant/exl3_gemv_int8.cuh"
#include "../hgemm.cuh"
#include "../rope.cuh"
#include "../cache/q_cache.cuh"
@@ -382,6 +383,47 @@ void BC_Attention::configure_slot_qsa
}
}
+void BC_Attention::set_kvwin
+(
+ at::Tensor ov_k,
+ at::Tensor ov_v,
+ int sinks,
+ int window,
+ int cyclic_rows,
+ int ring_rows
+)
+{
+ TORCH_CHECK(quant_cache && !qsa, "BC_Attention: KVWIN requires a quantized cache and no QSA indexer");
+ kvwin = true;
+ kw_ov_k = std::move(ov_k);
+ kw_ov_v = std::move(ov_v);
+ kw_S = sinks;
+ kw_W = window;
+ kw_Rc = cyclic_rows;
+ kw_R = ring_rows;
+}
+
+void BC_Attention::configure_slot_kvwin
+(
+ int bsz,
+ int q_len,
+ int regime,
+ at::Tensor pool_len,
+ std::shared_ptr<TritonKernel> k_ovw,
+ std::shared_ptr<TritonKernel> k_ring,
+ int ovw_gy
+)
+{
+ TORCH_CHECK(kvwin && regime == 0, "BC_Attention: KVWIN slot without set_kvwin / in the sparse regime");
+ Slot& s = slot(bsz, q_len, regime);
+ TORCH_CHECK(s.configured, "BC_Attention: KVWIN attached to an unconfigured slot");
+ TORCH_CHECK(pool_len.is_contiguous() && pool_len.numel() >= bsz, "BC_Attention: bad pool_len static");
+ s.kw_pool_len = std::move(pool_len);
+ s.k_ovw = k_ovw;
+ s.k_ring = k_ring;
+ s.kw_ovw_gy = ovw_gy;
+}
+
// Live split configuration from the current block-table bound (same formula as the python
// dispatch path, so the two produce identical numerics)
// key blocks per split (was 4): short contexts get more CTAs (upstream exllamav3 1.6.0, MIT)
@@ -409,6 +451,7 @@ void BC_Attention::run_gr
const c10::optional<at::Tensor>& inv_freq_override,
int regime,
int64_t t_total,
+ const c10::optional<at::Tensor>& kvwin_slots,
Graph* graph
)
{
@@ -435,7 +478,23 @@ void BC_Attention::run_gr
at::Tensor xh_q = xh_flat.narrow(0, 0, (int64_t) R * hs).view({R, hs});
bool use_qg_mgemm = gate_mode == 2 && qg_ptrs_trellis.has_value() && R <= 32;
bool use_qkv = qkv_ptrs_trellis.has_value() && R <= 32;
- if (use_qkv)
+ // m == 1, no gate/bias: q, k and v as ONE int8 sq-GEMV launch over the stacked 256-column groups (the sliced mgemm
+ // streams the 33 MB bundle at ~565 GB/s, the sq kernel at ~715 GB/s). Falls back to the bundle when it declines
+ s.qkv_tri = false;
+ if (use_qkv && R == 1 && gate_mode == 0 && hs == hidden_size && !g_weight && k_proj && v_proj && !use_k_as_v &&
+ !q_proj->bias && !k_proj->bias && !v_proj->bias && q_proj->mul1 && k_proj->mul1 && v_proj->mul1 && x2.dtype() == at::kHalf)
+ {
+ at::Tensor kvt = s.kv.view({2, R, num_kv_heads * head_dim});
+ at::Tensor k_out = kvt.select(0, 0), v_out = kvt.select(0, 1);
+ s.qkv_tri = exl3_gemv_int8_tri(x2, q_proj->trellis, s.q2, q_proj->suh, q_proj->svh,
+ k_proj->trellis, k_out, k_proj->suh, k_proj->svh,
+ v_proj->trellis, v_out, v_proj->suh, v_proj->svh, stream, graph);
+ }
+ if (s.qkv_tri)
+ {
+ // Q, K, V written by the triple launch
+ }
+ else if (use_qkv)
{
// Q, K, V (and a quantized full gate) as one sliced mgemm; the K/V section below is
// skipped. The carrier only supplies the dtype and slice width
@@ -591,6 +650,34 @@ void BC_Attention::run_gr
}
}
+ // KVWIN: the new rows enter the ring (the ring pass includes the row's own key) and the pool
+ // pass gets its shortened sequence lengths (cache_seqlens - W)
+ if (kvwin)
+ {
+ std::vector<void*> args =
+ {
+ (void*) s.k4.data_ptr(),
+ (void*) s.v4.data_ptr(),
+ (void*) kw_ov_k.data_ptr(),
+ (void*) kw_ov_v.data_ptr(),
+ (void*) kvwin_slots.value().data_ptr(),
+ (void*) cache_seqlens.data_ptr(),
+ (void*) s.kw_pool_len.data_ptr(),
+ (void*) (intptr_t) q_len,
+ (void*) (intptr_t) kw_S,
+ (void*) (intptr_t) kw_Rc,
+ (void*) (intptr_t) kw_R,
+ (void*) (intptr_t) kw_W,
+ };
+ s.k_ovw->launch(bsz, s.kw_ovw_gy, num_kv_heads, args, stream);
+ if (graph)
+ {
+ graph->record_param(s.k_ovw->handle(), GP_attn_seqlens, 5);
+ graph->record_param(s.k_ovw->handle(), GP_kvwin_slots, 4);
+ graph->record_param(s.k_ovw->handle(), GP_end, 0);
+ }
+ }
+
// QSA indexer planes (both regimes, so the selection has complete history once it
// activates): fused q/raw-key projection, staging split + per-head q norm, raw-key plane
// append and the pooled keys touched by this append
@@ -766,7 +853,7 @@ void BC_Attention::run_gr
(void*) cache_k.data_ptr(),
(void*) cache_v.data_ptr(),
(void*) block_table.data_ptr(),
- (void*) cache_seqlens.data_ptr(),
+ kvwin ? (void*) s.kw_pool_len.data_ptr() : (void*) cache_seqlens.data_ptr(),
(void*) s.o.data_ptr(),
(void*) s.partial_o.data_ptr(),
(void*) s.partial_ml.data_ptr(),
@@ -775,7 +862,7 @@ void BC_Attention::run_gr
(void*) h32.data_ptr(),
(void*) (intptr_t) split_len,
(void*) (intptr_t) (int) block_table.size(1),
- (void*) (intptr_t) num_splits,
+ (void*) (intptr_t) (num_splits + (kvwin ? 1 : 0)), // KVWIN: partial stride, the ring partial is the last
(void*) s.q.data_ptr(), // sinks: dead arg, slots compile with HAS_SINKS = false
};
// Launched at the split cap so the captured grid never changes; splits at or above the
@@ -784,13 +871,42 @@ void BC_Attention::run_gr
if (graph)
{
graph->record_param(s.k_split->handle(), GP_attn_block_table, 3);
- graph->record_param(s.k_split->handle(), GP_attn_seqlens, 4);
+ if (!kvwin)
+ graph->record_param(s.k_split->handle(), GP_attn_seqlens, 4);
graph->record_param(s.k_split->handle(), GP_attn_split_len, 11, 4);
graph->record_param(s.k_split->handle(), GP_attn_num_pages, 12, 4);
graph->record_param(s.k_split->handle(), GP_attn_num_splits, 13, 4);
graph->record_param(s.k_split->handle(), GP_end, 0);
}
}
+ if (kvwin)
+ {
+ // fp16 ring pass: one more partial after the pool splits
+ std::vector<void*> args =
+ {
+ (void*) s.q.data_ptr(),
+ (void*) kw_ov_k.data_ptr(),
+ (void*) kw_ov_v.data_ptr(),
+ (void*) kvwin_slots.value().data_ptr(),
+ (void*) cache_seqlens.data_ptr(),
+ (void*) h32.data_ptr(),
+ (void*) s.partial_o.data_ptr(),
+ (void*) s.partial_ml.data_ptr(),
+ (void*) (intptr_t) (num_splits + 1),
+ (void*) (intptr_t) kw_S,
+ (void*) (intptr_t) kw_W,
+ (void*) (intptr_t) kw_Rc,
+ (void*) (intptr_t) kw_R,
+ };
+ s.k_ring->launch(s.programs, 1, 1, args, stream);
+ if (graph)
+ {
+ graph->record_param(s.k_ring->handle(), GP_kvwin_slots, 3);
+ graph->record_param(s.k_ring->handle(), GP_attn_seqlens, 4);
+ graph->record_param(s.k_ring->handle(), GP_attn_num_splits, 8, 4);
+ graph->record_param(s.k_ring->handle(), GP_end, 0);
+ }
+ }
{
std::vector<void*> args =
{
@@ -798,7 +914,7 @@ void BC_Attention::run_gr
(void*) s.partial_ml.data_ptr(),
(void*) s.o.data_ptr(),
(void*) h32.data_ptr(),
- (void*) (intptr_t) num_splits,
+ (void*) (intptr_t) (num_splits + (kvwin ? 1 : 0)),
// Static sink pointer when the module has learned sinks (combine compiled with
// HAS_SINKS), dead arg otherwise
sinks ? (void*) sinks.value().data_ptr() : (void*) s.q.data_ptr(),
@@ -853,10 +969,12 @@ void BC_Attention::run
const c10::optional<at::Tensor>& position_ids,
const c10::optional<at::Tensor>& inv_freq_override,
int regime,
- int64_t t_total
+ int64_t t_total,
+ const c10::optional<at::Tensor>& kvwin_slots
)
{
py::gil_scoped_release release;
+ TORCH_CHECK(!kvwin || kvwin_slots, "BC_Attention: KVWIN module run without ring slots");
c10::cuda::CUDAGuard device_guard(x.device());
cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream();
@@ -869,12 +987,12 @@ void BC_Attention::run
// captured, then launched below like every later run, with only the I/O pointers patched
if (graph_outer_capture(stream))
{
- run_gr(bsz, q_len, s, x, y, cache_seqlens, block_table, position, positions, position_ids, inv_freq_override, regime, t_total, nullptr);
+ run_gr(bsz, q_len, s, x, y, cache_seqlens, block_table, position, positions, position_ids, inv_freq_override, regime, t_total, kvwin_slots, nullptr);
return;
}
if (s.runs == 0)
{
- run_gr(bsz, q_len, s, x, y, cache_seqlens, block_table, position, positions, position_ids, inv_freq_override, regime, t_total, nullptr);
+ run_gr(bsz, q_len, s, x, y, cache_seqlens, block_table, position, positions, position_ids, inv_freq_override, regime, t_total, kvwin_slots, nullptr);
s.runs = 1;
return;
}
@@ -882,7 +1000,7 @@ void BC_Attention::run
if (!s.graph->ready)
{
s.graph->capture_begin();
- run_gr(bsz, q_len, s, x, y, cache_seqlens, block_table, position, positions, position_ids, inv_freq_override, regime, t_total, s.graph.get());
+ run_gr(bsz, q_len, s, x, y, cache_seqlens, block_table, position, positions, position_ids, inv_freq_override, regime, t_total, kvwin_slots, s.graph.get());
s.graph->capture_end();
s.runs = 2;
}
@@ -905,7 +1023,9 @@ void BC_Attention::run
bool use_qkv = qkv_ptrs_trellis.has_value() && R <= 32;
// Q / gate projections (an fp16 gate is a cublas node with no patchable sites)
- if (use_qkv)
+ if (s.qkv_tri)
+ params.emplace_back(GP_gemm_A, xptr); // one int8 GEMV launch covers q, k, v
+ else if (use_qkv)
params.emplace_back(GP_mgemm_A, xptr); // one sliced mgemm covers q, k, v (and a quantized gate)
else if (use_qg_mgemm)
params.emplace_back(GP_mgemm_A, xptr);
@@ -956,6 +1076,11 @@ void BC_Attention::run
params.emplace_back(GP_qcache_seqlens, (void*) cache_seqlens.data_ptr());
params.emplace_back(GP_qcache_block_table, (void*) block_table.data_ptr());
params.emplace_back(GP_qcache_blocks_per_seq, (void*) (uintptr_t) bt_width);
+ if (kvwin)
+ {
+ params.emplace_back(GP_attn_seqlens, (void*) cache_seqlens.data_ptr());
+ params.emplace_back(GP_kvwin_slots, (void*) kvwin_slots.value().data_ptr());
+ }
}
else
{
@@ -1003,12 +1128,20 @@ void BC_Attention::run
{
int num_splits, split_len;
split_config(bt_width, page_size, q_len, s.block_n, s.splits_cap, &num_splits, &split_len);
+ int ns_total = num_splits + (kvwin ? 1 : 0);
params.emplace_back(GP_attn_block_table, (void*) block_table.data_ptr());
- params.emplace_back(GP_attn_seqlens, (void*) cache_seqlens.data_ptr());
+ if (!kvwin)
+ params.emplace_back(GP_attn_seqlens, (void*) cache_seqlens.data_ptr());
params.emplace_back(GP_attn_split_len, (void*) (uintptr_t) split_len);
params.emplace_back(GP_attn_num_pages, (void*) (uintptr_t) bt_width);
- params.emplace_back(GP_attn_num_splits, (void*) (uintptr_t) num_splits);
- params.emplace_back(GP_attn_num_splits, (void*) (uintptr_t) num_splits); // combine kernel
+ params.emplace_back(GP_attn_num_splits, (void*) (uintptr_t) ns_total);
+ if (kvwin)
+ {
+ params.emplace_back(GP_kvwin_slots, (void*) kvwin_slots.value().data_ptr()); // ring partial
+ params.emplace_back(GP_attn_seqlens, (void*) cache_seqlens.data_ptr());
+ params.emplace_back(GP_attn_num_splits, (void*) (uintptr_t) ns_total);
+ }
+ params.emplace_back(GP_attn_num_splits, (void*) (uintptr_t) ns_total); // combine kernel
}
void* yptr = padded ? s.yp.data_ptr() : (void*) y.data_ptr();
params.emplace_back(GP_gemm_C, yptr);
diff --git a/exllamav3/exllamav3_ext/libtorch/attention.h b/exllamav3/exllamav3_ext/libtorch/attention.h
index f3c48c0..27ff034 100644
--- a/exllamav3/exllamav3_ext/libtorch/attention.h
+++ b/exllamav3/exllamav3_ext/libtorch/attention.h
@@ -147,6 +147,14 @@ struct BC_Attention
at::Tensor qsa_raw_plane; // flat (pages * page_size, D_i) fp16
at::Tensor qsa_pool_plane; // flat (pages * page_size / P, D_i) fp16
+ // KVWIN (cache/kvwin.py): fp16 sink+window ring next to the quantized pool. The ring writer
+ // (also derives the pool pass's sequence lengths, cache_seqlens - W) runs after the cache
+ // append, the ring pass is one more flash-decoding partial after the pool splits, and the
+ // combine reduces num_splits + 1 partials. The per-job ring slot ids are patched per call
+ bool kvwin = false;
+ at::Tensor kw_ov_k, kw_ov_v;
+ int kw_S = 0, kw_W = 0, kw_Rc = 0, kw_R = 0;
+
struct Slot
{
bool configured = false;
@@ -166,6 +174,7 @@ struct BC_Attention
at::Tensor q2, q4, k4, v4, o2, o4, qg2, g2;
at::Tensor qkv_c_ptrs; // sliced bundle: per-slice output pointers into the statics
+ bool qkv_tri = false; // q/k/v ran as one int8 GEMV launch (m == 1): the graph patches its activation pointer as a gemm A
std::shared_ptr<TritonKernel> k_split;
std::shared_ptr<TritonKernel> k_combine; // null when num_splits == 1
std::shared_ptr<TritonKernel> k_update; // null when quant_cache
@@ -187,6 +196,12 @@ struct BC_Attention
int qsa_split_len = 0;
int qsa_programs = 0;
+ // KVWIN statics/kernels (kvwin == true): pool pass sequence lengths (bsz) and the ring
+ // writer / ring partial kernels
+ at::Tensor kw_pool_len;
+ std::shared_ptr<TritonKernel> k_ovw, k_ring;
+ int kw_ovw_gy = 0;
+
std::unique_ptr<Graph> graph;
};
std::vector<Slot> slots;
@@ -266,6 +281,28 @@ struct BC_Attention
at::Tensor pool_plane
);
+ void set_kvwin
+ (
+ at::Tensor ov_k,
+ at::Tensor ov_v,
+ int sinks,
+ int window,
+ int cyclic_rows,
+ int ring_rows
+ );
+
+ // Attaches the KVWIN statics/kernels to an already-configured slot (regime 0)
+ void configure_slot_kvwin
+ (
+ int bsz,
+ int q_len,
+ int regime,
+ at::Tensor pool_len,
+ std::shared_ptr<TritonKernel> k_ovw,
+ std::shared_ptr<TritonKernel> k_ring,
+ int ovw_gy
+ );
+
bool needs_configure(int bsz, int q_len, int regime);
void configure_slot
@@ -331,7 +368,8 @@ struct BC_Attention
const c10::optional<at::Tensor>& position_ids,
const c10::optional<at::Tensor>& inv_freq_override,
int regime,
- int64_t t_total
+ int64_t t_total,
+ const c10::optional<at::Tensor>& kvwin_slots = c10::nullopt
);
void run_gr
@@ -349,6 +387,7 @@ struct BC_Attention
const c10::optional<at::Tensor>& inv_freq_override,
int regime,
int64_t t_total,
+ const c10::optional<at::Tensor>& kvwin_slots,
Graph* graph
);
diff --git a/exllamav3/exllamav3_ext/libtorch/attention_bc.h b/exllamav3/exllamav3_ext/libtorch/attention_bc.h
index 3d01cef..d05bf1e 100644
--- a/exllamav3/exllamav3_ext/libtorch/attention_bc.h
+++ b/exllamav3/exllamav3_ext/libtorch/attention_bc.h
@@ -160,6 +160,23 @@ py::class_<BC_Attention, std::shared_ptr<BC_Attention>>(m, "BC_Attention").def
py::arg("xp"),
py::arg("yp")
)
+.def("set_kvwin", &BC_Attention::set_kvwin,
+ py::arg("ov_k"),
+ py::arg("ov_v"),
+ py::arg("sinks"),
+ py::arg("window"),
+ py::arg("cyclic_rows"),
+ py::arg("ring_rows")
+)
+.def("configure_slot_kvwin", &BC_Attention::configure_slot_kvwin,
+ py::arg("bsz"),
+ py::arg("q_len"),
+ py::arg("regime"),
+ py::arg("pool_len"),
+ py::arg("k_ovw"),
+ py::arg("k_ring"),
+ py::arg("ovw_gy")
+)
.def("configure_slot_qsa", &BC_Attention::configure_slot_qsa,
py::arg("bsz"),
py::arg("q_len"),
@@ -184,4 +201,18 @@ py::class_<BC_Attention, std::shared_ptr<BC_Attention>>(m, "BC_Attention").def
py::arg("qsa_split_len") = 0,
py::arg("qsa_programs") = 0
)
-.def("run", &BC_Attention::run);
+.def("run", &BC_Attention::run,
+ py::arg("bsz"),
+ py::arg("q_len"),
+ py::arg("x"),
+ py::arg("y"),
+ py::arg("cache_seqlens"),
+ py::arg("block_table"),
+ py::arg("position"),
+ py::arg("positions"),
+ py::arg("position_ids"),
+ py::arg("inv_freq_override"),
+ py::arg("regime"),
+ py::arg("t_total"),
+ py::arg("kvwin_slots") = c10::nullopt
+);
diff --git a/exllamav3/exllamav3_ext/libtorch/mla_attention.cpp b/exllamav3/exllamav3_ext/libtorch/mla_attention.cpp
index abe2fab..5f97bd3 100644
--- a/exllamav3/exllamav3_ext/libtorch/mla_attention.cpp
+++ b/exllamav3/exllamav3_ext/libtorch/mla_attention.cpp
@@ -421,10 +421,14 @@ void BC_MLAttention::run_gr
// sequence and reads them back from the cache)
if (quant_cache)
{
- quant_cache_cont_gr(s.ckv, s.qtmp, s.stmp, 0.0f, graph);
+ // TurboQuant pages (h32 carries the fp32 codebook): no CUDA quantizer; the append kernel rotates and encodes the staged
+ // latent itself, its constants (rotation, codebook, midpoints) live in the stmp slot
+ const bool tq = h32.scalar_type() == at::kFloat;
+ if (!tq)
+ quant_cache_cont_gr(s.ckv, s.qtmp, s.stmp, 0.0f, graph);
std::vector<void*> args =
{
- (void*) s.qtmp.data_ptr(),
+ tq ? (void*) s.ckv.data_ptr() : (void*) s.qtmp.data_ptr(),
(void*) s.stmp.data_ptr(),
(void*) s.kpe.data_ptr(),
(void*) cache_ckv.data_ptr(),
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_gemv_int8_inst_sq_k1.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_gemv_int8_inst_sq_k1.cu
index cb78354..ad3e3cb 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_gemv_int8_inst_sq_k1.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_gemv_int8_inst_sq_k1.cu
@@ -19,3 +19,8 @@ void* exl3_gemv_int8_sq_sel_k1(int M, bool c_fp32, bool residual, bool dual)
#undef SELM_
return nullptr;
}
+
+void* exl3_gemv_int8_sq_tri_sel_k1(bool c_fp32)
+{
+ return c_fp32 ? nullptr : (void*) exl3_gemv_int8_sq_kernel<1, 1, false, false, false, true>;
+}
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_gemv_int8_inst_sq_k2.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_gemv_int8_inst_sq_k2.cu
index 1ce4480..d0a87bd 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_gemv_int8_inst_sq_k2.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_gemv_int8_inst_sq_k2.cu
@@ -19,3 +19,8 @@ void* exl3_gemv_int8_sq_sel_k2(int M, bool c_fp32, bool residual, bool dual)
#undef SELM_
return nullptr;
}
+
+void* exl3_gemv_int8_sq_tri_sel_k2(bool c_fp32)
+{
+ return c_fp32 ? nullptr : (void*) exl3_gemv_int8_sq_kernel<2, 1, false, false, false, true>;
+}
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_gemv_int8_inst_sq_k3.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_gemv_int8_inst_sq_k3.cu
index eff14bd..1f72f17 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_gemv_int8_inst_sq_k3.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_gemv_int8_inst_sq_k3.cu
@@ -19,3 +19,8 @@ void* exl3_gemv_int8_sq_sel_k3(int M, bool c_fp32, bool residual, bool dual)
#undef SELM_
return nullptr;
}
+
+void* exl3_gemv_int8_sq_tri_sel_k3(bool c_fp32)
+{
+ return c_fp32 ? nullptr : (void*) exl3_gemv_int8_sq_kernel<3, 1, false, false, false, true>;
+}
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_gemv_int8_inst_sq_k4.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_gemv_int8_inst_sq_k4.cu
index 47a957b..2cda133 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_gemv_int8_inst_sq_k4.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_gemv_int8_inst_sq_k4.cu
@@ -19,3 +19,8 @@ void* exl3_gemv_int8_sq_sel_k4(int M, bool c_fp32, bool residual, bool dual)
#undef SELM_
return nullptr;
}
+
+void* exl3_gemv_int8_sq_tri_sel_k4(bool c_fp32)
+{
+ return c_fp32 ? nullptr : (void*) exl3_gemv_int8_sq_kernel<4, 1, false, false, false, true>;
+}
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_gemv_int8_inst_sq_k5.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_gemv_int8_inst_sq_k5.cu
index 7e48ed2..8d0ecd1 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_gemv_int8_inst_sq_k5.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_gemv_int8_inst_sq_k5.cu
@@ -19,3 +19,8 @@ void* exl3_gemv_int8_sq_sel_k5(int M, bool c_fp32, bool residual, bool dual)
#undef SELM_
return nullptr;
}
+
+void* exl3_gemv_int8_sq_tri_sel_k5(bool c_fp32)
+{
+ return c_fp32 ? nullptr : (void*) exl3_gemv_int8_sq_kernel<5, 1, false, false, false, true>;
+}
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_gemv_int8_inst_sq_k6.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_gemv_int8_inst_sq_k6.cu
index e9a1f01..adc1b2d 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_gemv_int8_inst_sq_k6.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_gemv_int8_inst_sq_k6.cu
@@ -19,3 +19,8 @@ void* exl3_gemv_int8_sq_sel_k6(int M, bool c_fp32, bool residual, bool dual)
#undef SELM_
return nullptr;
}
+
+void* exl3_gemv_int8_sq_tri_sel_k6(bool c_fp32)
+{
+ return c_fp32 ? nullptr : (void*) exl3_gemv_int8_sq_kernel<6, 1, false, false, false, true>;
+}
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_gemv_int8_instances.cuh b/exllamav3/exllamav3_ext/quant/comp_units/exl3_gemv_int8_instances.cuh
index 7223030..16f3789 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_gemv_int8_instances.cuh
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_gemv_int8_instances.cuh
@@ -8,6 +8,12 @@ void* exl3_gemv_int8_sq_sel_k3(int M, bool c_fp32, bool residual, bool dual);
void* exl3_gemv_int8_sq_sel_k4(int M, bool c_fp32, bool residual, bool dual);
void* exl3_gemv_int8_sq_sel_k5(int M, bool c_fp32, bool residual, bool dual);
void* exl3_gemv_int8_sq_sel_k6(int M, bool c_fp32, bool residual, bool dual);
+void* exl3_gemv_int8_sq_tri_sel_k1(bool c_fp32);
+void* exl3_gemv_int8_sq_tri_sel_k2(bool c_fp32);
+void* exl3_gemv_int8_sq_tri_sel_k3(bool c_fp32);
+void* exl3_gemv_int8_sq_tri_sel_k4(bool c_fp32);
+void* exl3_gemv_int8_sq_tri_sel_k5(bool c_fp32);
+void* exl3_gemv_int8_sq_tri_sel_k6(bool c_fp32);
void* exl3_gemv_int8_coop_sel_k1(bool c_fp32, bool residual);
void* exl3_gemv_int8_coop_sel_k2(bool c_fp32, bool residual);
diff --git a/exllamav3/exllamav3_ext/quant/exl3_dec.cu b/exllamav3/exllamav3_ext/quant/exl3_dec.cu
index 27f8931..3af457c 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_dec.cu
+++ b/exllamav3/exllamav3_ext/quant/exl3_dec.cu
@@ -667,11 +667,10 @@ __device__ __forceinline__ void block_reduce(const float* acc, float* red, float
__syncthreads();
}
-// Cross-block k reduction: store this block's z to scratch, count arrivals; returns true in the
-// last arriving block (for this counter), which then holds nothing yet (caller sums partials).
-__device__ __forceinline__ bool arrive(const float* z, float* part, int ncols, int* counter, int target, int tid)
+// Cross-block arrival only (the caller has already stored its partials): fence, count, and return
+// true in the last arriving block (which then resets the counter for the next launch).
+__device__ __forceinline__ bool arrive_count(int* counter, int target, int tid)
{
- for (int col = tid; col < ncols; col += THREADS) part[col] = z[col];
__threadfence();
__syncthreads();
__shared__ int s_last;
@@ -687,6 +686,14 @@ __device__ __forceinline__ bool arrive(const float* z, float* part, int ncols, i
return true;
}
+// Cross-block k reduction: store this block's z to scratch, count arrivals; returns true in the
+// last arriving block (for this counter), which then holds nothing yet (caller sums partials).
+__device__ __forceinline__ bool arrive(const float* z, float* part, int ncols, int* counter, int target, int tid)
+{
+ for (int col = tid; col < ncols; col += THREADS) part[col] = z[col];
+ return arrive_count(counter, target, tid);
+}
+
// Ragged k split: the k extent is G groups of 8 tiles (128 inputs); block kb of kbs takes groups
// [kb * G / kbs, (kb + 1) * G / kbs), i.e. ktw = group count tiles per wave (1 .. KTW_MAX).
__device__ __forceinline__ void k_split(int G, int kb, int kbs, int& k0, int& ktw)
@@ -2432,8 +2439,37 @@ struct JobsR
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 reads
int x_row_pitch; // half-elements between consecutive rows of x (K for contiguous x)
+ int arr1; // 1: one cross-block arrival per block for all its rows (see gemv_kernel_r), else one per row
};
+// Output rotation (Hadamard + svh scale) and store of one row's reduced strip from the LDS z (waves 0-3).
+__device__ __forceinline__ void rotate_store_row(const float* z, const JobR& job, int col0, int ncols, int row, int wave, int lane)
+{
+ if (wave >= 4 || wave * 128 >= ncols) return;
+ float v[4];
+ #pragma unroll
+ for (int i = 0; i < 4; ++i) v[i] = z[wave * 128 + lane * 4 + i];
+ const int col = col0 + wave * 128 + lane * 4;
+#if !defined(EXL3_DEC_DEBUG)
+ fwht128(v, lane);
+ const uint2 sr = *reinterpret_cast<const uint2*>(job.svh + col);
+ const half* sh = reinterpret_cast<const half*>(&sr);
+ #pragma unroll
+ for (int i = 0; i < 4; ++i) v[i] *= HAD_SCALE * __half2float(sh[i]);
+#endif
+ if (job.out_fp32)
+ *reinterpret_cast<float4*>(reinterpret_cast<float*>(job.out) + (size_t) row * job.N + col) =
+ make_float4(v[0], v[1], v[2], v[3]);
+ else
+ {
+ half o[4];
+ #pragma unroll
+ for (int i = 0; i < 4; ++i) o[i] = sat_half(v[i]);
+ *reinterpret_cast<uint2*>(reinterpret_cast<half*>(job.out) + (size_t) row * job.N + col) =
+ *reinterpret_cast<uint2*>(o);
+ }
+}
+
constexpr int GEMV_R_ROW_BUDGET = MOE_R_MAX * MOE_R_KTW_MAX; // 128: max rpb * ktw
// Rows per exl3_dec_gemv_r call. One block still holds at most MOE_R_MAX rows (LDS staging, accumulators); rows beyond that run as
// further grid.y row chunks of the same launch. Every row keeps batch-1's ktw / kbs / reduction order, so the bits of a row do not
@@ -2537,6 +2573,40 @@ void gemv_kernel_r(const half* __restrict__ x, JobsR jobs, float* scratch, int*
const int col0 = strip * STRIP;
const int ncols = min(STRIP, job.N - col0);
+ if (jobs.arr1 && jobs.kbs > 1)
+ {
+ // One arrival for every row this block carries: rows differ only in their partial buffers,
+ // so a single fence + atomic (target kbs) replaces one serialized arrival per row. Per-row
+ // reduction order (kb index order) and rotation are unchanged.
+ // The slot is the counter of this block's OWN row chunk (row0), never a fixed row 0: with
+ // grid.y = nch row chunks the chunks run concurrently and each must open its own barrier
+ // after its kbs blocks arrived. Sharing one slot across chunks made the target reach early
+ // and reduced a partially written partial buffer (Qwen27 HIP 7-8 row verify: 3/3 distinct
+ // logits md5 per arm, 2026-10-28).
+ #pragma unroll
+ for (int j = 0; j < RM; ++j)
+ {
+ if (j >= nrows) break;
+ float xsum = 0.0f;
+ for (int c = 0; c < ktw; ++c) xsum += s_xsum[j][c];
+ block_reduce<CB>(acc[j], red, z, xsum, wave, lane, tid);
+ float* part = scratch + job.part_base + (size_t) (row0 + j) * jobs.kbs * job.N + (size_t) kb * job.N + col0;
+ for (int col = tid; col < ncols; col += THREADS) part[col] = z[col];
+ }
+ if (!arrive_count(counters + job.ctr_base + row0 * job.strips + strip, jobs.kbs, tid)) return;
+ #pragma unroll
+ for (int j = 0; j < RM; ++j)
+ {
+ if (j >= nrows) break;
+ const int row = row0 + j;
+ const float* p = scratch + job.part_base + (size_t) row * jobs.kbs * job.N + col0;
+ for (int col = tid; col < ncols; col += THREADS) z[col] = sum_coherent(p + col, job.N, jobs.kbs);
+ __syncthreads();
+ rotate_store_row(z, job, col0, ncols, row, wave, lane);
+ __syncthreads();
+ }
+ return;
+ }
#pragma unroll
for (int j = 0; j < RM; ++j)
{
@@ -2560,31 +2630,7 @@ void gemv_kernel_r(const half* __restrict__ x, JobsR jobs, float* scratch, int*
__syncthreads();
}
- if (wave < 4 && wave * 128 < ncols)
- {
- float v[4];
- #pragma unroll
- for (int i = 0; i < 4; ++i) v[i] = z[wave * 128 + lane * 4 + i];
- const int col = col0 + wave * 128 + lane * 4;
-#if !defined(EXL3_DEC_DEBUG)
- fwht128(v, lane);
- const uint2 sr = *reinterpret_cast<const uint2*>(job.svh + col);
- const half* sh = reinterpret_cast<const half*>(&sr);
- #pragma unroll
- for (int i = 0; i < 4; ++i) v[i] *= HAD_SCALE * __half2float(sh[i]);
-#endif
- if (job.out_fp32)
- *reinterpret_cast<float4*>(reinterpret_cast<float*>(job.out) + (size_t) row * job.N + col) =
- make_float4(v[0], v[1], v[2], v[3]);
- else
- {
- half o[4];
- #pragma unroll
- for (int i = 0; i < 4; ++i) o[i] = sat_half(v[i]);
- *reinterpret_cast<uint2*>(reinterpret_cast<half*>(job.out) + (size_t) row * job.N + col) =
- *reinterpret_cast<uint2*>(o);
- }
- }
+ rotate_store_row(z, job, col0, ncols, row, wave, lane);
if (jobs.kbs > 1) __syncthreads();
}
}
@@ -2657,6 +2703,12 @@ static void dec_gemv_r_impl
// 5..8 rows only (the <= 4 row launches keep their grid); 9..32 rows swap by default (EXL3_GEMV_R_SWAP9=0 restores the plain grid):
// the chunks of one weight block then run side by side and share its reads through L2 instead of re-streaming the weights per chunk
jobs.swap = (env_int("EXL3_GEMV_R_CHUNK_FAST", 0) != 0 || (R > MOE_R_MAX && env_int("EXL3_GEMV_R_SWAP9", 1) != 0)) && R > 4 && R > rpb;
+ // EXL3_GEMV_R_ARR1 (default 1): one cross-block arrival per block instead of one per row (one fence + one atomic for
+ // all the rows a block carries). Sound for any chunking because the counter slot is the block's own row chunk
+ // (kernel: ctr_base + row0 * strips + strip): each chunk opens its own barrier after exactly its kbs blocks arrived.
+ // The earlier row-0-only slot was racy once a job ran more than one chunk (7..8 row verify, 9..32 row MoE rows:
+ // repeated runs gave different logits). Per-row reduction order is untouched, so output is bit-identical to ARR1=0.
+ jobs.arr1 = env_int("EXL3_GEMV_R_ARR1", 1) != 0;
jobs.x_row_pitch = Kdim;
int blocks = 0, part = 0, ctr = 0;
for (int i = 0; i < n; ++i)
diff --git a/exllamav3/exllamav3_ext/quant/exl3_gemv_int8.cu b/exllamav3/exllamav3_ext/quant/exl3_gemv_int8.cu
index a350d6c..79c45ba 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_gemv_int8.cu
+++ b/exllamav3/exllamav3_ext/quant/exl3_gemv_int8.cu
@@ -123,6 +123,20 @@ static void* select_gemv_int8_sq_kernel(int K, int M, bool c_fp32, bool residual
return nullptr;
}
+static void* select_gemv_int8_sq_tri_kernel(int K, bool c_fp32)
+{
+ switch (K)
+ {
+ case 1: return exl3_gemv_int8_sq_tri_sel_k1(c_fp32);
+ case 2: return exl3_gemv_int8_sq_tri_sel_k2(c_fp32);
+ case 3: return exl3_gemv_int8_sq_tri_sel_k3(c_fp32);
+ case 4: return exl3_gemv_int8_sq_tri_sel_k4(c_fp32);
+ case 5: return exl3_gemv_int8_sq_tri_sel_k5(c_fp32);
+ case 6: return exl3_gemv_int8_sq_tri_sel_k6(c_fp32);
+ }
+ return nullptr;
+}
+
// Fixed-size per-device workspace shared by the sq and coop paths, allocated once and never
// reallocated: the pointer is baked as a kernel argument into captured CUDA graphs, so growing the
// buffer would leave every previously captured graph with a dangling workspace pointer (and let a
@@ -160,13 +174,18 @@ static bool exl3_gemv_int8_sq
int device, int num_sms, cudaStream_t stream, Graph* graph,
// Second matrix of a dual launch (same shape, K and output type), all null for a single GEMV
const half* A2_ptr = nullptr, const uint16_t* B2_ptr = nullptr, void* C2_ptr = nullptr,
- const half* suh2_ptr = nullptr, const half* svh2_ptr = nullptr
+ const half* suh2_ptr = nullptr, const half* svh2_ptr = nullptr,
+ // tri: B2/C2/suh2/svh2 are the second matrix of width n2, the third is (B3, C3, suh3, svh3, n3); same activations, m == 1
+ int n2 = 0, const uint16_t* B3_ptr = nullptr, void* C3_ptr = nullptr,
+ const half* suh3_ptr = nullptr, const half* svh3_ptr = nullptr, int n3 = 0
)
{
if (size_m > 2) return false;
- const bool dual = B2_ptr != nullptr;
+ const bool tri = B3_ptr != nullptr;
+ const bool dual = B2_ptr != nullptr && !tri;
+ if (tri && (size_m != 1 || residual || c_fp32 || n2 > size_n || n3 > size_n || n2 % 256 || n3 % 256)) return false;
int M = size_m;
- void* fn = select_gemv_int8_sq_kernel(K, M, c_fp32, residual, dual);
+ void* fn = tri ? select_gemv_int8_sq_tri_kernel(K, c_fp32) : select_gemv_int8_sq_kernel(K, M, c_fp32, residual, dual);
if (!fn) return false;
int rows_max = gemv_int8_sq_rows_max(M, residual);
@@ -177,7 +196,7 @@ static bool exl3_gemv_int8_sq
auto decomp = [&] (int grid_, int& ksplit, int& rows_per)
{
int rows_total = size_k / 16;
- int nb256 = size_n / 256;
+ int nb256 = (size_n + (tri ? n2 + n3 : 0)) / 256;
int r = CEIL_DIVIDE(rows_total * nb256, grid_);
rows_per = (MAX(r, MIN(2 * r, 32)) + 7) & ~7;
rows_per = MAX(rows_per, SQ_MINROWS);
@@ -228,7 +247,7 @@ static bool exl3_gemv_int8_sq
int maxb;
// A pair takes the grid, and so the slice decomposition, its single-matrix kernel would get: that keeps the pair
// bit-identical to two launches even where the pair instantiation needs more registers (lower occupancy)
- void* fn_occ = dual ? select_gemv_int8_sq_kernel(K, M, c_fp32, residual, false) : fn;
+ void* fn_occ = (dual || tri) ? select_gemv_int8_sq_kernel(K, M, c_fp32, residual, false) : fn;
if (!fn_occ) return false;
auto occ_key = std::make_pair(fn_occ, smem_guess);
auto occ_it = gemv_occ_cache[device].find(occ_key);
@@ -253,11 +272,12 @@ static bool exl3_gemv_int8_sq
int rows_eff = rows_per; // the kernel takes the host's slice height (single source of truth)
size_t smem = smem_for(rows_per);
if (ksplit > SQ_KSPLIT_CAP) return false;
- if ((dual ? 2 : 1) * (size_n / 256) > SQ_COUNTERS_CAP) return false; // counters, per matrix
- if ((dual ? 2 : 1) * ksplit * M > 4 * SQ_KSPLIT_CAP) return false; // (slice, row) scale entries
+ const int nmat = tri ? 3 : (dual ? 2 : 1);
+ if (tri ? (size_n + n2 + n3) / 256 > SQ_COUNTERS_CAP : nmat * (size_n / 256) > SQ_COUNTERS_CAP) return false; // counters, per matrix
+ if (nmat * ksplit * M > 4 * SQ_KSPLIT_CAP) return false; // (slice, row) scale entries
int pstride = size_n * (residual ? 2 : 1);
- int* ws_ptr = gemv_int8_get_ws(device, SQ_WS_RESERVED + (size_t) (dual ? 2 : 1) * ksplit * M * pstride);
+ int* ws_ptr = gemv_int8_get_ws(device, SQ_WS_RESERVED + (size_t) nmat * ksplit * M * pstride);
if (!ws_ptr) return false;
void* kernelArgs[] =
@@ -277,7 +297,13 @@ static bool exl3_gemv_int8_sq
(void*) &B2_ptr,
(void*) &C2_ptr,
(void*) &suh2_ptr,
- (void*) &svh2_ptr
+ (void*) &svh2_ptr,
+ (void*) &n2,
+ (void*) &B3_ptr,
+ (void*) &C3_ptr,
+ (void*) &suh3_ptr,
+ (void*) &svh3_ptr,
+ (void*) &n3
};
cudaError_t err = cudaLaunchKernel(fn, dim3(grid), dim3(NUM_THREADS), kernelArgs, smem, stream);
@@ -290,7 +316,16 @@ static bool exl3_gemv_int8_sq
if (exl3_gemv_int8_trace())
fprintf(stderr, "[exl3_gemv_int8] sq kernel: m=%d k=%d n=%d K=%d residual=%d dual=%d grid=%d rows_per=%d ksplit=%d smem=%zu\n",
size_m, size_k, size_n, K, (int) residual, (int) dual, grid, rows_per, ksplit, smem);
- if (dual)
+ if (tri)
+ {
+ // The outputs are the caller's statics; only the activation pointer changes between replays
+ if (graph)
+ {
+ graph->record_param(fn, GP_gemm_A, 0);
+ graph->record_param(fn, GP_end, 0);
+ }
+ }
+ else if (dual)
{
// Only the activation and output pointers change between calls (the weights are static); recorded
// in the (A, C, A, C) order of two back-to-back single GEMVs so the caller's patch list is the same
@@ -491,6 +526,10 @@ bool exl3_gemv_int8_pair
if (K < 1 || K > exl3_gemv_int8_max_k(device)) return false;
bool residual = exl3_gemv_int8_mode() == 1;
if (size_m > (residual ? 1 : 2)) return false;
+ // Pair rows cap: at m == 2 the pair kernel (more registers, 2x staging and partials per unit) measures SLOWER than two
+ // single launches on 3090 (gate/up 5120x17408 K4: 134-140 us vs 2 x 64); bit-identical either way. EXL3_GEMV_PAIR_MAXM=2 restores it.
+ static const int pair_maxm = [] { const char* e = getenv("EXL3_GEMV_PAIR_MAXM"); return e ? atoi(e) : 1; }();
+ if (size_m > pair_maxm) return false;
int num_sms = DevCtx::instance().get_num_sms(device);
return exl3_gemv_int8_sq(
(const half*) A.data_ptr(), (const uint16_t*) B1.data_ptr(), C1.data_ptr(),
@@ -512,3 +551,53 @@ bool exl3_gemv_int8_pair_eager
const at::cuda::OptionalCUDAGuard device_guard(A.device());
return exl3_gemv_int8_pair(A, B1, C1, suh1, svh1, B2, C2, suh2, svh2, at::cuda::getCurrentCUDAStream().stream(), nullptr);
}
+
+// q/k/v style triple: three mul1 GEMVs of different widths over one activation row in ONE sq launch (m == 1, fp16 outputs).
+// Not bit-identical to three launches (one slice height for the stack); EXL3_GEMV_TRI=0 disables. Returns false for the caller's fallback.
+bool exl3_gemv_int8_tri
+(
+ const at::Tensor& A,
+ const at::Tensor& B1, at::Tensor& C1, const c10::optional<at::Tensor>& suh1, const c10::optional<at::Tensor>& svh1,
+ const at::Tensor& B2, at::Tensor& C2, const c10::optional<at::Tensor>& suh2, const c10::optional<at::Tensor>& svh2,
+ const at::Tensor& B3, at::Tensor& C3, const c10::optional<at::Tensor>& suh3, const c10::optional<at::Tensor>& svh3,
+ cudaStream_t stream,
+ Graph* graph
+)
+{
+ static const int mode = [] { const char* e = getenv("EXL3_GEMV_TRI"); return e ? atoi(e) : 1; }();
+ if (!mode || !exl3_gemv_int8_enabled()) return false;
+ if (!suh1 || !svh1 || !suh2 || !svh2 || !suh3 || !svh3) return false;
+ if (C1.dtype() != at::kHalf || C2.dtype() != at::kHalf || C3.dtype() != at::kHalf) return false;
+ int K = B1.size(2) / 16;
+ if (B2.size(2) / 16 != K || B3.size(2) / 16 != K || B2.size(0) != B1.size(0) || B3.size(0) != B1.size(0)) return false;
+ int size_k = A.size(-1);
+ int size_n = B1.size(1) * 16, n2 = B2.size(1) * 16, n3 = B3.size(1) * 16;
+ int size_m = A.numel() / size_k;
+ if (size_m != 1 || size_n % 256 || size_k % 128) return false;
+ int device;
+ cudaGetDevice(&device);
+ if (K < 1 || K > exl3_gemv_int8_max_k(device)) return false;
+ bool residual = exl3_gemv_int8_mode() == 1;
+ if (residual) return false;
+ int num_sms = DevCtx::instance().get_num_sms(device);
+ return exl3_gemv_int8_sq(
+ (const half*) A.data_ptr(), (const uint16_t*) B1.data_ptr(), C1.data_ptr(),
+ size_m, size_k, size_n, K, false, residual,
+ (const half*) suh1->data_ptr(), nullptr, (const half*) svh1->data_ptr(),
+ device, num_sms, stream, graph,
+ (const half*) A.data_ptr(), (const uint16_t*) B2.data_ptr(), C2.data_ptr(),
+ (const half*) suh2->data_ptr(), (const half*) svh2->data_ptr(),
+ n2, (const uint16_t*) B3.data_ptr(), C3.data_ptr(), (const half*) suh3->data_ptr(), (const half*) svh3->data_ptr(), n3);
+}
+
+bool exl3_gemv_int8_tri_eager
+(
+ const at::Tensor& A,
+ const at::Tensor& B1, at::Tensor& C1, const c10::optional<at::Tensor>& suh1, const c10::optional<at::Tensor>& svh1,
+ const at::Tensor& B2, at::Tensor& C2, const c10::optional<at::Tensor>& suh2, const c10::optional<at::Tensor>& svh2,
+ const at::Tensor& B3, at::Tensor& C3, const c10::optional<at::Tensor>& suh3, const c10::optional<at::Tensor>& svh3
+)
+{
+ const at::cuda::OptionalCUDAGuard device_guard(A.device());
+ return exl3_gemv_int8_tri(A, B1, C1, suh1, svh1, B2, C2, suh2, svh2, B3, C3, suh3, svh3, at::cuda::getCurrentCUDAStream().stream(), nullptr);
+}
diff --git a/exllamav3/exllamav3_ext/quant/exl3_gemv_int8.cuh b/exllamav3/exllamav3_ext/quant/exl3_gemv_int8.cuh
index 9a361c1..fd8f91d 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_gemv_int8.cuh
+++ b/exllamav3/exllamav3_ext/quant/exl3_gemv_int8.cuh
@@ -47,3 +47,21 @@ bool exl3_gemv_int8_pair_eager
const at::Tensor& B1, at::Tensor& C1, const c10::optional<at::Tensor>& suh1, const c10::optional<at::Tensor>& svh1,
const at::Tensor& B2, at::Tensor& C2, const c10::optional<at::Tensor>& suh2, const c10::optional<at::Tensor>& svh2
);
+
+bool exl3_gemv_int8_tri
+(
+ const at::Tensor& A,
+ const at::Tensor& B1, at::Tensor& C1, const c10::optional<at::Tensor>& suh1, const c10::optional<at::Tensor>& svh1,
+ const at::Tensor& B2, at::Tensor& C2, const c10::optional<at::Tensor>& suh2, const c10::optional<at::Tensor>& svh2,
+ const at::Tensor& B3, at::Tensor& C3, const c10::optional<at::Tensor>& suh3, const c10::optional<at::Tensor>& svh3,
+ cudaStream_t stream,
+ Graph* graph
+);
+
+bool exl3_gemv_int8_tri_eager
+(
+ const at::Tensor& A,
+ const at::Tensor& B1, at::Tensor& C1, const c10::optional<at::Tensor>& suh1, const c10::optional<at::Tensor>& svh1,
+ const at::Tensor& B2, at::Tensor& C2, const c10::optional<at::Tensor>& suh2, const c10::optional<at::Tensor>& svh2,
+ const at::Tensor& B3, at::Tensor& C3, const c10::optional<at::Tensor>& suh3, const c10::optional<at::Tensor>& svh3
+);
diff --git a/exllamav3/exllamav3_ext/quant/exl3_gemv_int8_kernel.cuh b/exllamav3/exllamav3_ext/quant/exl3_gemv_int8_kernel.cuh
index 1563993..8e9b326 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_gemv_int8_kernel.cuh
+++ b/exllamav3/exllamav3_ext/quant/exl3_gemv_int8_kernel.cuh
@@ -343,6 +343,21 @@ __device__ __forceinline__ void gemv_int8_row_sums
#define SQ_COUNTERS_CAP 4096 // fixed counter region: size_n up to 1M
#define SQ_WS_RESERVED (SQ_COUNTERS_CAP + 4 * SQ_KSPLIT_CAP * 4) // sq-private region at workspace start (counters + per-slice-per-row scales, m <= 4)
+// Weight-stream load: read-only, no L1 allocation, L2 evict-first (the trellis rows are read exactly once per
+// launch). Measured on 3090 (bit-identical): M = 1 -0.5..-1.9 us per launch, M = 2 flat-to-worse, so M = 1 only.
+template <bool hint>
+__device__ __forceinline__ uint2 ldg_stream_u2(const uint32_t* p)
+{
+#if defined(USE_ROCM)
+ return *(const uint2*) p;
+#else
+ if constexpr (!hint) return *(const uint2*) p;
+ uint2 r;
+ asm volatile("ld.global.nc.L1::no_allocate.v2.u32 {%0,%1}, [%2];" : "=r"(r.x), "=r"(r.y) : "l"(p));
+ return r;
+#endif
+}
+
// Wide unit (4 bpw): one (256-column x k-slice) unit, warp per adjacent block pair, uint2 loads.
// M activation rows share the decoded weights: extraction and the B stream are amortized, each row
// only adds its dp4a chains against its own splat region (sh_as + r * slice_stride; residual splats
@@ -372,14 +387,14 @@ __device__ __forceinline__ void gemv_int8_unit_wide
int shfl_src = (lane & 16) | ((lane + 15) & 15);
int iacc0[M] = {}, iacc1[M] = {}, jacc0[M] = {}, jacc1[M] = {};
- uint2 r0 = *(const uint2*) bp;
+ uint2 r0 = ldg_stream_u2<(M == 1)>(bp);
uint2 r1 = {};
- if (nrows > 1) r1 = *(const uint2*) (bp + row_stride);
+ if (nrows > 1) r1 = ldg_stream_u2<(M == 1)>(bp + row_stride);
for (int kb = 0; kb < nrows; ++kb)
{
uint2 r2 = {};
- if (kb + 2 < nrows) r2 = *(const uint2*) (bp + (size_t) (kb + 2) * row_stride);
+ if (kb + 2 < nrows) r2 = ldg_stream_u2<(M == 1)>(bp + (size_t) (kb + 2) * row_stride);
uint32_t prev = __shfl_sync(0xffffffff, r0.y, shfl_src);
uint32_t w0, w1, w2, w3, w4, w5, w6, w7;
@@ -1018,9 +1033,33 @@ __host__ __device__ constexpr int gemv_int8_sq_rows_max(int M, bool residual)
return cap < SQ_ROWS_MAX ? cap : SQ_ROWS_MAX;
}
+// L2 prefetch of the head of a unit's weight stream (first EXL3_SQ_PF block rows of its 256-column stripe), issued BEFORE the (not K=3: the extra registers drop its occupancy 5 -> 4 blocks/SM)
+// serial slice staging so the DRAM is busy during the staging instead of idle (no registers held across the staging, unlike a
+// register pre-issue). Layout: row stride 2 * bits * size_n bytes, stripe 512 * bits bytes = 4 * bits 128-byte lines.
+#ifndef EXL3_SQ_PF
+#define EXL3_SQ_PF 8
+#endif
+template <int bits>
+__device__ __forceinline__ void gemv_int8_prefetch_unit(const uint16_t* __restrict__ B, int nb256, int kb0, int nrows, int size_n)
+{
+#if !defined(USE_ROCM)
+ constexpr int lines = 4 * bits;
+ int rows_pf = nrows < EXL3_SQ_PF ? nrows : EXL3_SQ_PF;
+ int i = threadIdx.x;
+ if (i < lines * rows_pf)
+ {
+ const char* base = (const char*) B + (size_t) kb0 * size_n * 2 * bits + (size_t) nb256 * 512 * bits;
+ asm volatile("prefetch.global.L2 [%0];" :: "l"(base + (size_t) (i / lines) * size_n * 2 * bits + (i % lines) * 128));
+ }
+#endif
+}
+
// dual: a second matrix (B2, ...) is computed by the same launch; a separate instantiation so the single-matrix
// kernels keep their register budget (and so their occupancy)
-template <int bits, int M, bool c_fp32, bool residual, bool dual = false>
+// tri: three matrices of different widths over the same activations (q, k, v of an attention block) stacked along the
+// 256-column groups in one launch; the slice height comes from the host (rows_ovr), the second/third matrix are
+// (B2, C2, suh2, svh2, n2) and (B3, C3, suh3, svh3, n3), the first is the usual (B, C, suh, svh, size_n)
+template <int bits, int M, bool c_fp32, bool residual, bool dual = false, bool tri = false>
__global__ __launch_bounds__(NUM_THREADS)
void exl3_gemv_int8_sq_kernel
(
@@ -1041,7 +1080,13 @@ void exl3_gemv_int8_sq_kernel
const uint16_t* __restrict__ B2,
void* __restrict__ C2,
const half* __restrict__ suh2,
- const half* __restrict__ svh2
+ const half* __restrict__ svh2,
+ const int n2,
+ const uint16_t* __restrict__ B3,
+ void* __restrict__ C3,
+ const half* __restrict__ suh3,
+ const half* __restrict__ svh3,
+ const int n3
)
{
extern __shared__ uint32_t shmem[];
@@ -1055,7 +1100,8 @@ void exl3_gemv_int8_sq_kernel
int nb256_mat = size_n / 256;
// A pair stacks the matrices: each (slice, 256-column) unit runs for both back to back, with the slice
// height, and so the numerics, of a single launch
- int nb256_total = nb256_mat;
+ const int nbm1 = tri ? n2 / 256 : 0, nbm2 = tri ? n3 / 256 : 0;
+ int nb256_total = tri ? nb256_mat + nbm1 + nbm2 : nb256_mat;
int r = CEIL_DIVIDE(rows_total * nb256_total, (int) gridDim.x);
int rows_per = (MAX(r, MIN(2 * r, 32)) + 7) & ~7;
rows_per = MAX(rows_per, SQ_MINROWS);
@@ -1086,6 +1132,55 @@ void exl3_gemv_int8_sq_kernel
int t = threadIdx.x;
int prev_key = -1;
+ if constexpr (tri)
+ {
+ const bool share3 = suh2 == suh && suh3 == suh;
+ for (int unit = blockIdx.x; unit < units; unit += gridDim.x)
+ {
+ int slice = unit / nb256_total;
+ int g = unit % nb256_total;
+ int mat = g < nb256_mat ? 0 : (g < nb256_mat + nbm1 ? 1 : 2);
+ int nb256 = mat == 0 ? g : (mat == 1 ? g - nb256_mat : g - nb256_mat - nbm1);
+ const uint16_t* B_m = mat == 0 ? B : (mat == 1 ? B2 : B3);
+ void* C_m = mat == 0 ? C : (mat == 1 ? C2 : C3);
+ const half* suh_m = mat == 0 ? suh : (mat == 1 ? suh2 : suh3);
+ const half* svh_m = mat == 0 ? svh : (mat == 1 ? svh2 : svh3);
+ int n_m = mat == 0 ? size_n : (mat == 1 ? n2 : n3);
+ int smat = share3 ? 0 : mat;
+ float* qsums_m = qsums + 4 * smat * ms;
+ int kb0 = slice * rows_per;
+ int nrows = MIN(rows_per, rows_total - kb0);
+ int key = slice * 3 + smat;
+ if (key != prev_key)
+ {
+ gemv_int8_stage_slice<M, residual>(A, size_m, size_k, suh_m, qsums_m + 4 * slice * M,
+ sh_ah, sh_as, slice_stride, sh_red, kb0, nrows);
+ prev_key = key;
+ }
+ int* pacc = partials + ((size_t) mat * ms + (size_t) slice * M) * pstride;
+ if constexpr (bits == 4)
+ gemv_int8_unit_wide<M, residual, false>(B_m, pacc, pstride, sh_as, slice_stride, nb256, kb0, nrows, n_m);
+ else if constexpr (gemv_int8_stage_smem(bits))
+ gemv_int8_unit_smem<bits, M, residual, false>(B_m, pacc, pstride, sh_as, slice_stride, sh_b, nb256, kb0, nrows, n_m);
+ else
+ gemv_int8_unit_narrow<bits, M, residual, false>(B_m, pacc, pstride, sh_as, slice_stride, nb256, kb0, nrows, n_m);
+ __threadfence();
+ __syncthreads();
+ int* counter = counters + g;
+ if (t == 0) sh_last = (atomicAdd(counter, 1) == ksplit - 1) ? 1 : 0;
+ __syncthreads();
+ if (sh_last)
+ {
+#if defined(USE_ROCM)
+ __threadfence();
+#endif
+ gemv_int8_epilogue_group_sq<M, c_fp32, residual>(partials + (size_t) mat * ms * pstride, qsums_m, pstride, ksplit,
+ size_m, C_m, svh_m, sh_tmp, nb256, n_m);
+ if (t == 0) *counter = 0;
+ }
+ }
+ return;
+ }
for (int unit = blockIdx.x; unit < units; unit += gridDim.x)
{
int slice = unit / nb256_total;
@@ -1102,6 +1197,9 @@ void exl3_gemv_int8_sq_kernel
int kb0 = slice * rows_per;
int nrows = MIN(rows_per, rows_total - kb0);
int key = slice * 2 + smat;
+#if EXL3_SQ_PF > 0
+ if constexpr (M == 1 && bits != 3) gemv_int8_prefetch_unit<bits>(B_m, nb256, kb0, nrows, size_n);
+#endif
if (key != prev_key)
{
gemv_int8_stage_slice<M, residual>(A_m, size_m, size_k, suh_m, qsums_m + 4 * slice * M,
diff --git a/exllamav3/generator/chunk_il.py b/exllamav3/generator/chunk_il.py
index f19a6fe..9059c08 100644
--- a/exllamav3/generator/chunk_il.py
+++ b/exllamav3/generator/chunk_il.py
@@ -82,7 +82,13 @@ class ChunkPlanner:
self.row_s = float(e("EXL3_CIL_ROW_S", "0.0007")) if row_s is None else row_s # 2.9 s per 4096-row chunk until measured
self.decode_s = float(e("EXL3_CIL_DECODE_S", "0.05")) if decode_s is None else decode_s
self.dprio = e("EXL3_CIL_DECODE_PRIO", "0") == "1"
- self.dprio_chunk = max(256, int(e("EXL3_CIL_DPRIO_CHUNK", "768")) // 256 * 256)
+ # decode-priority chunk: EXL3_CIL_DPRIO_CHUNK=<rows> pins it; unset = time-based, EXL3_CIL_DPRIO_CHUNK_S (1.5 s) of the leader's
+ # measured s/row, capped at EXL3_CIL_DPRIO_CHUNK_MAX rows (2048), floor 256. Same decode share on a fast and on a slow
+ # model (fixed 768 rows: 0.5 s on Qwen3.8 but 1.0 s on GLM-5.3; 2048 fixed starved the GLM streams to 0.34 tok/s).
+ pin = e("EXL3_CIL_DPRIO_CHUNK", "")
+ self._dprio_pin = max(256, int(pin) // 256 * 256) if pin else 0
+ self._dprio_s = float(e("EXL3_CIL_DPRIO_CHUNK_S", "1.5"))
+ self._dprio_max = max(256, int(e("EXL3_CIL_DPRIO_CHUNK_MAX", "2048")) // 256 * 256)
self.single_decode = (e("EXL3_CIL_SINGLE_DECODE", "1") != "0" and not self.dprio) if single_decode is None else single_decode
self._clock = clock
self._lead: _Leader | None = None
@@ -91,6 +97,12 @@ class ChunkPlanner:
self._last_decoded: dict[Any, int] = {}
self.finished: list[dict] = [] # stats of the last leaders that completed (bounded)
+ @property
+ def dprio_chunk(self) -> int:
+ if self._dprio_pin:
+ return self._dprio_pin
+ return max(256, min(self._dprio_max, int(self._dprio_s / max(self.row_s, 1e-6)) // 256 * 256))
+
# ---- helpers
def _stats(self, ld: _Leader, now: float) -> dict:
return {"deferred_s": round(ld.used, 4), "budget_s": round(self._budget(ld), 3), "slices": ld.slices, "chunks": ld.chunks,
diff --git a/exllamav3/generator/generator.py b/exllamav3/generator/generator.py
index 88dfbb6..adff1c7 100644
--- a/exllamav3/generator/generator.py
+++ b/exllamav3/generator/generator.py
@@ -4,6 +4,7 @@ import logging
import os
import time
import torch
+from ..model import cuda_graph as _cuda_graph
try:
from ..modules.moe_fused import check_barrier as _moe_fused_check # fused MoE half-layer grid barrier: raise if it ever timed out
except Exception: # noqa: BLE001
@@ -44,6 +45,8 @@ from .job import Job, _ttrace_begin, _ttrace_end, _TAIL_REPLY as _TAIL_REPLY_GEN
# once the results are handed out; every iterate / cancel / clear_queue runs it first, so later work sees the same cache state in
# the same order (exact by construction). Pays where the stash is a blocking copy (HIP .cpu(), CUDA EXL3_TAIL_PIN=0).
_REPLY_FIRST = os.environ.get("EXL3_REPLY_FIRST", "0") == "1"
+_LAG1_DEBUG = os.environ.get("EXL3_LAG1_DEBUG", "0") == "1"
+_LAG1 = os.environ.get("EXL3_LAG1", "0") == "1" # lag-1 decode pipeline (see Generator._gen_lag1)
from . import spec_sample
from .filter import Filter
from .row_groups import plan_groups, group_rows_cap, plain_rows_verify, GROUPS as ROW_GROUPS
@@ -624,11 +627,37 @@ class Generator:
self.flush_deferred()
if _TORCH_PROF is not None:
return self._iterate_profiled()
+ if _CPROF is not None and not _CPROF["done"] and any(j.is_prefill_done() for j in self.active_jobs):
+ return self._iterate_cprofiled()
results = self._iterate_inner()
if _moe_fused_check is not None:
_moe_fused_check(self.model)
return results
+ def _iterate_cprofiled(self) -> list[dict]:
+ """EXL3_CPROF=SKIP:STEPS:PATH (diagnostic): cProfile of STEPS decode iterations after SKIP of them (host time per function; cuda syncs show where the host waits for the GPU)."""
+ import cProfile, pstats
+ st = _CPROF
+ st["seen"] += 1
+ if st["seen"] <= st["skip"]:
+ return self._iterate_inner()
+ if st["prof"] is None:
+ st["prof"] = cProfile.Profile(); st["t0"] = time.perf_counter()
+ st["prof"].enable()
+ try:
+ results = self._iterate_inner()
+ finally:
+ st["prof"].disable()
+ st["n"] += 1
+ if st["n"] == st["steps"]:
+ wall = time.perf_counter() - st["t0"]
+ with open(st["path"], "w") as f:
+ f.write(f"{st['steps']} iterations, wall {wall / st['steps'] * 1000:.2f} ms/iter (profiled-region wall incl. unprofiled gaps)\n")
+ for key in ("tottime", "cumtime"):
+ ps = pstats.Stats(st["prof"], stream = f); ps.sort_stats(key).print_stats(45)
+ st["done"] = True
+ return results
+
def _iterate_profiled(self) -> list[dict]:
"""EXL3_TORCH_PROF=JOBS:SKIP:STEPS:PATH (diagnostic): once JOBS requests have been decoding together for SKIP iterations,
profile the next STEPS iterations with the torch profiler and write the kernel table (per iteration) to PATH."""
@@ -948,7 +977,8 @@ class Generator:
# Regular generation
else:
- self.iterate_gen(results)
+ if not (_LAG1 and self._gen_lag1(results)):
+ self.iterate_gen(results)
_ttrace_end("generation round", _t0)
# Visualization
@@ -1656,6 +1686,177 @@ class Generator:
params["export_states"] = [torch.cat(parts, dim = 0) for parts in zip(*exports)]
return torch.cat(logits, dim = 0)
+
+ # ---------------------------------------------------------------------------------------------------------------------
+ # Lag-1 decode pipeline (EXL3_LAG1=1). Plain decode (no draft, no recurrent cache) normally pays one host round trip
+ # per step: sample on the device -> read the token -> host bookkeeping -> build the next step's inputs -> launch. Here the
+ # next step is launched from the DEVICE token right after the sampler, before the host reads token k, so the GPU runs
+ # step k+1 while the host processes token k (one step of lag). The step in flight is adopted by the next call.
+ # A job that ends at token k leaves a wasted row in the step already in flight (its KV write lands in its own pages, in
+ # stream order ahead of any later reuse); that row is simply never sampled. Whatever the pipeline cannot do (filters,
+ # penalties, forced tokens, healing, banned strings, probs, drafts, recurrent caches, a job about to hit a token
+ # limit, waiting/prefilling jobs, a page boundary, no GPU embedding table) takes the regular loop.
+ # Needs the whole-forward CUDA graph with the GPU embedding table (cuda_graph.py, EXL3_GPU_EMB).
+ _lag = None
+ _lag_par = 0
+
+ def _lag1_job_ok(self, job) -> bool:
+ if len(job.sequences) != 1 or job.filters or job.embeddings or job.forced_ids is not None:
+ return False
+ if job.new_tokens < 0 or job.checkpoint is not None or job.banned_strings:
+ return False
+ if job.return_probs or job.return_top_tokens > 0 or job.sampler.reqs_past_ids:
+ return False
+ return True
+
+ def _lag1_ready(self) -> bool:
+ if self.draft_model or self.ngram_match_min or self.visualizer or _TAIL_REPLY_GEN or "mrope" in self.model.caps:
+ return False
+ if self.num_draft_tokens or ROW_GROUPS["on"] and ROW_INV["on"] and self.model.caps.get("row_inv_groups"):
+ return False
+ if _cuda_graph.CUDA_GRAPH_ENABLED and not torch.version.hip:
+ runner = self.model.__dict__.get("_cuda_graph_runner")
+ g = getattr(runner, "_gemb", None) if runner is not None else None
+ return g is not None and g is not False
+ return self.model.lag_table() is not None
+
+ def _lag1_params(self, jobs, rows_ids_shape, nxt: int):
+ """Inputs of the step `nxt` positions after the current host state (0 = now, 1 = the step after the token in flight)."""
+ par = self._lag_par = self._lag_par ^ 1
+ n = len(jobs)
+ max_seq_len = max(job.get_max_seq_len() for job in jobs) + nxt
+ max_pages_batch = block_table_pages(max_seq_len)
+ block_index = self._staging(f"block_index_l{par}", n, max_pages_batch)
+ block_index.zero_()
+ cache_seqlens = self._staging(f"cache_seqlens_l{par}", n)
+ for b, job in enumerate(jobs):
+ seq = job.sequences[0]
+ bi = seq.block_index_tensor[:, :max_pages_batch]
+ block_index[b:b + 1, :bi.shape[-1]].copy_(bi)
+ cache_seqlens[b] = seq.kv_position + nxt
+ params = {
+ "attn_mode": "flash_attn",
+ "block_table": block_index,
+ "cache": self.cache,
+ "cache_seqlens": cache_seqlens,
+ "recurrent_states": [job.recurrent_state for job in jobs] if (self.ring_states or self.recurrent_cache is not None) else None,
+ "indexed_embeddings": [],
+ "positions": None,
+ "recurrent_history": False,
+ "pinned_staging": True,
+ "dflash_verify": plain_rows_verify(n, False),
+ }
+ return params
+
+ def _gen_lag1(self, results: list) -> bool:
+ """One pipelined decode round. Returns False (nothing done) when the regular loop must run this round."""
+ st = self._lag
+ if st is None:
+ if not self._lag1_ready():
+ return False
+ jobs = [j for j in self.active_jobs if j.is_prefill_done()]
+ if not jobs or len(jobs) != len(self.active_jobs) or self.pending_jobs or not all(self._lag1_job_ok(j) for j in jobs):
+ return False
+ # step k from host ids (regular forward; the cuda graph runner takes the ids through its GPU table)
+ _first = [j for j in jobs if j.time_first_token is None]
+ if _first:
+ cuda_sync_active()
+ for j in _first: j.time_first_token = time.time()
+ ids_list = []
+ for job in jobs:
+ ids_list += job.get_input_ids_list(None, len(ids_list), add_to_cache = True)
+ batch_ids = torch.cat(ids_list, dim = 0)
+ if batch_ids.shape[-1] != 1:
+ return False
+ params = self._lag1_params(jobs, batch_ids.shape, 0)
+ logits = self.model.forward(input_ids = batch_ids, params = params)
+ else:
+ self._lag = None
+ jobs, logits = st["jobs"], st["logits"]
+ for job in jobs:
+ if job in self.active_jobs:
+ job.get_input_ids_list(None, 0, add_to_cache = True) # the token that was fed from the device is on the host now
+
+ live = [(i, job) for i, job in enumerate(jobs) if job in self.active_jobs]
+ if not live:
+ return True
+ n_live = len(live)
+ pinned = self.sample_pinned
+ if pinned is None or pinned.shape[0] < n_live:
+ self.sample_pinned = pinned = torch.empty((max(n_live, 32), 1), dtype = torch.long, pin_memory = True)
+ launched = []
+ dev_tokens = []
+ for k, (i, job) in enumerate(live):
+ job.prepare_logit_mask()
+ job.prepare_sampling_past_ids()
+ tl = logits[i:i + 1, :, :]
+ sampled = job.receive_logits(tl)
+ nt = sampled[0]
+ dev_tokens.append(nt.view(1, 1))
+ pinned[k:k + 1].copy_(nt.view(1, 1), non_blocking = True)
+ launched.append((job, tl, (pinned[k:k + 1],) + sampled[1:]))
+ ev = torch.cuda.Event()
+ ev.record()
+
+ # launch the next step from the device tokens, unless something needs the host first
+ nxt = None
+ live_jobs = [job for _, job in live]
+ ahead = (
+ self._lag1_ready() and not self.pending_jobs and len(live_jobs) == len(self.active_jobs) and
+ all(self._lag1_job_ok(j) for j in live_jobs)
+ )
+ if ahead:
+ for job in live_jobs:
+ seq = job.sequences[0]
+ lim = job.max_new_tokens
+ if (lim is not None and job.new_tokens + 2 > lim) or job.new_tokens + 2 > job.max_rq_tokens:
+ ahead = False; break
+ # a recurrent state with a token in flight is one position ahead of the host: keep checkpoint / stash positions
+ # (page boundaries) out of the window where the next iterate would read it
+ if self.recurrent_cache is not None and not 3 <= seq.kv_position % PAGE_SIZE <= PAGE_SIZE - 4:
+ ahead = False; break
+ if (seq.kv_position + 1) // PAGE_SIZE >= len(seq.allocated_pages) or \
+ seq.allocated_pages[(seq.kv_position + 1) // PAGE_SIZE].ref_count != 1:
+ ahead = False; break
+ if ahead:
+ ids_dev = torch.cat(dev_tokens, dim = 0).to(torch.long)
+ params = self._lag1_params(live_jobs, ids_dev.shape, 1)
+ nlogits = self.model.forward_dev(ids_dev, params)
+ if nlogits is not None:
+ nxt = {"jobs": live_jobs, "logits": nlogits}
+ ev.synchronize()
+
+ completed_jobs = []
+ requeuing_jobs = []
+ for job, token_logits, (next_token, next_k_tokens, next_k_probs, next_prob) in launched:
+ eos, sampled_token, rq = job.receive_sample(token_logits, next_token, next_k_tokens, next_k_probs, next_prob, results)
+ if job.checkpoint_rewound:
+ job.checkpoint_rewound = False
+ if len(job.sequences) == 1 and rq:
+ requeuing_jobs.append(job)
+ elif eos:
+ completed_jobs.append(job)
+
+ num_jobs = self.num_remaining_jobs()
+ for job in completed_jobs + requeuing_jobs:
+ if _REPLY_FIRST and job not in requeuing_jobs:
+ self.deferred_jobs.append(job)
+ else:
+ job.deallocate_pages()
+ self.active_jobs.remove(job)
+ for job in requeuing_jobs:
+ rq_job = job.prepare_for_requeue()
+ self.pending_jobs.insert(0, rq_job)
+ if num_jobs and not self.num_remaining_jobs() and not self.deferred_jobs:
+ self.on_queue_drained()
+ self._lag = nxt if self.active_jobs else None
+ if _LAG1_DEBUG:
+ c = self._lag_stats = getattr(self, "_lag_stats", [0, 0, 0])
+ c[0] += 1; c[1] += int(nxt is not None); c[2] += int(st is not None)
+ if c[0] % 100 == 0:
+ print(f"[lag1] rounds {c[0]} launched-ahead {c[1]} adopted {c[2]}", flush = True)
+ return True
+
def iterate_gen(self, results: list, draft_tokens: torch.Tensor | None = None):
_HP0[0] = time.perf_counter()
@@ -2510,6 +2711,10 @@ _PF_PROF = None
if os.environ.get("EXL3_PF_PROF"):
_pa = os.environ["EXL3_PF_PROF"].rsplit(":", 1)
_PF_PROF = dict(path = _pa[0], call = int(_pa[1]), seen = 0, done = False)
+_CPROF = None
+if os.environ.get("EXL3_CPROF"):
+ _cp = os.environ["EXL3_CPROF"].split(":", 2)
+ _CPROF = dict(skip = int(_cp[0]), steps = int(_cp[1]), path = _cp[2], seen = 0, n = 0, prof = None, done = False)
_TORCH_PROF = None
if os.environ.get("EXL3_TORCH_PROF"):
_a = os.environ["EXL3_TORCH_PROF"].split(":", 3)
diff --git a/exllamav3/kernel_seed/triton-3.7.0-gfx1151.tar.xz b/exllamav3/kernel_seed/triton-3.7.0-gfx1151.tar.xz
index 7d85c4e..bd00b39 100644
Binary files a/exllamav3/kernel_seed/triton-3.7.0-gfx1151.tar.xz and b/exllamav3/kernel_seed/triton-3.7.0-gfx1151.tar.xz differ
diff --git a/exllamav3/model/cuda_graph.py b/exllamav3/model/cuda_graph.py
index 7d90789..f4955b8 100644
--- a/exllamav3/model/cuda_graph.py
+++ b/exllamav3/model/cuda_graph.py
@@ -132,7 +132,7 @@ def _stream_for(dev_index: int):
class _Entry:
__slots__ = ("graph", "out", "x_in", "bt", "cs", "pos", "params", "warm", "last_used", "cache_ref", "fp",
- "slots", "slots_src", "exports", "swa_cs", "swa_host")
+ "slots", "slots_src", "exports", "swa_cs", "swa_host", "ids")
def _cache_fp(cache):
@@ -190,6 +190,7 @@ class CudaGraphRunner:
self.has_conv = False
self.has_mamba = False
self.has_swa = False
+ self.has_ring = False
self.swa_mods = []
_registry.append(weakref.ref(self))
@@ -213,6 +214,7 @@ class CudaGraphRunner:
self.has_conv = False
self.has_mamba = False
self.has_swa = False
+ self.has_ring = False
self.swa_mods = []
for mod, inst, _ in fm[1:]:
t = type(mod)
@@ -285,6 +287,10 @@ class CudaGraphRunner:
if mod.device is None:
return False
devs.add(torch.device(mod.device))
+ # KVWIN ring-only models (plain attention + fp16 sink/window rings riding the recurrent state slots): the ring ids are
+ # static slot data exactly like a GDN model's, the ring writer/reader run inside the capture (bc_attn.py)
+ from ..cache import kvwin
+ self.has_ring = bool(kvwin.ANY_ACTIVE) and os.environ.get("EXL3_CUDA_GRAPH_RING", "1") != "0" and not (self.has_gdn or self.has_conv or self.has_mamba or self.has_swa)
if len(devs) != 1 or (self.has_gdn and self.has_conv):
return False # GDN graphs pass device slot ids, ShortConv reads them on the host: no mixed model
dev = devs.pop()
@@ -295,6 +301,40 @@ class CudaGraphRunner:
self.dev = dev
return True
+ # -- GPU embedding table (EXL3_GPU_EMB: auto | 0 | 1) ----------------------------------------------------------------
+ # The table normally stays on the CPU (mmapped, gathered per step on the host: median 74 us, mean 345 us with ms-long page-fault
+ # outliers inside the server). With enough free VRAM after load it is copied to the device once and the gather runs inside the
+ # captured graph from a static id buffer; auto = only when free VRAM > table + EXL3_GPU_EMB_MARGIN_MB (default 2048), so the
+ # max-context configurations that need the memory keep the CPU table. The table only pays off for the lag-1 pipeline, so with
+ # EXL3_GPU_EMB unset it is built only when EXL3_LAG1=1: an unset switch leaves load-time VRAM exactly as in 1.8.2.
+ def _gemb_setup(self, emb, ids):
+ self._gemb = False
+ mode = os.environ.get("EXL3_GPU_EMB", "auto" if os.environ.get("EXL3_LAG1", "0") == "1" else "0")
+ if mode == "0" or emb.embedding is None or emb.normalize or emb.multiplier != 1.0:
+ return
+ w = emb.embedding.weight
+ if w.device.type != "cpu" or w.dtype not in (torch.half, torch.bfloat16):
+ return
+ need = w.numel() * w.element_size()
+ free, _ = torch.cuda.mem_get_info(self.dev)
+ margin = int(os.environ.get("EXL3_GPU_EMB_MARGIN_MB", "2048")) << 20
+ if mode == "auto" and free < need + margin:
+ return
+ probe = ids.detach().cpu().reshape(-1)[:4].reshape(1, -1).clone()
+ ref = emb.forward(probe, {})
+ wg = w.detach().to(self.dev)
+ got = wg.index_select(0, probe.to(self.dev).reshape(-1)).view(1, -1, wg.shape[1]).to(ref.dtype)
+ if got.shape != ref.shape or not torch.equal(got.cpu(), ref):
+ del wg
+ return
+ self._gemb = wg
+ self._gemb_dtype = ref.dtype
+
+ def _gemb_gather(self, e):
+ """x_in <- table[ids] (device ops: eager for warmup, captured for the graph)."""
+ w = self._gemb
+ e.x_in.copy_(w.index_select(0, e.ids.view(-1)).view(e.x_in.shape))
+
def _decline(self, ids, params):
"""None when this call may be graphed, else a short reason."""
if (ids.dim() != 2 or not 1 <= ids.shape[0] <= CUDA_GRAPH_MAX_B or ids.shape[1] > CUDA_GRAPH_MAX_Q
@@ -315,7 +355,7 @@ class CudaGraphRunner:
if kvwin.ANY_ACTIVE and kvwin.any_cold(params):
return "kvwin_cold" # the cold ring fill is a host step: eager this step, graph again from the next one
rs = params.get("recurrent_states")
- if self.has_gdn or self.has_conv or self.has_mamba or self.has_swa:
+ if self.has_gdn or self.has_conv or self.has_mamba or self.has_swa or self.has_ring:
slots = params.get("recurrent_slots")
nb = ids.shape[0] if CUDA_GRAPH_MULTI else 1 # one recurrent state / slot per job
if (not rs or len(rs) != nb or any(getattr(r, "exported", False) for r in rs[:nb])
@@ -350,14 +390,20 @@ class CudaGraphRunner:
# Embedding stays eager, exactly as forward_ls would run it
emb, inst0, _ = fm[0]
params["layer_instance"] = inst0
- x = emb.prepare_for_device(ids, params)
- x = emb.forward(x, params)
+ if getattr(self, "_gemb", None) is None:
+ self._gemb_setup(emb, ids)
+ use_gemb = self._gemb is not False and ids.dim() == 2 and ids.dtype == torch.long
+ if use_gemb:
+ x = torch.empty((*ids.shape, emb.hidden_size), dtype = self._gemb_dtype, device = "meta") # shape/dtype stand-in (key, buffers)
+ else:
+ x = emb.prepare_for_device(ids, params)
+ x = emb.forward(x, params)
tail = fm[1:]
key = self._key(x, params)
if key in self.disabled:
self.stats["declines"]["disabled_key"] += 1
- return self._run_tail(tail, x, params)
+ return self._run_tail(tail, self._real_x(emb, ids, params, x), params)
cache = params["cache"]
e = self.entries.get(key)
@@ -371,24 +417,26 @@ class CudaGraphRunner:
self.entries.move_to_end(key)
dev = self.dev
- self._load(e, x, params)
+ self._load(e, x, params, ids if use_gemb else None)
if e.graph is None:
if e.warm < CUDA_GRAPH_WARMUPS:
e.warm += 1
self.stats["warmups"] += 1
# real eager call through the same static buffers; output is the step's result
p = dict(e.params)
+ if use_gemb:
+ self._gemb_gather(e)
y = self._run_tail(tail, e.x_in, p)
if "export_states" in p:
params["export_states"] = p["export_states"]
return y
t_cap = time.perf_counter()
- ok = self._capture(key, e, tail, x, params)
+ ok = self._capture(key, e, tail, x, params, use_gemb)
if CUDA_GRAPH_LOG_CAPTURES: # EXL3_CUDA_GRAPH_LOG_CAPTURES=1: one line per capture, with the time the decode of every job waited
print(f"[cudagraph] capture {time.perf_counter() - t_cap:.2f} s key={key[1:5]} captures={self.stats['captures']} "
f"evictions={self.stats.get('evictions', 0)} entries={len(self.entries)}", flush = True)
if not ok:
- return self._run_tail(tail, x, params) # FALLBACK=eager decline
+ return self._run_tail(tail, self._real_x(emb, ids, params, x), params) # FALLBACK=eager decline
try:
with torch.cuda.device(dev):
if _DIAG:
@@ -416,6 +464,12 @@ class CudaGraphRunner:
# -- internals -----------------------------------------------------------------------------
+ @staticmethod
+ def _real_x(emb, ids, params, x):
+ if x.device.type != "meta":
+ return x
+ return emb.forward(emb.prepare_for_device(ids, params), params)
+
@staticmethod
def _run_tail(tail, x, p):
# Same loop as Model.forward_ls minus the embedding (declines guarantee no last_tokens_only /
@@ -441,7 +495,7 @@ class CudaGraphRunner:
# per-job page counts feed only the MLA decode kernel's KV split (mla_attn.py); MLAttention models
# never get here (_check_model), and with B jobs they would recapture whenever one job crosses 16 pages
None if CUDA_GRAPH_MULTI else (tuple(pages) if pages is not None else None),
- (self.has_gdn, self.has_mamba), tuple(sorted(exl)) if exl else None, tuple(sorted(exn)) if exn else None,
+ (self.has_gdn, self.has_mamba, self.has_ring), tuple(sorted(exl)) if exl else None, tuple(sorted(exn)) if exn else None,
tuple(int(s) for s in params["recurrent_slots"].tolist()) if self.has_conv else None, # every job's conv slot is baked in
tuple(r.slot for r in params["recurrent_states"]) if self.has_swa else None, # per-slot ring block table is baked in
)
@@ -463,13 +517,14 @@ class CudaGraphRunner:
e.slots = e.slots_src = e.exports = e.swa_cs = e.swa_host = None
with torch.cuda.device(dev):
e.x_in = torch.empty(x.shape, dtype = x.dtype, device = dev)
+ e.ids = torch.zeros(x.shape[:2], dtype = torch.long, device = dev)
e.bt = torch.zeros(bt.shape, dtype = bt.dtype, device = dev)
e.cs = torch.zeros(cs.shape, dtype = cs.dtype, device = dev)
e.pos = None if (pos is None or pos is cs) else torch.zeros(pos.shape, dtype = pos.dtype, device = dev)
if self.has_swa:
e.swa_cs = torch.zeros(x.shape[0], dtype = torch.int32, device = dev)
e.swa_host = torch.zeros(x.shape[0], dtype = torch.int32).pin_memory()
- if self.has_gdn or self.has_mamba:
+ if self.has_gdn or self.has_mamba or self.has_ring:
# Fixed-address slot buffer refreshed only when the live slot
# tensor object changes (stable across steps for one job, so
# the capture never bakes a per-step upload address).
@@ -488,7 +543,7 @@ class CudaGraphRunner:
self.entries[key] = e
return e
- def _load(self, e, x, params):
+ def _load(self, e, x, params, gids = None):
"""Per-step values into the static buffers (stream-ordered on the current stream)."""
# Multi-job (EXL3_CUDA_GRAPH_MULTI) per-job state, all either keyed or copied here, nothing else is read
# inside the capture: job order / join / leave -> row order of x, block table, cache_seqlens, positions
@@ -498,7 +553,10 @@ class CudaGraphRunner:
# replay and by the generator; state tensors are cache-owned with fixed pointers (_cache_fp), the slot
# ids select the row inside them; BC split config derives from the (keyed) table width, not from the
# cache lengths; per-job sampling state never enters the forward.
- e.x_in.copy_(x, non_blocking = True)
+ if gids is not None:
+ e.ids.copy_(gids, non_blocking = gids.is_pinned())
+ else:
+ e.x_in.copy_(x, non_blocking = True)
e.bt.copy_(params["block_table"], non_blocking = True)
e.cs.copy_(params["cache_seqlens"], non_blocking = True)
if e.pos is not None:
@@ -519,7 +577,7 @@ class CudaGraphRunner:
e.slots.copy_(get_for_device(params, "recurrent_slots", self.dev))
e.slots_src = live
- def _capture(self, key, e, tail, x, params) -> bool:
+ def _capture(self, key, e, tail, x, params, use_gemb = False) -> bool:
dev = self.dev
for d in range(torch.cuda.device_count()):
if torch.cuda.memory_allocated(d) > 0:
@@ -532,6 +590,8 @@ class CudaGraphRunner:
capture_error_mode = "thread_local"):
assert torch.cuda.is_current_stream_capturing()
pc = dict(e.params)
+ if use_gemb:
+ self._gemb_gather(e)
out = self._run_tail(tail, e.x_in, pc)
except Exception as ex:
self._drop(key)
diff --git a/exllamav3/model/model.py b/exllamav3/model/model.py
index 9de6073..a34ec29 100644
--- a/exllamav3/model/model.py
+++ b/exllamav3/model/model.py
@@ -275,6 +275,73 @@ class Model(Model_TPMixin, Model_LSMixin):
return y
+ def lag_table(self):
+ """Device copy of the token embedding table for the lag-1 pipeline's eager path (None: not possible for this model)."""
+ t = self.__dict__.get("_lag_tbl", 0)
+ if t != 0:
+ return t
+ self._lag_tbl = None
+ try:
+ from ..modules import Embedding, NGramEmbedding
+ if self.loaded_tp or not torch.cuda.is_available() or self._get_prefetch_layers or getattr(self.config, "moe_cpu_hosts", None):
+ return None
+ if any(type(m).__name__ in ("PLE", "PerLayerEmbedding") or isinstance(m, NGramEmbedding) for m in self.modules):
+ return None
+ emb, inst0, _ = self.fwd_modules[0]
+ if not isinstance(emb, Embedding) or emb.embedding is None or emb.normalize or emb.multiplier != 1.0:
+ return None
+ w = emb.embedding.weight
+ if w.dtype not in (torch.half, torch.bfloat16):
+ return None
+ dev = self.fwd_modules[1][0].device
+ if dev is None or torch.device(dev).type != "cuda":
+ return None
+ need = w.numel() * w.element_size() if w.device.type == "cpu" else 0
+ free, _ = torch.cuda.mem_get_info(dev)
+ if free < need + (int(os.environ.get("EXL3_GPU_EMB_MARGIN_MB", "1536")) << 20):
+ return None
+ probe = torch.arange(0, 8, dtype = torch.long).reshape(1, -1)
+ ref = emb.forward(probe, {"layer_instance": inst0})
+ wg = w.detach() if w.device.type == "cuda" else w.detach().to(dev)
+ got = wg.index_select(0, probe.to(wg.device).reshape(-1)).view(1, -1, wg.shape[1]).to(ref.dtype)
+ if got.shape != ref.shape or not torch.equal(got.cpu(), ref.cpu()):
+ return None
+ self._lag_tbl = (wg, ref.dtype)
+ except Exception as ex:
+ print(f"[lag1] no device embedding table: {ex}", flush = True)
+ self._lag_tbl = None
+ return self._lag_tbl
+
+
+ @torch.inference_mode
+ def forward_dev(self, input_ids: torch.Tensor, params: dict):
+ """forward() for a decode step whose ids are a device tensor (lag-1 pipeline). CUDA with the whole-forward graph: only the
+ graph can take them (its GPU embedding table), a decline returns None. Otherwise the eager layers run from a device-side
+ embedding gather (lag_table). Same arithmetic as forward(): the table rows are the rows Embedding.forward reads."""
+ if _cuda_graph.CUDA_GRAPH_ENABLED and not torch.version.hip:
+ if self.loaded_tp or not torch.cuda.is_available():
+ return None
+ x = self.prepare_inputs(input_ids, params)
+ if params.get("recurrent_states") is not None and "recurrent_slots" not in params:
+ prepare_for_recurrence(input_ids, params, self)
+ y = _cuda_graph.maybe_forward(self, x, params)
+ if y is not None:
+ advance_recurrent_states(input_ids, params, self)
+ return y
+ tbl = self.lag_table()
+ if tbl is None:
+ return None
+ x = self.prepare_inputs(input_ids, params)
+ if params.get("recurrent_states") is not None and "recurrent_slots" not in params:
+ prepare_for_recurrence(input_ids, params, self)
+ wg, dt = tbl
+ params["input_ids"] = input_ids
+ x = wg.index_select(0, input_ids.reshape(-1)).view(*input_ids.shape, wg.shape[1]).to(dt)
+ y = self.forward_ls(x, params, skip_first = True)
+ advance_recurrent_states(input_ids, params, self)
+ return y
+
+
def unload(self):
_cuda_graph.purge(self)
for module in self.modules:
diff --git a/exllamav3/model/model_ls.py b/exllamav3/model/model_ls.py
index 471e8ed..c166fda 100644
--- a/exllamav3/model/model_ls.py
+++ b/exllamav3/model/model_ls.py
@@ -335,12 +335,13 @@ class Model_LSMixin(ABC):
self,
x: torch.Tensor,
params: dict,
+ skip_first: bool = False,
):
for h in getattr(self.config, "moe_cpu_hosts", {}).values():
h.begin_pass()
self._name_embedding_target(x, params)
span = _FWD_SPAN and x.dim() >= 3 and x.shape[1] <= 8 # (batch, rows, ..): decode/verify only, not prefill chunks
- for module, instance, idx in self.fwd_modules:
+ for module, instance, idx in (self.fwd_modules[1:] if skip_first else self.fwd_modules):
params["layer_instance"] = instance
if module.caps.get("logits_output"):
# EXL3_PF_SKIP: skip_logits -- the caller discards the logits (the MTP prompt
diff --git a/exllamav3/modules/attention_fn/bc_attn.py b/exllamav3/modules/attention_fn/bc_attn.py
index 00a7a45..9a15f99 100644
--- a/exllamav3/modules/attention_fn/bc_attn.py
+++ b/exllamav3/modules/attention_fn/bc_attn.py
@@ -34,6 +34,11 @@ and gathered split kernels live in qsa_triton.py. A module with an indexer that
declines the BC path outright: an unarmed graph would let the planes go stale under dense decode
and poison later sparse selection.
+KVWIN (cache/kvwin.py, CUDA): a layer with a fp16 sink+window ring runs it in the graph too -- the ring writer (which also derives the
+pool pass's sequence lengths, cache_seqlens - W) after the cache append, the pool splits over [S, q-W] (KEY_LO = S), the ring pass as
+one more flash-decoding partial and the combine over one partial more. The per-job ring slots are patched like the other pointers.
+EXL3_BC_KVWIN=0 sends such layers back to the Python path; ROCm keeps declining them.
+
Enabled by default; EXL3_BC_ATTN=0 disables the path. Unsupported module/cache configurations
fall back to the dispatch path by design (build_bc_attn returns None); unexpected failures
while building the path raise.
@@ -55,6 +60,11 @@ MAX_R = MAX_BSZ * MAX_QLEN
_kernel_cache = {}
_sm_count = {}
+MAX_BSZ_KW = 8 # BC_Attention.MAX_BSZ
+_RING_BN = int(os.environ.get("EXL3_BC_RING_BN", "256"))
+_RING_WARPS = int(os.environ.get("EXL3_BC_RING_WARPS", "8"))
+_RING_STAGES = int(os.environ.get("EXL3_BC_RING_STAGES", "1"))
+_kvwin_bc = os.environ.get("EXL3_BC_KVWIN", "1") != "0" # KVWIN ring inside the BC_Attention graph
def _is_pow2(n: int) -> bool:
@@ -118,7 +128,7 @@ class BCAttn:
return w
def __init__(self, module, cache_k, cache_v, k_scales = None, v_scales = None,
- k_bits = 0, v_bits = 0, qsa_layer = None):
+ k_bits = 0, v_bits = 0, qsa_layer = None, kvwin_state = None):
self.module = module
self.device = torch.device(module.device)
self.head_dim = module.head_dim
@@ -258,7 +268,14 @@ class BCAttn:
raw_plane = qsa_layer.raw_k.view(-1, idx.head_dim),
pool_plane = qsa_layer.pooled.view(-1, idx.head_dim),
)
+ # KVWIN (cache/kvwin.py): the ring writer and the ring partial run inside the graph; the pool pass attends [S, q-W].
+ # Only the plain causal quantized decode shape (the one the ring serves) takes this path, see step()
+ self.kw = kvwin_state
+ if self.kw is not None:
+ c = self.kw.cfg
+ self.bc.set_kvwin(self.kw.ov_k, self.kw.ov_v, c.S, c.W, c.Rc, c.R)
self.slot_widths = {}
+ self.kw_bad = set()
def _configure(self, bsz: int, q_len: int, causal: bool, regime: int):
import triton
@@ -287,6 +304,11 @@ class BCAttn:
decode_row_layout,
)
+ kw = self.kw
+ if kw is not None and not (ATTN16 and causal and regime == 0 and self.k_bits > 0 and self.v_bits > 0):
+ return False # the ring serves causal quantized decode on the 1.6 kernels only: the Python path runs it
+ key_lo = kw.cfg.S if kw is not None else 0
+
dev = self.device
hd = self.head_dim
hd_pad = triton.next_power_of_2(hd) # kernel tile width (zero-padded past hd)
@@ -331,7 +353,7 @@ class BCAttn:
page_size = PAGE_SIZE, head_dim = hd, HD_PAD = hd_pad, scale = float(self.sm_scale),
CAUSAL = bool(causal), WINDOW_LEFT = window_left, WINDOW_RIGHT = window_right,
SOFTCAP = float(self.softcap or 0.0), FINAL = False, HAS_SINKS = False,
- BLOCK_ROWS = block_rows, BLOCK_N = block_n, KEY_LO = 0,
+ BLOCK_ROWS = block_rows, BLOCK_N = block_n, KEY_LO = key_lo,
)
if not ATTN16:
consts |= dict(BLOCK_M = block_m, BLOCK_H = block_h)
@@ -339,7 +361,7 @@ class BCAttn:
if ATTN16 and self.quant and self.k_bits > 0 and self.v_bits > 0:
from . import qdec_cuda
qcfg = None if not qdec_cuda.GRAPH_ENABLED else qdec_cuda.make_cfg(q_len, qh, kvh, hd, self.k_bits, self.v_bits, PAGE_SIZE, causal, self.sm_scale,
- block_rows, window_left, window_right, self.softcap or 0.0, q_len)
+ block_rows, window_left, window_right, self.softcap or 0.0, q_len, key_lo)
if qcfg is not None and h_blocks != 1 and not qcfg.get("rows_kernel"):
qcfg = None
if qcfg is not None and qcfg.get("rows_kernel"):
@@ -410,8 +432,9 @@ class BCAttn:
o = g_tensor_cache.get(dev, (bsz, q_len, qh, hd), torch.half, "bca_o")
# Regime-1 slots never launch the dense split/combine; their partials are sized by the
# sparse kernels in _configure_qsa (same bucketed tags, so the footprint is the max)
- pn_o = programs * splits_cap * block_rows * hd_pad
- pn_ml = programs * splits_cap * block_rows * 2
+ ns_cap = splits_cap + (1 if kw is not None else 0) # KVWIN: the ring partial follows the pool splits
+ pn_o = programs * ns_cap * block_rows * hd_pad
+ pn_ml = programs * ns_cap * block_rows * 2
if regime == 1:
pn_o, pn_ml = self._qsa_partial_sizes(bsz * q_len)
partial_o = g_tensor_cache.get_bucketed(dev, pn_o, torch.float, "bca_po")
@@ -437,8 +460,42 @@ class BCAttn:
xp, yp,
)
+ if kw is not None:
+ from .kvwin_triton import _ov_write_kernel, _ring_split_kernel
+ cfg = kw.cfg
+ sig_w = {
+ "k": "*fp16", "v": "*fp16", "ov_k": "*fp16", "ov_v": "*fp16", "slots": "*i32", "seqlens": "*i32",
+ "pool_len": "*i32", "q_len": "i32", "S": "i32", "Rc": "i32", "R": "i32", "W": "i32",
+ } | {n: "constexpr" for n in ("n_kv_heads", "head_dim", "HD_PAD", "WRITE_POOL_LEN")}
+ consts_w = dict(n_kv_heads = kvh, head_dim = hd, HD_PAD = hd_pad, WRITE_POOL_LEN = True)
+ k_ovw = _compile_kernel(dev, _ov_write_kernel, sig_w, consts_w, 1, 1)
+ # the JIT path specializes pointers and ints divisible by 16 (vectorized ring loads): the AOT kernel declares them too,
+ # every one is a whole allocation (statics, the ring tensors) or a configured constant
+ d16 = lambda n: ":16" if n % 16 == 0 else ""
+ sig_r = {
+ "q": "*fp16:16", "ov_k": "*fp16:16", "ov_v": "*fp16:16", "slots": "*i32", "cache_seqlens": "*i32",
+ "h32": "*fp16:16", "partial_o": "*fp32:16", "partial_ml": "*fp32:16",
+ "ns_total": "i32", "sinks_n": "i32" + d16(cfg.S), "win": "i32" + d16(cfg.W), "Rc": "i32" + d16(cfg.Rc),
+ "R": "i32" + d16(cfg.R),
+ } | {n: "constexpr" for n in (
+ "q_len", "n_q_heads", "n_kv_heads", "head_dim", "HD_PAD", "scale", "ROT_V", "LAYOUT", "BLOCK_M", "BLOCK_H",
+ "BLOCK_ROWS", "BLOCK_N", "RPP")}
+ consts_r = dict(q_len = q_len, n_q_heads = qh, n_kv_heads = kvh, head_dim = hd, HD_PAD = hd_pad,
+ scale = float(self.sm_scale), ROT_V = self.v_bits > 0, LAYOUT = 0, BLOCK_M = 1, BLOCK_H = 1,
+ BLOCK_ROWS = block_rows, BLOCK_N = _RING_BN, RPP = 0)
+ # one-tile ring pass with 8 warps when the K tile (BLOCK_N x head_dim fp16) fits comfortably in shared memory; wide heads
+ # (hd 256) or a device that refuses the tile fall back to the 64-key / 4-warp pass
+ bn = min(_RING_BN, max(16, 32768 // hd_pad))
+ try:
+ k_ring = _compile_kernel(dev, _ring_split_kernel, sig_r, consts_r | dict(BLOCK_N = bn), _RING_WARPS, _RING_STAGES)
+ except RuntimeError:
+ k_ring = _compile_kernel(dev, _ring_split_kernel, sig_r, consts_r | dict(BLOCK_N = 64), 4, 1)
+ pool_len = g_tensor_cache.get(dev, (MAX_BSZ_KW,), torch.int32, "bca_poollen")
+ self.bc.configure_slot_kvwin(bsz, q_len, regime, pool_len, k_ovw, k_ring, cfg.S + min(q_len, cfg.Rc))
+
if self.qsa:
self._configure_qsa(bsz, q_len, regime)
+ return True
# ---- QSA -----------------------------------------------------------------------------------
@@ -609,9 +666,14 @@ class BCAttn:
inv_freq: torch.Tensor | None,
causal: bool = True,
host_seqlens: torch.Tensor | None = None,
+ kvwin_ctx = None,
) -> torch.Tensor | None:
bsz, q_len, _ = x.shape
+ # KVWIN: a call without job states (no ring context) writes the pool alone, as the Python path does
+ if self.kw is not None and (kvwin_ctx is None or kvwin_ctx.state is not self.kw or not causal):
+ return None
+
# QSA regime: dense below the sparse threshold (top-k cannot exclude anything there, so
# dense attention is exact), gathered sparse above it. Sparse slots are decode-only;
# other shapes fall back to the eager path, which maintains the planes identically
@@ -635,12 +697,16 @@ class BCAttn:
# position source, block-table pointer/width, split configuration -- is a runtime
# argument patched into the graph
skey = (tuple(inv_freq.shape) if inv_freq is not None else None, causal)
+ if (bsz, q_len, regime) in self.kw_bad:
+ return None
if self.slot_widths.get((bsz, q_len, regime), ...) != skey:
- self._configure(bsz, q_len, causal, regime)
+ if self._configure(bsz, q_len, causal, regime) is False:
+ self.kw_bad.add((bsz, q_len, regime))
+ return None
self.slot_widths[(bsz, q_len, regime)] = skey
y = torch.empty((bsz, q_len, self.hidden_size), dtype = self.o_dtype, device = x.device)
self.bc.run(bsz, q_len, x, y, cache_seqlens, block_table, position, positions,
- position_ids, inv_freq, regime, t_total)
+ position_ids, inv_freq, regime, t_total, kvwin_ctx.slots if self.kw is not None else None)
return y
@@ -753,8 +819,11 @@ def build_bc_attn(module, layer):
from ...cache.qsa import QSAPlanes
m = module
- if getattr(layer, "kvwin", None) is not None:
- # KVWIN: the graph writes the pool inside the captured block and would leave the fp16 ring stale
+ kw = getattr(layer, "kvwin", None)
+ if kw is not None and not (kw.active and _kvwin_bc and not torch.version.hip and isinstance(layer, CacheLayer_quant) and
+ getattr(m, "qsa_indexer", None) is None):
+ # KVWIN without the in-graph ring (EXL3_BC_KVWIN=0, or an inactive ring): the graph would write the pool and leave
+ # the fp16 ring stale
_trace_build(m, None, "attn")
return None
if getattr(layer, "tq", False):
@@ -794,7 +863,7 @@ def build_bc_attn(module, layer):
return None
if isinstance(layer, CacheLayer_quant):
bca = BCAttn(m, layer.qk, layer.qv, layer.sk, layer.sv, layer.k_bits, layer.v_bits,
- qsa_layer = layer if qsa_idx is not None else None)
+ qsa_layer = layer if qsa_idx is not None else None, kvwin_state = kw)
else:
bca = BCAttn(m, layer.k, layer.v,
qsa_layer = layer if qsa_idx is not None else None)
diff --git a/exllamav3/modules/attention_fn/bc_mla.py b/exllamav3/modules/attention_fn/bc_mla.py
index e8e0b3b..99bb697 100644
--- a/exllamav3/modules/attention_fn/bc_mla.py
+++ b/exllamav3/modules/attention_fn/bc_mla.py
@@ -53,10 +53,19 @@ class BCMLA:
self.w_kv = m.kv_a_proj_with_mqa.out_features
self.quant = isinstance(layer, CacheLayer_MLA_quant)
+ self.tq = bool(getattr(layer, "tq", False))
+ self.tq_consts = None
if self.quant:
self.cache_ckv, self.cache_scales, self.cache_kpe, self.k_bits = layer.get_qc()
from .triton_paged import _get_h32
- h32 = _get_h32(self.device)
+ if self.tq:
+ # TurboQuant: the h32 slot of the kernels carries the fp32 codebook (C++ switches on its dtype); the append kernel's
+ # constants (rotation, codebook, midpoints) ride in the stmp slot
+ st = layer.state
+ h32 = st.cbk
+ self.tq_consts = torch.cat([st.rot_t32.reshape(-1), st.cbk, st.midk]).contiguous()
+ else:
+ h32 = _get_h32(self.device)
else:
self.cache_ckv, self.cache_kpe = layer.k, layer.v
self.cache_scales, self.k_bits = None, 0
@@ -70,6 +79,8 @@ class BCMLA:
# The staging kernel reads the norm weight as fp16; checkpoints usually store it bf16
# (fp16-exact at weight magnitudes). The ext object keeps the converted copy alive
kv_norm_w = m.kv_a_layernorm.weight.data.half().contiguous()
+ if getattr(layer, "tq", False):
+ kv_norm_w = torch.ones_like(kv_norm_w) # gamma is folded into the up-projections (mla_attn.load_local)
# NoPE models (GLM5.3: qk_rope_head_dim 0) have no rope instance; the rope stages are
# compiled out of the graph and the ext object gets inert placeholders
@@ -203,7 +214,16 @@ class BCMLA:
BLOCK_M = absorb_bm, BLOCK_N = 128),
4, 2)
- if self.quant:
+ if self.tq:
+ from .mla_triton import _mla_tq_scatter_kernel
+ k_append = _compile_kernel(dev, _mla_tq_scatter_kernel,
+ {"ckv_new": "*fp16", "consts": "*fp32", "kpe_new": "*fp16", "qk": "*i32",
+ "sk": "*fp16", "kpe_cache": "*fp16", "block_table": "*i32",
+ "cache_seqlens": "*i32", "num_pages_per_seq": "i32", "append_len": "i32"}
+ | {n: "constexpr" for n in ("page_size", "BITS", "D_c", "D_r", "BK")},
+ dict(page_size = PAGE_SIZE, BITS = self.k_bits, D_c = D_c, D_r = D_r, BK = 16),
+ 4, 2)
+ elif self.quant:
groups = D_c // 32
w_tot = groups * self.k_bits
k_append = _compile_kernel(dev, _mla_kv_quant_scatter_kernel,
@@ -225,10 +245,10 @@ class BCMLA:
# Same tuning as the dispatch wrapper (mla_attn_triton_decode)
block_m = triton.next_power_of_2(q_len)
- block_h = max(16 // block_m, 1)
+ block_h = max((32 if self.tq else 16) // block_m, 1)
block_h = min(block_h, max(1, triton.next_power_of_2(H)))
block_rows = block_m * block_h
- block_n = 64 if self.quant else (32 if D_c <= 512 else 16)
+ block_n = 32 if self.tq else (64 if self.quant else (32 if D_c <= 512 else 16))
n_warps = 8 if self.quant else 4
n_stages = 1 if self.quant else 3
h_blocks = triton.cdiv(H, block_h)
@@ -243,15 +263,15 @@ class BCMLA:
cache_t = "*i32" if self.quant else "*fp16"
k_split = _compile_kernel(dev, _mla_decode_split_kernel,
{"q_lat": "*fp16", "q_pe": "*fp16", "ckv_cache": cache_t, "kpe_cache": "*fp16",
- "ckv_scales": "*fp16", "h32": "*fp16", "block_table": "*i32",
+ "ckv_scales": "*fp16", "h32": "*fp32" if self.tq else "*fp16", "block_table": "*i32",
"cache_seqlens": "*i32", "out": "*fp16", "partial_o": "*fp32",
"partial_ml": "*fp32", "split_len": "i32", "num_pages_per_seq": "i32",
"num_splits": "i32"}
| {n: "constexpr" for n in (
- "QC", "QC_TRANS", "Q_PE_TM", "bsz", "q_len", "pre_appended_len", "n_q_heads",
+ "QC", "TQ", "QC_TRANS", "Q_PE_TM", "bsz", "q_len", "pre_appended_len", "n_q_heads",
"page_size", "D_c", "D_r", "scale", "CAUSAL", "FINAL",
"BLOCK_M", "BLOCK_H", "BLOCK_ROWS", "BLOCK_N")},
- dict(QC = self.k_bits, QC_TRANS = True, Q_PE_TM = True, bsz = bsz, q_len = q_len,
+ dict(QC = self.k_bits, TQ = int(self.tq), QC_TRANS = True, Q_PE_TM = True, bsz = bsz, q_len = q_len,
pre_appended_len = q_len, n_q_heads = H, page_size = PAGE_SIZE, D_c = D_c,
D_r = D_r, scale = float(self.sm_scale), CAUSAL = True, FINAL = False,
BLOCK_M = block_m, BLOCK_H = block_h, BLOCK_ROWS = block_rows,
@@ -259,11 +279,11 @@ class BCMLA:
n_warps, n_stages)
k_combine = _compile_kernel(dev, _mla_decode_combine_kernel,
- {"partial_o": "*fp32", "partial_ml": "*fp32", "out": "*fp16", "h32": "*fp16",
+ {"partial_o": "*fp32", "partial_ml": "*fp32", "out": "*fp16", "h32": "*fp32" if self.tq else "*fp16",
"num_splits": "i32"}
| {n: "constexpr" for n in (
- "QC", "bsz", "q_len", "n_q_heads", "D_c", "BLOCK_M", "BLOCK_H", "BLOCK_ROWS")},
- dict(QC = self.k_bits, bsz = bsz, q_len = q_len, n_q_heads = H, D_c = D_c,
+ "QC", "TQ", "bsz", "q_len", "n_q_heads", "D_c", "BLOCK_M", "BLOCK_H", "BLOCK_ROWS")},
+ dict(QC = self.k_bits, TQ = int(self.tq), bsz = bsz, q_len = q_len, n_q_heads = H, D_c = D_c,
BLOCK_M = block_m, BLOCK_H = block_h, BLOCK_ROWS = block_rows),
4, 1)
@@ -294,7 +314,10 @@ class BCMLA:
o = sbuf("bcm_o", R, H * D_v)
partial_o = sbuf("bcm_po", programs * splits_cap * block_rows * D_c, dtype = torch.float)
partial_ml = sbuf("bcm_ml", programs * splits_cap * block_rows * 2, dtype = torch.float)
- if self.quant:
+ if self.tq:
+ qtmp = sbuf("bcm_qtmp_tq", 1, dtype = torch.int) # unused by the TurboQuant append (C++ skips the CUDA quantizer)
+ stmp = self.tq_consts
+ elif self.quant:
qtmp = sbuf("bcm_qtmp", R, D_c // 32 * self.k_bits, dtype = torch.int)
stmp = sbuf("bcm_stmp", R, D_c // 32)
else:
@@ -460,11 +483,11 @@ class BCMLA:
"k_len": "i32", "win_len": "i32", "pool_len": "i32",
"num_pages_per_row": "i32", "q_pos0": "i32", "win_floor": "i32",
"ring_beg": "i32", "slot_ids": "i32", "ring_stride": "i32",
- "pool_s": "*fp16:16", "h32": "*fp16:16",
+ "pool_s": "*fp16:16", "h32": "*fp32:16" if self.tq else "*fp16:16",
} | {n: "constexpr" for n in (
"H", "page_size", "D_c", "D_c_pad", "D_r", "K_pad", "compress_rate", "scale",
"HAS_WINDOW", "DENSE_POOL", "BLOCK_H", "BLOCK_N", "BLOCK_W", "SEQ",
- "MULTIROW", "DEBUG_BOUNDS", "DEBUG_PAGES", "Q_SPLIT", "OUT_LATENT", "QC")}
+ "MULTIROW", "DEBUG_BOUNDS", "DEBUG_PAGES", "Q_SPLIT", "OUT_LATENT", "QC", "TQ")}
consts_s = dict(
H = H, page_size = PAGE_SIZE, D_c = D_c,
D_c_pad = 1 << (D_c - 1).bit_length(), D_r = D_r, K_pad = kp,
@@ -476,7 +499,7 @@ class BCMLA:
SEQ = q_len, MULTIROW = 1 if bsz > 1 else 0,
DEBUG_BOUNDS = 0, DEBUG_PAGES = 0,
Q_SPLIT = 1, OUT_LATENT = 1,
- QC = self.k_bits if self.quant else 0,
+ QC = self.k_bits if self.quant else 0, TQ = int(self.tq),
)
k_dsa_split = _compile_kernel(dev, _dsa_attn_split_kernel, sig_s, consts_s, 4, 2)
@@ -484,15 +507,15 @@ class BCMLA:
"ws_ml": "*fp32:16", "ws_acc": "*fp32:16", "sinks": "*fp32:16",
"derot_inv_freq": "*fp32:16",
"out": "*fp16:16", "q_pos0": "i32", "R": "i32", "n_splits": "i32",
- "h32": "*fp16:16",
+ "h32": "*fp32:16" if self.tq else "*fp16:16",
} | {n: "constexpr" for n in (
"H", "D_c", "D_r", "HAS_SINKS", "DEROTATE", "HPG", "BLOCK_H", "BLOCK_D",
- "SEQ", "MULTIROW", "OUT_LATENT", "QC")}
+ "SEQ", "MULTIROW", "OUT_LATENT", "QC", "TQ")}
consts_c = dict(
H = H, D_c = D_c, D_r = D_r, HAS_SINKS = False, DEROTATE = False,
HPG = 0, BLOCK_H = BLOCK_H, BLOCK_D = 128,
SEQ = 1, MULTIROW = 0, OUT_LATENT = 1,
- QC = self.k_bits if self.quant else 0,
+ QC = self.k_bits if self.quant else 0, TQ = int(self.tq),
)
k_dsa_combine = _compile_kernel(dev, _dsa_attn_combine_kernel, sig_c, consts_c, 4, 2)
diff --git a/exllamav3/modules/attention_fn/cu/qdec.cu b/exllamav3/modules/attention_fn/cu/qdec.cu
index 7a8a0f3..dc006cd 100644
--- a/exllamav3/modules/attention_fn/cu/qdec.cu
+++ b/exllamav3/modules/attention_fn/cu/qdec.cu
@@ -117,7 +117,7 @@ template<int B, int IL, int RH> __device__ __forceinline__ u32 vdq(const u32* wA
return hfma2(x, sc, hmul2(sc, 0x38003800u));
}
#endif
-extern "C" __global__ void __launch_bounds__(NTHREADS)
+extern "C" __global__ void __launch_bounds__(NTHREADS, 1)
qdec_split(
const u16* __restrict__ q, const u32* __restrict__ k_cache, const u32* __restrict__ v_cache,
const int* __restrict__ block_table, const int* __restrict__ cache_seqlens, u16* out_unused,
@@ -128,9 +128,16 @@ qdec_split(
{
__shared__ __align__(16) u32 cbk_s[TQ ? (1 << (2 * KB)) : 1];
__shared__ __align__(16) u32 cbv_s[TQ ? (1 << (2 * VB)) : 1];
+ __shared__ __align__(16) u16 hraw[TQ ? 8 : 1024]; // H32 rotation matrix of the q prologue (fp16 bits, staged by cp.async)
extern __shared__ __align__(16) unsigned char smem[];
u16* Qs = (u16*)smem;
- unsigned char* ring = smem + ((NT * 8 * QSTR * 2 + 15) / 16) * 16;
+#if TQ
+ constexpr int QRAW_B = 0;
+#else
+ constexpr int QRAW_B = ((NT * 8 * HD * 2 + 15) / 16) * 16; // the q rows as loaded (fp16), rotated into Qs by the prologue
+#endif
+ u16* qraw = (u16*)(smem + ((NT * 8 * QSTR * 2 + 15) / 16) * 16);
+ unsigned char* ring = smem + ((NT * 8 * QSTR * 2 + 15) / 16) * 16 + QRAW_B;
const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
const int g = lane >> 2, t = lane & 3;
@@ -142,40 +149,23 @@ qdec_split(
const int n_start = split * split_len;
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)
- for (int i = tid; i < (1 << (2 * KB)); i += NTHREADS) cbk_s[i] = (u32)cbk[i & ((1 << KB) - 1)] | ((u32)cbk[i >> KB] << 16);
- for (int i = tid; i < (1 << (2 * VB)); i += NTHREADS) cbv_s[i] = (u32)cbv[i & ((1 << VB) - 1)] | ((u32)cbv[i >> VB] << 16);
- 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;
+#if !TQ
+ // The q rows and the H32 matrix are requested first (one group), then the first K/V slabs: the prologue below waits for the
+ // q group only, and its latency-bound rotation overlaps the K/V fetch.
+ for (int c = tid; c < 1024 / 8; c += NTHREADS) cp16(hraw + c * 8, h32 + c * 8, true);
+ if ((((size_t)q) & 15) == 0) {
+ for (int c = tid; c < ROWS * (HD / 8); c += NTHREADS) {
+ int r = c / (HD / 8), d8 = c % (HD / 8);
+ cp16(qraw + r * HD + d8 * 8, q + ((size_t)((batch * QLEN + r % QLEN) * NQH + kvh * GROUP + r / QLEN)) * HD + d8 * 8, true);
}
- __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();
- for (int idx = tid; idx < NT * 8 * HD; idx += NTHREADS) {
- int r = idx / HD, d = idx % HD, gi = d >> 5, c = d & 31;
- float acc = 0.f;
- if (r < ROWS) {
- int row_q = r % QLEN, hl = r / QLEN;
- const u16* qp = q + ((size_t)((batch * QLEN + row_q) * NQH + kvh * GROUP + hl)) * HD + gi * 32;
- #pragma unroll
- for (int k = 0; k < 32; k++) acc += h2f(qp[k]) * hs[k * 32 + c];
- }
- u32 hh = pack_h2(acc, 0.f) & 0xFFFFu;
-#if FASTDQ
- Qs[r * QSTR + ((d & ~15) | (d & 8) | ((d & 3) << 1) | ((d >> 2) & 1))] = (u16)hh;
-#else
- Qs[r * QSTR + d] = (u16)hh;
-#endif
+ } else { // q is a view at an odd offset: plain loads
+ for (int c = tid; c < ROWS * HD; c += NTHREADS) {
+ int r = c / HD, d = c % HD;
+ qraw[c] = q[((size_t)((batch * QLEN + r % QLEN) * NQH + kvh * GROUP + r / QLEN)) * HD + d];
}
- __syncthreads();
}
-
+ asm volatile("cp.async.commit_group;");
+#endif
float m[NT][2], l[NT][2], qabs[NT][2];
bool rvalid[NT][2];
#pragma unroll
@@ -249,6 +239,59 @@ qdec_split(
for (int s = 0; s < ST - 1; s++) fill(s, ld_phys(s));
int ph_cur = ld_phys(ST - 1);
+ // ---- q rows -> rotated (h32) fp16 in smem
+ if (TQ) { // q arrives already rotated: plain copy (K dim order permuted like below)
+ for (int i = tid; i < (1 << (2 * KB)); i += NTHREADS) cbk_s[i] = (u32)cbk[i & ((1 << KB) - 1)] | ((u32)cbk[i >> KB] << 16);
+ for (int i = tid; i < (1 << (2 * VB)); i += NTHREADS) cbv_s[i] = (u32)cbv[i & ((1 << VB) - 1)] | ((u32)cbv[i >> VB] << 16);
+ 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 {
+ asm volatile("cp.async.wait_group %0;" :: "n"(ST - 1));
+ __syncthreads();
+ // QU independent outputs per thread (NTHREADS is a multiple of 32, so they share the column c): the 32-term sums keep
+ // their order, the QU dependent chains run side by side
+ constexpr int QU = 4;
+ for (int base = tid; base < NT * 8 * HD; base += QU * NTHREADS) {
+ const u16* qp[QU];
+ float acc[QU];
+ #pragma unroll
+ for (int u = 0; u < QU; u++) {
+ int idx = base + u * NTHREADS;
+ int r = idx / HD, d = idx % HD;
+ acc[u] = 0.f;
+ qp[u] = (idx < NT * 8 * HD && r < ROWS) ? qraw + r * HD + (d >> 5) * 32 : nullptr;
+ }
+ const int c = base & 31;
+ #pragma unroll
+ for (int k = 0; k < 32; k++) {
+ const float hv = h2f(hraw[k * 32 + c]);
+ #pragma unroll
+ for (int u = 0; u < QU; u++)
+ if (qp[u]) acc[u] += h2f(qp[u][k]) * hv;
+ }
+ #pragma unroll
+ for (int u = 0; u < QU; u++) {
+ int idx = base + u * NTHREADS;
+ if (idx < NT * 8 * HD) {
+ int r = idx / HD, d = idx % HD;
+ u32 hh = pack_h2(acc[u], 0.f) & 0xFFFFu;
+#if FASTDQ
+ Qs[r * QSTR + ((d & ~15) | (d & 8) | ((d & 3) << 1) | ((d >> 2) & 1))] = (u16)hh;
+#else
+ Qs[r * QSTR + d] = (u16)hh;
+#endif
+ }
+ }
+ }
+ __syncthreads();
+ }
+
+
#if FASTDQ
const DqK dk = make_dqk<KB>(t);
const DqV dv = make_dqv<VB>(g);
diff --git a/exllamav3/modules/attention_fn/cu/qdec_rows.cu b/exllamav3/modules/attention_fn/cu/qdec_rows.cu
index f1d3eb1..77c7ee9 100644
--- a/exllamav3/modules/attention_fn/cu/qdec_rows.cu
+++ b/exllamav3/modules/attention_fn/cu/qdec_rows.cu
@@ -34,6 +34,9 @@
#define OWN ((NT + NW - 1) / NW) // row tiles owned per warp
#define SX_B (NW * NT * 32 * 16) // partial S exchange
#define PX_B (NT * 32 * 16) // P fragments (2 words) + rescale factors (2 floats) per row tile and lane
+#ifndef TQ
+#define TQ 0 // TurboQuant cache (cache/tq.py): codebook LUT dequant, ONE fp16 scale per head vector, q / output rotated outside
+#endif
// dynamic smem layout: [Sx][Px][ring: NW x ST x STAGE_B] (q lives in registers as this warp's MMA B fragments)
@@ -60,15 +63,23 @@ template<int CP> __device__ __forceinline__ void cpw(void* dst, const void* src,
#ifndef ABL
#define ABL 0
#endif
-extern "C" __global__ void __launch_bounds__(NTHREADS)
+// TurboQuant: packed raw pair (raw of the low / high half in bits 0.. / 16..) -> half2 of the codebook entries, from a pair table
+// in smem (index = raw lo | raw hi << B); the per-vector scale is folded into the scores (K) / the probabilities (V)
+template<int B> __device__ __forceinline__ u32 lut2(u32 x, const u32* cb)
+{
+ return cb[(x & ((1u << B) - 1)) | ((x >> (16 - B)) & (((1u << B) - 1) << B))];
+}
+extern "C" __global__ void __launch_bounds__(NTHREADS, 1)
qdec_split_rows(
const u16* __restrict__ q, const u32* __restrict__ k_cache, const u32* __restrict__ v_cache,
const int* __restrict__ block_table, const int* __restrict__ cache_seqlens, u16* out_unused,
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)
{
+ __shared__ __align__(16) u32 cbk_s[TQ ? (1 << (2 * KB)) : 1];
+ __shared__ __align__(16) u32 cbv_s[TQ ? (1 << (2 * VB)) : 1];
extern __shared__ __align__(16) unsigned char smem[];
float4* Sx = (float4*)smem;
uint2* Pp = (uint2*)(smem + SX_B);
@@ -87,6 +98,28 @@ qdec_split_rows(
// ---- q rows -> rotated (h32) fp16, kept as this warp's B fragments (head-dim groups warp*GW ..)
u32 qb[2 * GW][NT][2];
+#if TQ
+ { // q arrives already rotated: plain fp16 pairs, natural dim order
+ for (int i = tid; i < (1 << (2 * KB)); i += NTHREADS) cbk_s[i] = (u32)cbk[i & ((1 << KB) - 1)] | ((u32)cbk[i >> KB] << 16);
+ for (int i = tid; i < (1 << (2 * VB)); i += NTHREADS) cbv_s[i] = (u32)cbv[i & ((1 << VB) - 1)] | ((u32)cbv[i >> VB] << 16);
+ #pragma unroll
+ for (int kk = 0; kk < 2 * GW; kk++) {
+ const int d0 = (warp * 2 * GW + kk) * 16 + 2 * t;
+ #pragma unroll
+ for (int j = 0; j < NT; j++) {
+ const int r = 8 * j + g;
+ u32 w0 = 0, w1 = 0;
+ if (r < ROWS) {
+ const u16* qr = q + ((size_t)((batch * QLEN + r % QLEN) * NQH + kvh * GROUP + r / QLEN)) * HD + d0;
+ w0 = (u32)qr[0] | ((u32)qr[1] << 16);
+ w1 = (u32)qr[8] | ((u32)qr[9] << 16);
+ }
+ qb[kk][j][0] = w0; qb[kk][j][1] = w1;
+ }
+ }
+ __syncthreads(); // the codebook tables are read by every warp
+ }
+#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]);
@@ -118,6 +151,7 @@ qdec_split_rows(
}
__syncthreads();
}
+#endif
float m[OWN][2], l[OWN][2], qabs[OWN][2];
bool rvalid[OWN][2];
@@ -163,8 +197,14 @@ qdec_split_rows(
int tk = c / (VWW / VCP), pt = c % (VWW / VCP);
cpw<VCP>(vsm + tk * VSW + pt * VCP, v_cache + (row0 + tk) * (GPT * VB) + kvh * VCHW + warp * VWW + pt * VCP, n0 + tk < n_end, pol_f);
}
+#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;");
};
@@ -192,15 +232,24 @@ qdec_split_rows(
#pragma unroll
for (int gi = 0; gi < GW; gi++) {
const int gg = warp * GW + gi;
+#if !TQ
u32 sc0 = scale2<KB>(ksc[g * G + gg], ksc[g * G + gg]);
u32 sc1 = scale2<KB>(ksc[(g + 8) * G + gg], ksc[(g + 8) * G + gg]);
+#endif
#pragma unroll
for (int h = 0; h < 2; h++) {
int p0 = 16 * h + 2 * t, p1 = p0 + 8;
+#if TQ
+ u32 a0 = lut2<KB>(raw_pair<KB>(kr0 + gi * KB, p0), cbk_s);
+ u32 a1 = lut2<KB>(raw_pair<KB>(kr1 + gi * KB, p0), cbk_s);
+ u32 a2 = lut2<KB>(raw_pair<KB>(kr0 + gi * KB, p1), cbk_s);
+ u32 a3 = lut2<KB>(raw_pair<KB>(kr1 + gi * KB, p1), cbk_s);
+#else
u32 a0 = dequant2<KB>(raw_pair<KB>(kr0 + gi * KB, p0), sc0);
u32 a1 = dequant2<KB>(raw_pair<KB>(kr1 + gi * KB, p0), sc1);
u32 a2 = dequant2<KB>(raw_pair<KB>(kr0 + gi * KB, p1), sc0);
u32 a3 = dequant2<KB>(raw_pair<KB>(kr1 + gi * KB, p1), sc1);
+#endif
#pragma unroll
for (int j = 0; j < NT; j++) {
mma16816(S[j], a0, a1, a2, a3, qb[gi * 2 + h][j][0], qb[gi * 2 + h][j][1]);
@@ -225,12 +274,20 @@ qdec_split_rows(
}
float sv[4] = {acc.x, acc.y, acc.z, acc.w};
float s[4]; bool ok[4];
+#if TQ
+ const float kf0 = h2f(ksc[g * 2 + (kvh & 1)]) * sl, kf1 = h2f(ksc[(g + 8) * 2 + (kvh & 1)]) * sl;
+ const float vf0 = h2f(vsc[g * 2 + (kvh & 1)]), vf1 = h2f(vsc[(g + 8) * 2 + (kvh & 1)]);
+#endif
#pragma unroll
for (int e = 0; e < 4; e++) {
int tk = n0 + g + ((e >> 1) << 3);
int ri = e & 1;
ok[e] = rvalid[o][ri] && tk < n_end && tk >= KEY_LO && (!CAUSAL || (float)tk <= qabs[o][ri]);
+#if TQ
+ s[e] = ok[e] ? sv[e] * ((e >> 1) ? kf1 : kf0) : -INFINITY;
+#else
s[e] = ok[e] ? sv[e] * sl : -INFINITY;
+#endif
}
float alpha[2];
#pragma unroll
@@ -248,6 +305,9 @@ qdec_split_rows(
l[o][ri] = l[o][ri] * alpha[ri] + p0 + p1;
m[o][ri] = mn;
}
+#if TQ
+ s[0] *= vf0; s[1] *= vf0; s[2] *= vf1; s[3] *= vf1; // V scale rides on P (token g / g+8 of this lane's rows)
+#endif
Pp[j * 32 + lane] = make_uint2(movtrans(pack_h2(s[0], s[1])), movtrans(pack_h2(s[2], s[3])));
Pa[j * 32 + lane] = make_float2(alpha[0], alpha[1]);
}
@@ -272,15 +332,24 @@ qdec_split_rows(
#pragma unroll
for (int gi = 0; gi < GW; gi++) {
const int gg = warp * GW + gi;
+#if !TQ
u32 sAB = scale2<VB>(vsc[(2 * t) * G + gg], vsc[(2 * t + 1) * G + gg]);
u32 sCD = scale2<VB>(vsc[(2 * t + 8) * G + gg], vsc[(2 * t + 9) * G + gg]);
+#endif
#pragma unroll
for (int h = 0; h < 2; h++) {
int p1 = 16 * h + g, p2 = p1 + 8, i = gi * 2 + h;
+#if TQ
+ u32 a0 = lut2<VB>(raw_one<VB>(vA + gi * VB, p1) | (raw_one<VB>(vB + gi * VB, p1) << 16), cbv_s);
+ u32 a1 = lut2<VB>(raw_one<VB>(vA + gi * VB, p2) | (raw_one<VB>(vB + gi * VB, p2) << 16), cbv_s);
+ u32 a2 = lut2<VB>(raw_one<VB>(vC + gi * VB, p1) | (raw_one<VB>(vD + gi * VB, p1) << 16), cbv_s);
+ u32 a3 = lut2<VB>(raw_one<VB>(vC + gi * VB, p2) | (raw_one<VB>(vD + gi * VB, p2) << 16), cbv_s);
+#else
u32 a0 = dequant2<VB>(raw_one<VB>(vA + gi * VB, p1) | (raw_one<VB>(vB + gi * VB, p1) << 16), sAB);
u32 a1 = dequant2<VB>(raw_one<VB>(vA + gi * VB, p2) | (raw_one<VB>(vB + gi * VB, p2) << 16), sAB);
u32 a2 = dequant2<VB>(raw_one<VB>(vC + gi * VB, p1) | (raw_one<VB>(vD + gi * VB, p1) << 16), sCD);
u32 a3 = dequant2<VB>(raw_one<VB>(vC + gi * VB, p2) | (raw_one<VB>(vD + gi * VB, p2) << 16), sCD);
+#endif
#pragma unroll
for (int j = 0; j < NT; j++) mma16816(O[i][j], a0, a1, a2, a3, plo[j], phi[j]);
}
diff --git a/exllamav3/modules/attention_fn/dsa_triton.py b/exllamav3/modules/attention_fn/dsa_triton.py
index b09e875..5193d3b 100644
--- a/exllamav3/modules/attention_fn/dsa_triton.py
+++ b/exllamav3/modules/attention_fn/dsa_triton.py
@@ -106,6 +106,7 @@ def _dsa_attn_kernel(
OUT_LATENT: tl.constexpr = 0, # store only the latent half, head-major (H, R, D_c),
# the exact mla_unfold input; the rope half of the
# weighted sum is never accumulated
+ TQ: tl.constexpr = 0, # 1: TurboQuant pool (h32 slot = fp32 codebook, pool_s one fp16 scale per entry, rotation lives in the weights)
QC: tl.constexpr = 0, # pool_c is the packed quantized pool (QC bits per
# value, 32-value groups, H32-rotated domain)
):
@@ -137,7 +138,7 @@ def _dsa_attn_kernel(
if D_r > 0:
qr = tl.load(q_base + D_c + offs_r[None, :], mask = valid_h[:, None], other = 0.0)
- if QC > 0:
+ if QC > 0 and TQ == 0:
# Packed pool values live in the H32-rotated domain (orthonormal, block-diagonal
# per 32 values): rotate q once so every score dot is exact, rotate the fp16
# window tiles into the same domain, and rotate the accumulated output back in
@@ -184,7 +185,7 @@ def _dsa_attn_kernel(
mask = mc[:, None] & valid_c[None, :], other = 0.0) \
+ tl.load(ring + idx_r[:, None] * D + offs_c[None, :],
mask = mr[:, None] & valid_c[None, :], other = 0.0)
- if QC > 0:
+ if QC > 0 and TQ == 0:
vc = _rot_h32(vc, h32, BLOCK_W, D_c_pad)
scores = tl.dot(qc, tl.trans(vc))
if D_r > 0:
@@ -228,7 +229,7 @@ def _dsa_attn_kernel(
tl.device_assert(tl.where(in_range, (phys >= 0) & (phys < DEBUG_PAGES), True), "dsa_attn: pool page OOB")
tok = phys * page_size + idx_s % page_size
if QC > 0:
- vc = _qc_load_v(pool_c, pool_s, tok, 0, offs_c, in_range, QC, 1, D_c, D_c_pad)
+ vc = _qc_load_v(pool_c, pool_s, tok, 0, offs_c, in_range, QC, 1, D_c, D_c_pad, h32, TQ)
else:
vc = tl.load(pool_c + tok[:, None] * D_c + offs_c[None, :],
mask = in_range[:, None] & valid_c[None, :], other = 0.0)
@@ -253,7 +254,7 @@ def _dsa_attn_kernel(
denom = tl.where(l == 0.0, 1.0, l)
oc = acc_c / denom[:, None]
- if QC > 0:
+ if QC > 0 and TQ == 0:
# Accumulated in the rotated domain: one inverse rotation (H32 is involutory)
oc = _rot_h32(oc, h32, BLOCK_H, D_c_pad).to(tl.float32)
@@ -558,6 +559,7 @@ def _dsa_attn_split_kernel(
# MULTIROW keeps the per-job state args scalar)
OUT_LATENT: tl.constexpr = 0, # accumulate/store only the latent half; ws_acc rows
# are D_c wide and the combine emits (H, R, D_c)
+ TQ: tl.constexpr = 0,
QC: tl.constexpr = 0, # packed quantized pool (see _dsa_attn_kernel); the
# partials stay in the rotated domain
):
@@ -614,7 +616,7 @@ def _dsa_attn_split_kernel(
if D_r > 0:
qr = tl.load(q_base + D_c + offs_r[None, :], mask = valid_h[:, None], other = 0.0)
- if QC > 0:
+ if QC > 0 and TQ == 0:
# Packed pool values live in the H32-rotated domain (orthonormal, block-diagonal
# per 32 values): rotate q once so every score dot is exact, rotate the fp16
# window tiles into the same domain, and rotate the accumulated output back in
@@ -652,7 +654,7 @@ def _dsa_attn_split_kernel(
mask = mc[:, None] & valid_c[None, :], other = 0.0) \
+ tl.load(ring + idx_r[:, None] * D + offs_c[None, :],
mask = mr[:, None] & valid_c[None, :], other = 0.0)
- if QC > 0:
+ if QC > 0 and TQ == 0:
vc = _rot_h32(vc, h32, BLOCK_W, D_c_pad)
scores = tl.dot(qc, tl.trans(vc))
if D_r > 0:
@@ -692,7 +694,7 @@ def _dsa_attn_split_kernel(
tl.device_assert(tl.where(in_range, (phys >= 0) & (phys < DEBUG_PAGES), True), "dsa_split: pool page OOB")
tok = phys * page_size + idx_s % page_size
if QC > 0:
- vc = _qc_load_v(pool_c, pool_s, tok, 0, offs_c, in_range, QC, 1, D_c, D_c_pad)
+ vc = _qc_load_v(pool_c, pool_s, tok, 0, offs_c, in_range, QC, 1, D_c, D_c_pad, h32, TQ)
else:
vc = tl.load(pool_c + tok[:, None] * D_c + offs_c[None, :],
mask = in_range[:, None] & valid_c[None, :], other = 0.0)
@@ -969,6 +971,7 @@ def _dsa_attn_combine_kernel(
SEQ: tl.constexpr = 1,
MULTIROW: tl.constexpr = 0, # q_pos0 is a per-job i32 array when set
OUT_LATENT: tl.constexpr = 0, # ws rows are D_c wide; emit head-major (H, R, D_c)
+ TQ: tl.constexpr = 0,
QC: tl.constexpr = 0, # split partials came from a packed pool (rotated)
):
"""Combine phase: merge the split partials (sink folded in as one more partial),
@@ -1010,7 +1013,7 @@ def _dsa_attn_combine_kernel(
denom = tl.where(l_run == 0.0, 1.0, l_run)
o = acc / denom[:, None]
- if QC > 0:
+ if QC > 0 and TQ == 0:
# Partials from a packed pool are in the rotated domain: one inverse rotation per
# 32-group of the latent columns (the rope columns are fp16 pages, never rotated;
# D_c is a multiple of 32, so no group straddles the boundary)
@@ -1286,6 +1289,8 @@ def _dsa_pool_expand_kernel(
# the online path; _MAX_ENTRIES bounds the transient (1M entries * 576 dims ~ 1.2 GB)
_dsa_qc_stage = os.environ.get("EXL3_DSA_QC_STAGE", "1") != "0"
_dsa_qc_stage_min_r = int(os.environ.get("EXL3_DSA_QC_STAGE_MIN_R", "64"))
+_dsa_tq_gather = os.environ.get("EXL3_DSA_TQ_GATHER", "1") != "0"
+_dsa_tq_gather_max_r = int(os.environ.get("EXL3_DSA_TQ_GATHER_MAX_R", "8"))
_dsa_qc_stage_max_entries = int(os.environ.get("EXL3_DSA_QC_STAGE_MAX_ENTRIES", str(1 << 20)))
@@ -1294,16 +1299,21 @@ def _stage_packed_pool(pool_c, qc, pool_r, block_table, page_size, pool_len, D_c
a contiguous fp16 pool with an identity block table. Returns (pool_c, pool_r, block_table)
for the fp16 kernel path."""
from ...ext import exllamav3_ext as ext
- pool_s, bits = qc
+ pool_s, bits, tq = (*qc, None)[:3]
G = D_c // 32
npw = -(-pool_len // page_size)
pages = block_table[0, :npw].long()
pc = pool_c.reshape(-1, page_size, G * bits)[pages]
- ps = pool_s.reshape(-1, page_size, G)[pages]
n_rows = npw * page_size
rows_alloc = max(page_size, 1 << (n_rows - 1).bit_length()) # pow2: few distinct sizes
out = torch.empty((rows_alloc, D_c), dtype = torch.half, device = pool_c.device)
- ext.dequant_cache_cont(pc.view(-1, G * bits), ps.view(-1, G), out[:n_rows], 0.0)
+ if tq is not None:
+ # TurboQuant: codebook gather x one scale per entry, left in the rotated domain (the module's weights are rotated with it)
+ from .tq_triton import tq_dequant_rows
+ tq_dequant_rows(pc.view(-1, G * bits), pool_s.reshape(-1, page_size)[pages].reshape(-1), tq.cbk, out[:n_rows], bits, D_c)
+ else:
+ ps = pool_s.reshape(-1, page_size, G)[pages]
+ ext.dequant_cache_cont(pc.view(-1, G * bits), ps.view(-1, G), out[:n_rows], 0.0)
pr = pool_r.reshape(-1, page_size, D_r)[pages].contiguous() if D_r > 0 else pool_r
bt = torch.arange(npw, dtype = torch.int32, device = pool_c.device).unsqueeze(0)
return out[:n_rows].view(npw, page_size, D_c), pr, bt
@@ -1409,13 +1419,32 @@ def dsa_attn(
pool_c, qc, pool_r, block_table, page_size, pool_len, D_c, D_r)
qc = None
dummy_i = block_table
+ if (qc is not None and _dsa_tq_gather and len(qc) > 2 and qc[2] is not None and q_split and out_latent
+ and D_r == 0 and indices is not None and multirow is None and not nc_block and not nc_chunk
+ and not (win_len > 0 and kv_chunk is not None) and not dsa_debug_bounds
+ and R <= _dsa_tq_gather_max_r and pool_c.dtype == torch.int32):
+ # TurboQuant decode: dequantize only the gathered rows (one launch, ~K_pad x D_c fp16 per row) and run the fp16 decode
+ # split (dt / fast kernels) on them; the generic in-kernel plane loader costs ~6x the fp16 kernel per call (served GLM
+ # decode -10 %). Same fp16 values as the in-kernel loader, rotated domain, so the combine is the plain fp16 one.
+ from .tq_triton import tq_gather_dequant
+ pool_s_, bits_, tq_ = qc[0], qc[1], qc[2]
+ K_g = indices.shape[1]
+ st_out = g_tensor_cache.get(q.device, (R * K_g, D_c), torch.half, "dsa_tqg_rows")
+ st_idx = g_tensor_cache.get(q.device, (R, K_g), torch.int32, "dsa_tqg_idx")
+ tq_gather_dequant(pool_c, pool_s_.reshape(-1), tq_.cbk, indices, block_table, st_out, st_idx, page_size, bits_, D_c)
+ bt0 = g_tensor_cache.get(q.device, (1, 1), torch.int32, "dsa_tqg_bt")
+ bt0.zero_()
+ pool_c, block_table, indices, qc = st_out, bt0, st_idx, None
+ page_size = 1 << max(R * K_g - 1, 1).bit_length()
+ dummy_i = block_table
if qc is not None:
- pool_s, qc_bits = qc
+ pool_s, qc_bits, tq = (*qc, None)[:3]
assert D_c % 32 == 0 and pool_c.dtype == torch.int32 and pool_s.dtype == torch.half
- h32_t = _get_h32(q.device)
+ h32_t = _get_h32(q.device) if tq is None else tq.cbk16
+ tqf = int(tq is not None)
pc_arg = pool_c
else:
- pool_s, qc_bits, h32_t = q, 0, q # any valid fp16 pointers for the unused args
+ pool_s, qc_bits, h32_t, tqf = q, 0, q, 0 # any valid fp16 pointers for the unused args
pc_arg = pool_c.reshape(-1, D_c)
has_window = win_len > 0 and kv_chunk is not None
if q_split:
@@ -1449,7 +1478,7 @@ def dsa_attn(
num_stages = min(num_stages, 2)
block_h = min(block_h, 16)
if dsa_debug_bounds:
- pool_rows = pool_s.numel() // (D_c // 32) if qc is not None else pool_c.numel() // max(D_c, 1)
+ pool_rows = pool_s.numel() // (1 if tqf else D_c // 32) if qc is not None else pool_c.numel() // max(D_c, 1)
dbg_pages = -(-pool_rows // max(page_size, 1))
else:
dbg_pages = 0
@@ -1478,7 +1507,7 @@ def dsa_attn(
n_splits = 1
if n_splits > 1:
- block_h = min(block_h, 16) # more head-blocks: the split path wants parallelism
+ block_h = min(block_h, int(os.environ.get("EXL3_DSA_TQ_BH", "32")) if tqf else 16) # more head-blocks: the split path wants parallelism (tq: the codebook expansion is per head-block, so fewer blocks)
# Flash-decoding split: the monolithic kernel at R = 1 is 2 blocks walking the key
# tiles serially (pure latency); the split phase spreads the keys over
# R * h_blocks * n_splits programs and the combine folds sinks/derot/store
@@ -1553,8 +1582,8 @@ def dsa_attn(
SEQ = a_seq, MULTIROW = multirow is not None,
DEBUG_BOUNDS = dbg, DEBUG_PAGES = dbg_pages,
Q_SPLIT = 1 if q_split else 0, OUT_LATENT = 1 if out_latent else 0,
- QC = qc_bits,
- num_warps = num_warps, num_stages = 2,
+ QC = qc_bits, TQ = tqf,
+ num_warps = num_warps, num_stages = 1 if tqf else 2,
)
_dsa_attn_combine_kernel[(R * hb, triton.cdiv(D_out, 128))](
ws_ml, ws_acc, sinks_t, derot_t, out,
@@ -1564,7 +1593,7 @@ def dsa_attn(
BLOCK_H = block_h, BLOCK_D = 128,
SEQ = a_seq, MULTIROW = multirow is not None,
OUT_LATENT = 1 if out_latent else 0,
- QC = qc_bits,
+ QC = qc_bits, TQ = tqf,
num_warps = 4, num_stages = 2,
)
return out
@@ -1638,7 +1667,7 @@ def dsa_attn(
NC_BLOCK = 1 if nc_block else 0,
NC_CHUNK = 1 if nc_chunk else 0, NC_HIST = nc_hist,
Q_SPLIT = 1 if q_split else 0, OUT_LATENT = 1 if out_latent else 0,
- QC = qc_bits,
+ QC = qc_bits, TQ = tqf,
num_warps = num_warps, num_stages = num_stages,
)
return out
diff --git a/exllamav3/modules/attention_fn/kvwin_triton.py b/exllamav3/modules/attention_fn/kvwin_triton.py
index 5404500..6662a2f 100644
--- a/exllamav3/modules/attention_fn/kvwin_triton.py
+++ b/exllamav3/modules/attention_fn/kvwin_triton.py
@@ -7,11 +7,12 @@ from ...cache.kvwin import KVWinCtx
@triton.jit
def _ov_write_kernel(
- k, v, ov_k, ov_v, slots, seqlens,
- q_len, S, Rc, R,
+ k, v, ov_k, ov_v, slots, seqlens, pool_len,
+ q_len, S, Rc, R, W,
n_kv_heads: tl.constexpr,
head_dim: tl.constexpr,
HD_PAD: tl.constexpr,
+ WRITE_POOL_LEN: tl.constexpr = False,
):
"""One program per (batch, row j, kv head). j < S handles the sink row of position j (if it lies in this call),
j >= S the (j - S)-th of the last min(q_len, Rc) rows. A row that is both a sink and in the tail is written
@@ -21,6 +22,10 @@ def _ov_write_kernel(
h = tl.program_id(2)
L = tl.load(seqlens + b)
slot = tl.load(slots + b)
+ if WRITE_POOL_LEN:
+ # BC_Attention: the pool pass attends [S, q-W], its sequence length is the cache's shifted by W
+ if (j == 0) & (h == 0):
+ tl.store(pool_len + b, L - W)
t = tl.where(j < S, j, tl.maximum(q_len - Rc, 0) + (j - S))
p = L + t
ok = (t < q_len) & (slot >= 0) & ((j >= S) | (p < S))
@@ -45,8 +50,8 @@ def ov_write(ctx: KVWinCtx, k: torch.Tensor, v: torch.Tensor, cache_seqlens: tor
n_rows = cfg.S + min(q_len, cfg.Rc)
with torch.cuda.device(k.device):
_ov_write_kernel[(bsz, n_rows, n_kv_heads)](
- k, v, st.ov_k, st.ov_v, slots, cache_seqlens,
- q_len, cfg.S, cfg.Rc, cfg.R,
+ k, v, st.ov_k, st.ov_v, slots, cache_seqlens, cache_seqlens,
+ q_len, cfg.S, cfg.Rc, cfg.R, cfg.W,
n_kv_heads, head_dim, triton.next_power_of_2(head_dim),
num_warps = 1,
)
diff --git a/exllamav3/modules/attention_fn/mla_triton.py b/exllamav3/modules/attention_fn/mla_triton.py
index 3ecc2b8..e32d48f 100644
--- a/exllamav3/modules/attention_fn/mla_triton.py
+++ b/exllamav3/modules/attention_fn/mla_triton.py
@@ -68,6 +68,7 @@ import triton
import triton.language as tl
from .triton_paged import _qc_load_kt, _qc_load_v, _rot_h32
+from .tq_triton import _tq_pack_plane
@triton.jit(do_not_specialize = ["append_len", "num_pages_per_seq"])
def _mla_kv_quant_scatter_kernel(
@@ -110,6 +111,68 @@ def _mla_kv_quant_scatter_kernel(
tl.store(kpe_cache + tok * D_r + r, tl.load(kpe_new + row * D_r + r))
[email protected](do_not_specialize = ["append_len", "num_pages_per_seq"])
+def _mla_tq_scatter_kernel(
+ ckv_new, # (rows, D_c) fp16, NORMALIZED latent in the natural domain (graph path) -- rotated here
+ consts, # fp32: rot_t (D_c * D_c, y = x @ rot_t), then the 2^BITS codebook, then the 2^BITS - 1 midpoints
+ kpe_new, # (rows, D_r) fp16
+ qk, # (pages, page_size, D_c // 32 * BITS) int32
+ sk, # (pages, page_size, 1) fp16, norm / ||centroids||
+ kpe_cache, # (pages, page_size, 1, D_r) fp16
+ block_table,
+ cache_seqlens,
+ num_pages_per_seq,
+ append_len,
+ page_size: tl.constexpr,
+ BITS: tl.constexpr,
+ D_c: tl.constexpr,
+ D_r: tl.constexpr,
+ BK: tl.constexpr,
+):
+ """TurboQuant append for the graph-captured decode block: one program per new row. y = R x (dense matvec in fp32, BK rows of the
+ rotation per step), unit-normalize, nearest Lloyd-Max centroid per coordinate, bit planes, one fp16 scale, rope key copy."""
+ row = tl.program_id(0)
+ batch = row // append_len
+ pos = row - batch * append_len
+ abs_pos = tl.load(cache_seqlens + batch) + pos
+ page = abs_pos // page_size
+ phys = tl.load(block_table + batch * num_pages_per_seq + page)
+ tok = phys.to(tl.int64) * page_size + (abs_pos - page * page_size)
+
+ cols = tl.arange(0, D_c)
+ y = tl.zeros((D_c,), tl.float32)
+ for k0 in range(0, D_c, BK):
+ ks = k0 + tl.arange(0, BK)
+ xk = tl.load(ckv_new + row.to(tl.int64) * D_c + ks).to(tl.float32)
+ wt = tl.load(consts + ks[:, None] * D_c + cols[None, :])
+ y += tl.sum(xk[:, None] * wt, axis = 0)
+ # the dispatch path rotates in fp16 (tq_rotate); round the same way so both paths store the same codes
+ y = y.to(tl.float16).to(tl.float32)
+ cb_off = D_c * D_c
+ mid_off = cb_off + (1 << BITS)
+ nrm = tl.maximum(tl.sqrt(tl.sum(y * y, axis = 0)), 1e-12)
+ u = y / nrm
+ code = tl.zeros((D_c,), tl.int32)
+ for i in range((1 << BITS) - 1):
+ code += (u > tl.load(consts + mid_off + i)).to(tl.int32)
+ c = tl.load(consts + cb_off + code)
+ cn = tl.maximum(tl.sqrt(tl.sum(c * c, axis = 0)), 1e-12)
+ tl.store(sk + tok, (nrm / cn).to(tl.float16))
+ G: tl.constexpr = D_c // 32
+ wbase = qk + tok * (G * BITS)
+ if BITS & 8:
+ _tq_pack_plane(wbase, code, 8, BITS, 0, BITS - 8, G, D_c)
+ if BITS & 4:
+ _tq_pack_plane(wbase, code, 4, BITS, (BITS & 8), BITS - (BITS & 8) - 4, G, D_c)
+ if BITS & 2:
+ _tq_pack_plane(wbase, code, 2, BITS, (BITS & 12), BITS - (BITS & 12) - 2, G, D_c)
+ if BITS & 1:
+ _tq_pack_plane(wbase, code, 1, BITS, (BITS & 14), 0, G, D_c)
+ if D_r > 0:
+ r = tl.arange(0, D_r)
+ tl.store(kpe_cache + tok * D_r + r, tl.load(kpe_new + row * D_r + r))
+
+
@triton.jit(do_not_specialize = ["append_len", "num_pages_per_seq"])
def _mla_kv_update_kernel(
ckv_new, # (bsz, len, D_c)
@@ -219,6 +282,7 @@ def _mla_decode_split_kernel(
num_pages_per_seq, # runtime: block-table width can grow without recompiling
num_splits, # runtime: the grid may be launched wider; extra splits idle
QC: tl.constexpr, # latent cache bits (2-8), 0 = fp16
+ TQ: tl.constexpr, # 1: TurboQuant pages (h32 slot = fp32 codebook, scales (pages, page, 1)), rotation lives in the weights
QC_TRANS: tl.constexpr, # 0: expand both orientations; 1: expand V once, trans for K^T
Q_PE_TM: tl.constexpr, # q_pe layout: 0 = head-major (H, R, D_r), 1 = token-major
# (R, H, D_r) as staged by the BC graph (no permute stage)
@@ -266,7 +330,7 @@ def _mla_decode_split_kernel(
if D_r > 0:
q_r = tl.load(q_pe + qpe_row[:, None] * D_r + offs_r[None, :],
mask = valid_row[:, None], other = 0.0)
- if QC > 0:
+ if QC > 0 and TQ == 0:
# Packed values live in the rotated domain; rotating q here keeps the score dot exact
# (H32 is orthogonal and block-diagonal per 32, so dot(Hq, Hk) == dot(q, k))
q_c = _rot_h32(q_c, h32, BLOCK_ROWS, D_c)
@@ -295,11 +359,11 @@ def _mla_decode_split_kernel(
# the dequantized fp16 tile for the score dot (QC_TRANS 1) -- the transpose is of
# a plain fp16 value, not of loader interleave output (the miscompiling shape)
if QC_TRANS:
- v_tile = _qc_load_v(ckv_cache, ckv_scales, tok, 0, offs_c, in_range, QC, 1, D_c, D_c)
+ v_tile = _qc_load_v(ckv_cache, ckv_scales, tok, 0, offs_c, in_range, QC, 1, D_c, D_c, h32, TQ)
kt = tl.trans(v_tile)
else:
- kt = _qc_load_kt(ckv_cache, ckv_scales, tok, 0, offs_c, in_range, QC, 1, D_c, D_c)
- v_tile = _qc_load_v(ckv_cache, ckv_scales, tok, 0, offs_c, in_range, QC, 1, D_c, D_c)
+ kt = _qc_load_kt(ckv_cache, ckv_scales, tok, 0, offs_c, in_range, QC, 1, D_c, D_c, h32, TQ)
+ v_tile = _qc_load_v(ckv_cache, ckv_scales, tok, 0, offs_c, in_range, QC, 1, D_c, D_c, h32, TQ)
else:
# V is K: load the latent tile once, transpose it for the score dot
v_tile = tl.load(ckv_cache + tok[:, None] * D_c + offs_c[None, :],
@@ -328,7 +392,7 @@ def _mla_decode_split_kernel(
if FINAL:
out_tile = acc / tl.where(l[:, None] == 0.0, 1.0, l[:, None])
- if QC > 0:
+ if QC > 0 and TQ == 0:
# The accumulator is in the rotated domain (rotated V); one inverse rotation at
# the end recovers the latent (H32 is symmetric, so the same helper serves)
out_tile = _rot_h32(out_tile, h32, BLOCK_ROWS, D_c)
@@ -351,6 +415,7 @@ def _mla_decode_combine_kernel(
h32,
num_splits,
QC: tl.constexpr,
+ TQ: tl.constexpr,
bsz: tl.constexpr,
q_len: tl.constexpr,
n_q_heads: tl.constexpr,
@@ -389,7 +454,7 @@ def _mla_decode_combine_kernel(
l_sum += l_s * w
out_tile = acc / tl.where(l_sum[:, None] == 0.0, 1.0, l_sum[:, None])
- if QC > 0:
+ if QC > 0 and TQ == 0:
# Split partials stay in the rotated domain; the single inverse rotation happens here
out_tile = _rot_h32(out_tile, h32, BLOCK_ROWS, D_c)
q_row = row_h * (bsz * q_len) + batch * q_len + row_q
@@ -411,6 +476,7 @@ def _mla_prefill_kernel(
q_len,
n_rows,
QC: tl.constexpr,
+ TQ: tl.constexpr,
QC_TRANS: tl.constexpr,
pre_appended_len: tl.constexpr,
n_q_heads: tl.constexpr,
@@ -441,7 +507,7 @@ def _mla_prefill_kernel(
if D_r > 0:
q_r = tl.load(q_pe + q_row[:, None] * D_r + offs_r[None, :],
mask = valid_row[:, None], other = 0.0)
- if QC > 0:
+ if QC > 0 and TQ == 0:
q_c = _rot_h32(q_c, h32, BLOCK_M, D_c)
past = tl.load(cache_seqlens + batch) + pre_appended_len - q_len
@@ -467,11 +533,11 @@ def _mla_prefill_kernel(
if QC > 0:
if QC_TRANS:
- v_tile = _qc_load_v(ckv_cache, ckv_scales, tok, 0, offs_c, in_range, QC, 1, D_c, D_c)
+ v_tile = _qc_load_v(ckv_cache, ckv_scales, tok, 0, offs_c, in_range, QC, 1, D_c, D_c, h32, TQ)
kt = tl.trans(v_tile)
else:
- kt = _qc_load_kt(ckv_cache, ckv_scales, tok, 0, offs_c, in_range, QC, 1, D_c, D_c)
- v_tile = _qc_load_v(ckv_cache, ckv_scales, tok, 0, offs_c, in_range, QC, 1, D_c, D_c)
+ kt = _qc_load_kt(ckv_cache, ckv_scales, tok, 0, offs_c, in_range, QC, 1, D_c, D_c, h32, TQ)
+ v_tile = _qc_load_v(ckv_cache, ckv_scales, tok, 0, offs_c, in_range, QC, 1, D_c, D_c, h32, TQ)
else:
v_tile = tl.load(ckv_cache + tok[:, None] * D_c + offs_c[None, :],
mask = in_range[:, None], other = 0.0)
@@ -498,7 +564,7 @@ def _mla_prefill_kernel(
m = m_new
out_tile = acc / tl.where(l[:, None] == 0.0, 1.0, l[:, None])
- if QC > 0:
+ if QC > 0 and TQ == 0:
out_tile = _rot_h32(out_tile, h32, BLOCK_M, D_c)
tl.store(out + q_row[:, None] * D_c + offs_c[None, :], out_tile, mask = valid_row[:, None])
@@ -517,6 +583,7 @@ def _mla_gather_tile_kernel(
num_pages_per_seq, # runtime
batch, # runtime
QC: tl.constexpr,
+ TQ: tl.constexpr,
page_size: tl.constexpr,
D_c: tl.constexpr,
D_r: tl.constexpr,
@@ -537,9 +604,11 @@ def _mla_gather_tile_kernel(
offs_c = tl.arange(0, D_c)
if QC > 0:
- tile = _qc_load_v(ckv_cache, ckv_scales, tok, 0, offs_c, in_range, QC, 1, D_c, D_c)
- # h32 is symmetric orthonormal, so the same multiply that rotates also unrotates
- tile = _rot_h32(tile, h32, BLOCK_R, D_c)
+ tile = _qc_load_v(ckv_cache, ckv_scales, tok, 0, offs_c, in_range, QC, 1, D_c, D_c, h32, TQ)
+ # h32 is symmetric orthonormal, so the same multiply that rotates also unrotates; TQ keeps the rotated domain (the module's
+ # up-projection weights are rotated with it)
+ if TQ == 0:
+ tile = _rot_h32(tile, h32, BLOCK_R, D_c)
else:
tile = tl.load(ckv_cache + tok[:, None] * D_c + offs_c[None, :],
mask = in_range[:, None], other = 0.0)
@@ -1102,13 +1171,14 @@ def mla_attn_triton_decode(
if qc is not None:
from .triton_paged import _get_h32
- ckv_scales, qc_bits = qc
+ ckv_scales, qc_bits, tq = (*qc, None)[:3] # tq: cache.tq.TQState for TurboQuant pages (codebook in the h32 slot), else None
assert ckv_cache.shape[-1] == D_c // 32 * qc_bits
- h32 = _get_h32(q_lat.device)
+ h32 = _get_h32(q_lat.device) if tq is None else tq.cbk16
+ tqf = int(tq is not None)
if _qc_trans_override is not None:
qc_trans = _qc_trans_override != "0"
else:
- ckv_scales, qc_bits, h32 = q_lat, 0, q_lat
+ ckv_scales, qc_bits, h32, tqf = q_lat, 0, q_lat, 0
if out is None:
out = torch.empty_like(q_lat)
@@ -1119,14 +1189,14 @@ def mla_attn_triton_decode(
if block_h is None:
# 16 rows fills the tl.dot M axis; more heads per program means fewer redundant passes
# over the latent cache, which is what keeps large-head-count models compute-bound
- block_h = max(16 // block_m, 1)
+ block_h = max((32 if tqf else 16) // block_m, 1) # TurboQuant: the codebook expansion is the cost of a program, 32 rows halve the passes (GLM H64 at 4K: 0.91 -> 0.26 ms, rounding-level equal)
block_h = min(block_h, max(1, triton.next_power_of_2(n_q_heads)))
block_rows = block_m * block_h
if block_n is None:
# qc: one big expanded tile per iteration, no pipelining (the expansion is ALU work the
# scheduler overlaps anyway); swept best on Ampere/Ada/Blackwell at 512-wide latents.
# fp16: smaller tiles, deeper pipeline
- block_n = (32 if D_c <= 512 else 16) if qc is None else (_qc_bn_override or 64)
+ block_n = (32 if D_c <= 512 else 16) if qc is None else (_qc_bn_override or (32 if tqf else 64))
if num_stages is None:
num_stages = 3 if qc is None else 1
if num_warps is None:
@@ -1178,7 +1248,7 @@ def mla_attn_triton_decode(
q_lat, q_pe, ckv_cache, kpe_cache, ckv_scales, h32, block_table, cache_seqlens, out,
partial_o, partial_ml,
split_len, num_pages_per_seq, num_splits,
- qc_bits, bool(qc_trans), False, bsz, q_len, pre_appended_len, n_q_heads, page_size, D_c, D_r, float(softmax_scale),
+ qc_bits, tqf, bool(qc_trans), False, bsz, q_len, pre_appended_len, n_q_heads, page_size, D_c, D_r, float(softmax_scale),
bool(causal), num_splits == 1,
block_m, block_h, block_rows, block_n,
num_warps = num_warps, num_stages = num_stages,
@@ -1211,7 +1281,7 @@ def mla_attn_triton_decode(
if num_splits > 1:
_mla_decode_combine_kernel[(programs,)](
partial_o, partial_ml, out, h32, num_splits,
- qc_bits, bsz, q_len, n_q_heads, D_c, block_m, block_h, block_rows,
+ qc_bits, tqf, bsz, q_len, n_q_heads, D_c, block_m, block_h, block_rows,
num_warps = 4, num_stages = 1,
)
_dbg_sync("mla_decode_combine", q_lat.device)
@@ -1445,10 +1515,11 @@ def mla_attn_triton_prefill_mha(
if qc is not None:
from .triton_paged import _get_h32
- ckv_scales, qc_bits = qc
- h32 = _get_h32(dev)
+ ckv_scales, qc_bits, tq = (*qc, None)[:3] # tq: cache.tq.TQState for TurboQuant pages (codebook in the h32 slot), else None
+ h32 = _get_h32(dev) if tq is None else tq.cbk16
+ tqf = int(tq is not None)
else:
- ckv_scales, qc_bits, h32 = q, 0, q
+ ckv_scales, qc_bits, h32, tqf = q, 0, q, 0
# Workspace is bounded by (tile_size, chunk length), NOT by context length, and only ONE tile
# of up-projected K/V ever exists at a time. These are prefill-sized (128 MiB per buffer at a
@@ -1486,7 +1557,7 @@ def mla_attn_triton_prefill_mha(
_mla_gather_tile_kernel[(triton.cdiv(tl_len, 64),)](
ckv_cache, kpe_cache, ckv_scales, h32, block_table,
ckv_t, kpe_t, a, tl_len, npps, b,
- qc_bits, page_size, D_c, D_r, 64,
+ qc_bits, tqf, page_size, D_c, D_r, 64,
num_warps = 4, num_stages = 2,
)
# Up-projection as two plain contiguous GEMMs (never the strided-batched form)
@@ -1555,11 +1626,12 @@ def mla_attn_triton_prefill(
if qc is not None:
from .triton_paged import _get_h32
- ckv_scales, qc_bits = qc
+ ckv_scales, qc_bits, tq = (*qc, None)[:3] # tq: cache.tq.TQState for TurboQuant pages (codebook in the h32 slot), else None
assert ckv_cache.shape[-1] == D_c // 32 * qc_bits
- h32 = _get_h32(q_lat.device)
+ h32 = _get_h32(q_lat.device) if tq is None else tq.cbk16
+ tqf = int(tq is not None)
else:
- ckv_scales, qc_bits, h32 = q_lat, 0, q_lat
+ ckv_scales, qc_bits, h32, tqf = q_lat, 0, q_lat, 0
if block_m is None:
block_m = 32 if qc is None else 16
@@ -1577,7 +1649,7 @@ def mla_attn_triton_prefill(
_mla_prefill_kernel[(triton.cdiv(q_len, block_m), bsz * n_q_heads)](
q_lat, q_pe, ckv_cache, kpe_cache, ckv_scales, h32, block_table, cache_seqlens, out,
block_table.shape[1], q_len, n_rows,
- qc_bits, bool(qc_trans), pre_appended_len, n_q_heads, page_size, D_c, D_r, float(softmax_scale),
+ qc_bits, tqf, bool(qc_trans), pre_appended_len, n_q_heads, page_size, D_c, D_r, float(softmax_scale),
bool(causal), block_m, block_n,
num_warps = num_warps, num_stages = num_stages,
)
diff --git a/exllamav3/modules/attention_fn/qdec.hip b/exllamav3/modules/attention_fn/qdec.hip
index 50c3a70..1d0ab8c 100644
--- a/exllamav3/modules/attention_fn/qdec.hip
+++ b/exllamav3/modules/attention_fn/qdec.hip
@@ -125,6 +125,11 @@ template<int B> __device__ __forceinline__ u32 dequant2_tq(u32 raw_m, u32 s2, co
#define TQF_OFF 0
#endif
#define TQF (TQ && !TQF_OFF && (KB == 5 || KB == 6) && (VB == 5 || VB == 6) && (DTW == 8 || DTW == 4))
+// TQVP: the V runs of the next slab are fetched during the current slab's S / softmax (they stay live in vr / vsc, 48 VGPRs at 6 bits). With
+// 3+ q tiles (O accumulators 96+ VGPRs) that spills (72-79 VGPRs at 36-48 rows), so those fetch the V runs of a slab right before its lookups instead.
+#ifndef TQVP
+#define TQVP (NT <= 2)
+#endif
template<int B, int K> __device__ __forceinline__ void zbuild(u32 w, u32 y, u32& ze, u32& zo)
{
if (B == 6) {
@@ -306,15 +311,15 @@ qdec_split(
const int gi_v = dcol >> 5, p0 = dcol & 31;
u32 vr[16][NRW > 0 ? NRW : 1];
u32 vsc[16];
- auto load_v = [&]() {
+ auto load_v = [&](int r0, int lm) {
#pragma unroll
for (int e = 0; e < 16; e++) {
- size_t row = (size_t) row0 + min(e, lim);
+ size_t row = (size_t) r0 + min(e, lm);
load_run(vr[e], v_cache + row * (GPT * VB) + kvh * VCHW + gi_v * VB, p0);
vsc[e] = (u32) v_scales[row * NKV + kvh] * 0x10001u;
}
};
- if (nslabs > sw) { slab_rows(0); load_k(); load_v(); }
+ if (nslabs > sw) { slab_rows(0); load_k(); if (TQVP) load_v(row0, lim); }
#else
if (nslabs > sw) { slab_rows(0); load_k(); }
#endif
@@ -393,6 +398,7 @@ qdec_split(
if (!active) continue;
#if TQF
const bool more = it + 1 < iters && (sw + (it + 1) * NSW) < nslabs;
+ const int cur_row0 = row0, cur_lim = lim;
if (more) { slab_rows(it + 1); load_k(); } // kw is dead once S is formed
#endif
@@ -451,11 +457,12 @@ qdec_split(
#if TQF
{
u32 ze[16], zo[16], vsp[8];
+ if (!TQVP) load_v(cur_row0, cur_lim);
#pragma unroll
for (int e = 0; e < 16; e++) zbuild<VB, 0>(vr[e][0], vr[e][1], ze[e], zo[e]);
#pragma unroll
for (int i = 0; i < 8; i++) vsp[i] = perm(vsc[2 * i + 1], vsc[2 * i], 0x05040100u); // scales of tokens 2i, 2i + 1
- if (more) load_v(); // vr is dead: the next slab's V runs fly during the lookups below
+ if (TQVP && more) load_v(row0, lim); // vr is dead: the next slab's V runs fly during the lookups below
#pragma unroll
for (int u = 0; u < DTW / 2; u++) {
v8u b0, b1;
diff --git a/exllamav3/modules/attention_fn/qdec_cuda.py b/exllamav3/modules/attention_fn/qdec_cuda.py
index 3256a1d..5339e74 100644
--- a/exllamav3/modules/attention_fn/qdec_cuda.py
+++ b/exllamav3/modules/attention_fn/qdec_cuda.py
@@ -17,6 +17,7 @@ _SRC_ROWS = os.path.join(os.path.dirname(__file__), "cu", "qdec_rows.cu") #
_COMMON = os.path.join(os.path.dirname(__file__), "cu", "qdec_common.cuh")
ROWS_MODE = os.environ.get("EXL3_QDEC_ROWS", "1") # 0: no many-row kernel, 1: only where qdec.cu cannot, 2: always
_CACHE = os.path.expanduser(os.environ.get("EXL3_QDEC_CACHE", "~/.cache/exl3_qdec"))
+TQ_QDEC_MAX_NTHD = int(os.environ.get("EXL3_QDEC_TQ_NTHD", "384")) # TurboQuant: largest row tiles x head dim qdec.cu takes without spilling
_kernels = {}
@@ -50,7 +51,7 @@ def geometry(cfg):
sc_b = (16 * g * 2 + 15) // 16 * 16
stage_b = 16 * kstr * 4 + 16 * vstr * 4 + 2 * sc_b
ring = cfg["nw"] * cfg["st"] * stage_b
- qs = (nt * 8 * (hd + 8) * 2 + 15) // 16 * 16
+ qs = (nt * 8 * (hd + 8) * 2 + 15) // 16 * 16 + (nt * 8 * hd * 2 + 15) // 16 * 16 # rotated q rows + the raw rows staged by cp.async
merge = (cfg["nw"] * nt * 8 * hd + 2 * cfg["nw"] * nt * 8) * 4
return dict(nt=nt, rows=rows, stage_b=stage_b, shared=qs + max(ring, merge, 4096))
@@ -161,8 +162,11 @@ def rows_nw(hd):
def static_smem(cfg) -> int:
- """static shared memory of qdec.cu: the TurboQuant pair tables (codebook entry pairs as 32-bit words, K and V)"""
- return 4 * ((1 << 2 * cfg["kb"]) + (1 << 2 * cfg["vb"])) if cfg.get("tq") and not cfg.get("rows_kernel") else 0
+ """static shared memory of qdec.cu: the TurboQuant pair tables (codebook entry pairs as 32-bit words, K and V), else the 32x32 fp32
+ H32 matrix of the q prologue (the many-row kernel keeps it in its ring)"""
+ if cfg.get("rows_kernel") and not cfg.get("tq"):
+ return 0
+ return 4 * ((1 << 2 * cfg["kb"]) + (1 << 2 * cfg["vb"])) if cfg.get("tq") else 2048
def pick_nw_st(cfg):
@@ -173,7 +177,7 @@ def pick_nw_st(cfg):
c.update(nw=rows_nw(cfg["hd"]))
for st in ((int(os.environ["EXL3_QDEC_RST"]),) if os.environ.get("EXL3_QDEC_RST") else (3, 2, 1)):
c.update(st=st)
- if geometry(c)["shared"] <= 99 * 1024:
+ if geometry(c)["shared"] <= 99 * 1024 - static_smem(c):
return c["nw"], st
raise QdecUnsupported("no ring configuration fits")
narrow = cfg["hd"] == 128 and cfg["kb"] + cfg["vb"] <= 8
@@ -201,11 +205,19 @@ def make_cfg(q_len, n_q_heads, n_kv_heads, head_dim, k_bits, v_bits, page_size,
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
+ # TurboQuant: 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):
+ # qdec.cu keeps the whole O (hd x rows fp32) in registers and spills past ~384 accumulator columns (ptxas sm_86: hd128 nt4,
+ # hd256 nt2); the many-row kernel splits the head dim across the warps and serves everything above
+ old_ok = supported(cfg) and geometry(cfg)["nt"] * 8 <= block_rows and geometry(cfg)["nt"] * cfg["hd"] <= TQ_QDEC_MAX_NTHD
+ if ROWS_MODE == "2" or not old_ok:
+ rc = dict(cfg, rows_kernel=True, nw=rows_nw(cfg["hd"]), block_rows=max(16, triton.next_power_of_2(geometry(cfg)["rows"])))
+ if supported(rc):
+ cfg = rc
+ old_ok = True
+ if not old_ok:
return None
try:
cfg["nw"], cfg["st"] = pick_nw_st(cfg)
diff --git a/exllamav3/modules/attention_fn/qsa_triton.py b/exllamav3/modules/attention_fn/qsa_triton.py
index 5411c41..98a9018 100644
--- a/exllamav3/modules/attention_fn/qsa_triton.py
+++ b/exllamav3/modules/attention_fn/qsa_triton.py
@@ -170,6 +170,9 @@ def _qsa_sparse_split_kernel(
PAGED: tl.constexpr = 1,
QCK: tl.constexpr = 0, # packed quantized K pages (bits), 0 = fp16
QCV: tl.constexpr = 0, # packed quantized V pages (bits), 0 = fp16
+ k_cb = None, # TurboQuant codebooks (TQ == 1): q is already rotated, the codes read through them
+ v_cb = None,
+ TQ: tl.constexpr = 0,
):
"""Gathered GQA flash-decoding phase 1 over an index list, q_len == 1: one program per
(batch, kv_head, h_block, split), iterating the row's indices instead of the sequential
@@ -193,7 +196,7 @@ def _qsa_sparse_split_kernel(
offs_d = tl.arange(0, head_dim)
q_base = (batch * n_q_heads + q_head) * head_dim
q_tile = tl.load(q + q_base[:, None] + offs_d[None, :], mask = valid_row[:, None], other = 0.0)
- if QCK > 0:
+ if QCK > 0 and TQ == 0:
# Packed keys live in the H32-rotated domain: rotate q once, scores stay exact
q_tile = _rot_h32(q_tile, h32, BLOCK_H, head_dim)
@@ -217,7 +220,7 @@ def _qsa_sparse_split_kernel(
tok = idx_c
if QCK > 0:
- k_tile = _qc_load_kt(k_cache, k_scales, tok, kv_head, offs_d, valid_n, QCK, n_kv_heads, head_dim, head_dim)
+ k_tile = _qc_load_kt(k_cache, k_scales, tok, kv_head, offs_d, valid_n, QCK, n_kv_heads, head_dim, head_dim, k_cb, TQ)
else:
k_ptrs = k_cache + ((tok[None, :] * n_kv_heads + kv_head) * head_dim + offs_d[:, None])
k_tile = tl.load(k_ptrs, mask = valid_n[None, :], other = 0.0)
@@ -235,7 +238,7 @@ def _qsa_sparse_split_kernel(
if QCV > 0:
# Rotated-domain values: the partials stay rotated, the combine rotates back
- v_tile = _qc_load_v(v_cache, v_scales, tok, kv_head, offs_d, valid_n, QCV, n_kv_heads, head_dim, head_dim)
+ v_tile = _qc_load_v(v_cache, v_scales, tok, kv_head, offs_d, valid_n, QCV, n_kv_heads, head_dim, head_dim, v_cb, TQ)
else:
v_ptrs = v_cache + ((tok[:, None] * n_kv_heads + kv_head) * head_dim + offs_d[None, :])
v_tile = tl.load(v_ptrs, mask = valid_n[:, None], other = 0.0)
@@ -380,6 +383,7 @@ def qsa_sparse_attend_rows(
qc: tuple | None = None, # (k_scales, v_scales, k_bits, v_bits): k / v are the packed
# int32 pages (CacheLayer_quant), dequantized online
n_kv_heads: int | None = None, # required with qc (the packed rows carry no head axis)
+ tq = None, # TurboQuant state (cache.tq.TQState) with qc: q is already rotated, o comes back rotated
) -> torch.Tensor:
"""Eager gathered GQA attention, one index list per query row: the sparse prefill /
eager-fallback form of the BC sparse decode kernels. block_table = None runs the flat
@@ -427,11 +431,12 @@ def qsa_sparse_attend_rows(
head_dim = hd, K_pad = K_pad, scale = float(sm_scale),
BLOCK_H = BLOCK_H, BLOCK_N = BLOCK_N, PAGED = 1 if paged else 0,
QCK = k_bits, QCV = v_bits,
+ **(dict(k_cb = tq.cbk, v_cb = tq.cbv, TQ = 1) if tq is not None else {}),
num_warps = QSA_PIPE_NW if use_pipe else _QSA_NW, num_stages = _QSA_NS,
)
_paged_attn_decode_combine_kernel[(programs,)](
partial_o, partial_ml, o, h32, splits, partial_ml,
- QCV = v_bits, HAS_SINKS = False, q_len = 1, n_q_heads = H, n_kv_heads = kvh,
+ QCV = 0 if tq is not None else v_bits, HAS_SINKS = False, q_len = 1, n_q_heads = H, n_kv_heads = kvh,
head_dim = hd, HD_PAD = hd, BLOCK_M = 1, BLOCK_H = BLOCK_H, BLOCK_ROWS = BLOCK_H,
num_warps = 4, num_stages = 1,
)
diff --git a/exllamav3/modules/attention_fn/tq_triton.py b/exllamav3/modules/attention_fn/tq_triton.py
index 0bfd5e7..fa3007e 100644
--- a/exllamav3/modules/attention_fn/tq_triton.py
+++ b/exllamav3/modules/attention_fn/tq_triton.py
@@ -73,6 +73,114 @@ def tq_dequant_window(words, scales, cb, out, cache_seqlens, block_table, page_s
)
+def _tq_dequant_rows_kernel(
+ words, scales, cb, out, n_rows,
+ BITS: tl.constexpr,
+ D: tl.constexpr,
+ TB: tl.constexpr,
+):
+ """Contiguous rows (one fp16 scale per row, the MLA latent layout): out[row] = codebook[codes] * scale, rotated domain."""
+ row = tl.program_id(0) * TB + tl.arange(0, TB)
+ rmask = row < n_rows
+ d = tl.arange(0, D)
+ g = d // 32
+ r = d - g * 32
+ G: tl.constexpr = D // 32
+ base = row[:, None].to(tl.int64) * (G * BITS) + g[None, :] * BITS
+ m2 = rmask[:, None]
+ raw = tl.zeros((TB, D), tl.int32)
+ pbase = 0
+ if BITS & 8:
+ w = tl.load(words + base + pbase + (r // 4)[None, :], mask = m2, other = 0)
+ raw = (raw << 8) | ((w >> ((r % 4) * 8)[None, :]) & 255)
+ pbase += 8
+ if BITS & 4:
+ w = tl.load(words + base + pbase + (r // 8)[None, :], mask = m2, other = 0)
+ raw = (raw << 4) | ((w >> ((r % 8) * 4)[None, :]) & 15)
+ pbase += 4
+ if BITS & 2:
+ w = tl.load(words + base + pbase + (r // 16)[None, :], mask = m2, other = 0)
+ raw = (raw << 2) | ((w >> ((r % 16) * 2)[None, :]) & 3)
+ pbase += 2
+ if BITS & 1:
+ w = tl.load(words + base + pbase + (r // 32)[None, :], mask = m2, other = 0)
+ raw = (raw << 1) | ((w >> (r % 32)[None, :]) & 1)
+ sc = tl.load(scales + row, mask = rmask, other = 0.0).to(tl.float32)
+ val = (tl.load(cb + raw) * sc[:, None]).to(tl.float16)
+ tl.store(out + row[:, None].to(tl.int64) * D + d[None, :], val, mask = m2)
+
+
+def tq_dequant_rows(words, scales, cb, out, bits, dim):
+ """words [N, dim/32*bits] int32, scales [N] fp16 -> out [N, dim] fp16 (rotated domain)."""
+ n = words.shape[0]
+ tb = 8
+ with torch.cuda.device(words.device):
+ _tq_dequant_rows_kernel[(triton.cdiv(n, tb),)](words, scales, cb, out, n, bits, dim, tb, num_warps = 4, num_stages = 1)
+
+
+def _tq_gather_dequant_kernel(
+ words, scales, cb, indices, block_table, out, idx_out, npr,
+ K_pad: tl.constexpr,
+ PAGE: tl.constexpr,
+ BITS: tl.constexpr,
+ D: tl.constexpr,
+ TB: tl.constexpr,
+):
+ """Decode-time staging of the gathered rows of a TurboQuant latent pool: program (query row, TB-entry tile) dequantizes the
+ rows its indices select into out[row * K_pad + n] (fp16, rotated domain, MLA layout: one fp16 scale per entry) and writes the
+ compact index idx_out[row, n] = row * K_pad + n (-1 where the selection is padded), so the fp16 decode kernels run on `out`
+ with a one-page identity block table. Padded entries cost no loads or stores."""
+ row = tl.program_id(0)
+ n = tl.program_id(1) * TB + tl.arange(0, TB)
+ idx = tl.load(indices + row * K_pad + n, mask = n < K_pad, other = -1)
+ ok = idx >= 0
+ ids = tl.where(ok, idx, 0)
+ phys = tl.load(block_table + row * npr + ids // PAGE, mask = ok, other = 0)
+ tok = (phys * PAGE + ids % PAGE).to(tl.int64)
+ slot = row * K_pad + n
+ tl.store(idx_out + slot, tl.where(ok, slot, -1), mask = n < K_pad)
+ d = tl.arange(0, D)
+ g = d // 32
+ r = d - g * 32
+ G: tl.constexpr = D // 32
+ base = tok[:, None] * (G * BITS) + g[None, :] * BITS
+ m2 = ok[:, None]
+ raw = tl.zeros((TB, D), tl.int32)
+ pbase = 0
+ if BITS & 8:
+ w = tl.load(words + base + pbase + (r // 4)[None, :], mask = m2, other = 0)
+ raw = (raw << 8) | ((w >> ((r % 4) * 8)[None, :]) & 255)
+ pbase += 8
+ if BITS & 4:
+ w = tl.load(words + base + pbase + (r // 8)[None, :], mask = m2, other = 0)
+ raw = (raw << 4) | ((w >> ((r % 8) * 4)[None, :]) & 15)
+ pbase += 4
+ if BITS & 2:
+ w = tl.load(words + base + pbase + (r // 16)[None, :], mask = m2, other = 0)
+ raw = (raw << 2) | ((w >> ((r % 16) * 2)[None, :]) & 3)
+ pbase += 2
+ if BITS & 1:
+ w = tl.load(words + base + pbase + (r // 32)[None, :], mask = m2, other = 0)
+ raw = (raw << 1) | ((w >> (r % 32)[None, :]) & 1)
+ sc = tl.load(scales + tok, mask = ok, other = 0.0).to(tl.float32)
+ val = (tl.load(cb + raw) * sc[:, None]).to(tl.float16)
+ tl.store(out + slot[:, None].to(tl.int64) * D + d[None, :], val, mask = m2)
+
+
+def tq_gather_dequant(words, scales, cb, indices, block_table, out, idx_out, page_size, bits, dim, tb = 8, num_warps = 4):
+ """indices [R, K_pad] int32 (-1 padded) -> out [R * K_pad, dim] fp16 + idx_out [R, K_pad] int32 compact indices.
+ block_table has one row per query row, or a single row shared by all (stride 0). Graph-capturable (no host reads)."""
+ R, K_pad = indices.shape
+ npr = block_table.shape[1] if block_table.shape[0] > 1 else 0
+ with torch.cuda.device(words.device):
+ _tq_gather_dequant_kernel[(R, triton.cdiv(K_pad, tb))](
+ words, scales, cb, indices, block_table, out, idx_out, npr,
+ K_pad, page_size, bits, dim, tb, num_warps = num_warps, num_stages = 1,
+ )
+
+
@triton.jit
def _tq_write_kernel(
x, words, scales, cb, mid, block_table, cache_seqlens,
diff --git a/exllamav3/modules/attention_fn/triton_paged.py b/exllamav3/modules/attention_fn/triton_paged.py
index 8cc0f9e..51d9ab5 100644
--- a/exllamav3/modules/attention_fn/triton_paged.py
+++ b/exllamav3/modules/attention_fn/triton_paged.py
@@ -883,7 +883,7 @@ def _qc_load_kt(qwords, scales, tok_rows, kv_head, offs_d, mask_n,
if TQ:
# TurboQuant: Lloyd-Max codebook gather, one fp16 scale (norm / ||centroids||) per head vector
sc1 = tl.load(scales + tok_rows[None, :] * n_kv_heads + kv_head, mask = mask_n[None, :], other = 0.0)
- res = (tl.load(cb + raw) * sc1.to(tl.float32)).to(tl.float16)
+ res = (tl.load(cb + raw).to(tl.float32) * sc1.to(tl.float32)).to(tl.float16)
else:
sgb = kv_head * G
garr = tl.arange(0, G_PAD)
@@ -932,7 +932,7 @@ def _qc_load_v(qwords, scales, tok_rows, kv_head, offs_d, mask_n,
raw = p if first else (raw << 1) | p
if TQ:
sc1 = tl.load(scales + tok_rows[:, None] * n_kv_heads + kv_head, mask = mask_n[:, None], other = 0.0)
- res = (tl.load(cb + raw) * sc1.to(tl.float32)).to(tl.float16)
+ res = (tl.load(cb + raw).to(tl.float32) * sc1.to(tl.float32)).to(tl.float16)
else:
sgb = kv_head * G
garr = tl.arange(0, G_PAD)
@@ -1215,6 +1215,25 @@ def _qdec_hip_decode(q, k_cache, v_cache, block_table, cache_seqlens, causal, so
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, tq is not None)
if cfg is None:
+ # A verify step with more rows than one pass of the kernel holds (accumulator budget: 4 tokens at GQA 12, hd 256) runs as
+ # row chunks, each one a smaller verify at the shifted position: the Triton split kernels cost 15-20x more at 128K
+ if q_len > 1 and kv_append_len == q_len:
+ n = next((n for n in range(q_len - 1, 0, -1) if _qh.make_cfg(n, n_q_heads, n_kv_heads, head_dim, qck, qcv, k_cache.shape[1], causal, softmax_scale,
+ window_left, window_right, softcap, n, has_sinks, ring.cfg.S if ring is not None else 0, tq is not None) is not None), 0)
+ if n:
+ if _QDEC_HIP_DEBUG: _qdec_hip_note(("hip-chunks", f"q_len {q_len} in {n}"))
+ if out is None:
+ out = torch.empty_like(q)
+ for i0 in range(0, q_len, n):
+ m = min(n, q_len - i0)
+ qc_ = q[:, i0:i0 + m].contiguous() if bsz > 1 else q[:, i0:i0 + m]
+ oc = _qdec_hip_decode(qc_, k_cache, v_cache, block_table, cache_seqlens + i0 if i0 else cache_seqlens, causal, softmax_scale, window_size,
+ softcap, sinks if has_sinks else None, None if bsz > 1 else out[:, i0:i0 + m], num_splits, max_kv_len, qc, m, n_kv_heads, ring, tq)
+ if oc is None:
+ return None
+ if bsz > 1:
+ out[:, i0:i0 + m] = oc
+ return out
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
if _QDEC_HIP_DEBUG: _qdec_hip_note(("hip", f"q_len {q_len} hd {head_dim} bits {qck},{qcv} sinks {has_sinks}"))
diff --git a/exllamav3/modules/attention_fn/triton_paged_cu.py b/exllamav3/modules/attention_fn/triton_paged_cu.py
index fa40368..1cb3fa4 100644
--- a/exllamav3/modules/attention_fn/triton_paged_cu.py
+++ b/exllamav3/modules/attention_fn/triton_paged_cu.py
@@ -800,7 +800,7 @@ def paged_attn_triton_decode_cu(
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, tq is not None)
- if tq is not None and (qcfg is None or h_blocks != 1):
+ if tq is not None and (qcfg is None or (h_blocks != 1 and not qcfg.get("rows_kernel"))):
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"):
diff --git a/exllamav3/modules/attn.py b/exllamav3/modules/attn.py
index bddd33b..7368841 100644
--- a/exllamav3/modules/attn.py
+++ b/exllamav3/modules/attn.py
@@ -1187,7 +1187,7 @@ class Attention(Module):
return o
- def bc_attn_step(self, x, cache, params, block_table, cache_seqlens, host_seqlens = None):
+ def bc_attn_step(self, x, cache, params, block_table, cache_seqlens, host_seqlens = None, kvwin_ctx = None):
"""
Graph-captured decode attention block (projections through o_proj as one C++ call,
replayed as one CUDA graph after warmup). Returns the block output, or None when the
@@ -1213,7 +1213,7 @@ class Attention(Module):
return None
return bca.step(
x, cache_seqlens, block_table, position, positions, position_ids, inv_freq,
- causal = params.get("causal", True), host_seqlens = host_seqlens
+ causal = params.get("causal", True), host_seqlens = host_seqlens, kvwin_ctx = kvwin_ctx
)
@@ -1224,7 +1224,10 @@ class Attention(Module):
return default, kwargs
from ..cache.fp16 import CacheLayer_fp16
from ..cache.quant import CacheLayer_quant
- from ..cache.qsa import CacheLayer_qsa, CacheLayer_qsa_quant
+ from ..cache.qsa import CacheLayer_qsa, CacheLayer_qsa_quant, CacheLayer_qsa_tq
+ from ..cache.tq import CacheLayer_tq
+ if issubclass(default, CacheLayer_tq):
+ return CacheLayer_qsa_tq, kwargs
if issubclass(default, CacheLayer_quant):
return CacheLayer_qsa_quant, kwargs
assert issubclass(default, CacheLayer_fp16), \
@@ -1341,7 +1344,7 @@ class Attention(Module):
bsz <= _bc_max_bsz and seqlen <= _bc_max_qlen
):
o = self.bc_attn_step(x, cache, params, block_table, cache_seqlens,
- host_seqlens = qsa_seqlens_cpu)
+ host_seqlens = qsa_seqlens_cpu, kvwin_ctx = ov)
if o is not None:
return o
@@ -1379,7 +1382,7 @@ class Attention(Module):
_sim_kvq_inplace(v, simulate_kv_quant[1], sq_ca)
if qsa_sparse:
- qsa_layer.update_kv_direct(cache_seqlens, block_table, k, v, seqlen)
+ qsa_layer.update_kv_sparse(cache_seqlens, block_table, k, v, seqlen)
if params.get("kv_only") and _kv_only_skip:
# EXL3_PF_SKIP kv_only (the MTP draft prompt prefill): K/V and the indexer planes are written, the block's
# output is discarded by the caller, so the selection, the sparse attention and everything after it are skipped.
@@ -1397,8 +1400,18 @@ class Attention(Module):
cs_host = params.get("cache_seqlens")
if isinstance(cs_host, torch.Tensor) and cs_host.device.type == "cpu" and cs_host.numel():
max_kv_len = int(cs_host.max())
+ # TurboQuant cache: the many-row kernel (cu/qdec_rows.cu) serves every row count 1..32 as one program per kv
+ # head (verified against the dequantized reference, relerr 0.7-1.9e-3), so the R verify rows run as ONE batched
+ # call like the quantized cache does through the BC graph path. The per-row loop below is a bitwise
+ # row-invariance device and costs R x the attention time (128K MTP verify: 49.3 ms/step of 98.0 vs 12.0 of
+ # 59.0 for the quant cache). EXL3_TQ_VERIFY_LOOP=1 keeps the loop.
+ tq_batch = False
+ if 1 < seqlen <= MAX_BSZN_GEMV_R and ov is None and os.environ.get("EXL3_TQ_VERIFY_LOOP", "0") == "0":
+ from ..cache import CacheLayer as _CLv
+ _lyr = cache if isinstance(cache, _CLv) else cache.layers[self.layer_idx, params.get("layer_instance") or 0]
+ tq_batch = bool(getattr(_lyr, "tq", False))
if (
- 1 < seqlen <= MAX_BSZN_GEMV_R and non_causal_spans is None and
+ 1 < seqlen <= MAX_BSZN_GEMV_R and non_causal_spans is None and not tq_batch and
os.environ.get("EXL3_VERIFY_ATTN_LOOP", "0") != "0"
):
# Row-invariant verify: the R-row paged decode tiles the KV span from the batch's single
@@ -1520,7 +1533,7 @@ class Attention(Module):
thr = self.qsa_indexer.sparse_threshold()
if all(int(qsa_cpu[b]) + seqlen > thr for b in range(bsz)):
q_idx = self.qsa_indexer.update_planes(qsa_layer, x, self.rope, block_table, qsa_cpu, params)
- qsa_layer.update_kv_direct(cache_seqlens, block_table, k, v, seqlen)
+ qsa_layer.update_kv_sparse(cache_seqlens, block_table, k, v, seqlen)
outs.append(self.qsa_indexer.sparse_attend(qsa_layer, self, q, q_idx, block_table, qsa_cpu))
bsz_loop = 0
for b in range(bsz_loop):
@@ -1533,7 +1546,7 @@ class Attention(Module):
else:
cpu_b, sparse = None, False
if sparse:
- qsa_layer.update_kv_direct(cs_b, bt_b, k[sl], v[sl], seqlen)
+ qsa_layer.update_kv_sparse(cs_b, bt_b, k[sl], v[sl], seqlen)
outs.append(self.qsa_indexer.sparse_attend_verify(qsa_layer, self, q[sl], q_idx, bt_b, cpu_b))
else:
max_kv_len = int(cpu_b.max().item()) if cpu_b is not None else None
diff --git a/exllamav3/modules/mla_attn.py b/exllamav3/modules/mla_attn.py
index 0d5ae77..38e3ae5 100644
--- a/exllamav3/modules/mla_attn.py
+++ b/exllamav3/modules/mla_attn.py
@@ -420,6 +420,9 @@ class MLAttention(Module):
# serves every path, and no cuBLAS batched GEMM is involved anywhere in the module
self.w_uk_flat = None # (kv_lora_rank, H * qk_nope_head_dim)
self.w_uv_flat = None # (kv_lora_rank, H * v_head_dim)
+ self.tq_inv_gamma = None
+ self.tq_rot_g = None
+ self.tq_state = None # TurboQuant cache: TQState whose rotation is folded into the two flats above
self._scratch = {}
@@ -428,7 +431,9 @@ class MLAttention(Module):
was constructed with. A quantized cache request maps to the packed-latent layer: k_bits
sets the latent width, the shared rope key stays fp16 (v_bits is accepted but unused -
there is no separate V)."""
- from ..cache import CacheLayer_fp16, CacheLayer_MLA_fp16, CacheLayer_quant, CacheLayer_MLA_quant
+ from ..cache import CacheLayer_fp16, CacheLayer_MLA_fp16, CacheLayer_quant, CacheLayer_MLA_quant, CacheLayer_MLA_tq
+ if getattr(default, "tq", False):
+ return CacheLayer_MLA_tq, kwargs
if issubclass(default, CacheLayer_quant):
return CacheLayer_MLA_quant, kwargs
if issubclass(default, CacheLayer_fp16):
@@ -500,6 +505,24 @@ class MLAttention(Module):
self.w_uv_flat = torch.empty((D_c, H * v), dtype = torch.half, device = device)
self.w_uv_flat.view(D_c, H, v).copy_(w[:, nope:, :].permute(2, 0, 1))
+ # TurboQuant cache: the module keeps its latent in the rotated domain end to end (cache/mla.py CacheLayer_MLA_tq): W_UK / W_UV are
+ # stored left-multiplied by R, so q_lat comes out rotated and the unfold un-rotates for free; the normalized latent is rotated once
+ # after kv_a_layernorm (_attend_pre, BC stage)
+ tqs = [bool(getattr(cl, "tq", False)) for cl in self.cache_layers]
+ assert all(tqs) or not any(tqs), "an MLA module cannot mix TurboQuant and other caches (its weights are folded for one domain)"
+ self.tq_state = None
+ if tqs and all(tqs):
+ from ..cache.tq import TQState
+ self.tq_state = TQState.get(D_c, self.cache_layers[0].k_bits, self.cache_layers[0].k_bits, device)
+ r = self.tq_state.rot32
+ # read the norm weight directly: the submodule's own tensor may still be a deferred (not yet filled) read at this point
+ g = self.config.stc.get_tensor(self.kv_a_layernorm.tensor_key, device, float2half = True, allow_bf16 = True, no_defer = True).float()
+ assert bool((g != 0).all()), "kv_a_layernorm weight has zeros: the TurboQuant fold divides by it"
+ self.tq_inv_gamma = (1.0 / g).contiguous()
+ self.tq_rot_g = (r * self.tq_inv_gamma[None, :]).t().contiguous().half() # y = R (x / gamma) as one rotation GEMM: x @ (R diag(1/gamma))^T
+ self.w_uk_flat = (r @ (g[:, None] * self.w_uk_flat.float())).half()
+ self.w_uv_flat = (r @ (g[:, None] * self.w_uv_flat.float())).half()
+
@override
def load(self, device: torch.Device, **kwargs):
@@ -515,8 +538,12 @@ class MLAttention(Module):
if self.w_uk_flat is not None:
H, nope, v = self.num_q_heads, self.qk_nope_head_dim, self.v_head_dim
D_c = self.kv_lora_rank
- uk = self.w_uk_flat.view(D_c, H, nope).permute(1, 2, 0)
- uv = self.w_uv_flat.view(D_c, H, v).permute(1, 2, 0)
+ wuk, wuv = self.w_uk_flat, self.w_uv_flat
+ if self.tq_state is not None: # undo the fold: the checkpoint layout is the natural latent domain
+ wuk = (self.tq_inv_gamma[:, None] * (self.tq_state.rot32.t() @ wuk.float())).half()
+ wuv = (self.tq_inv_gamma[:, None] * (self.tq_state.rot32.t() @ wuv.float())).half()
+ uk = wuk.view(D_c, H, nope).permute(1, 2, 0)
+ uv = wuv.view(D_c, H, v).permute(1, 2, 0)
t[f"{self.key}.{self.key_kv_b}.weight"] = \
torch.cat([uk, uv], dim = 1).reshape(H * (nope + v), D_c).contiguous()
# K-pool compression parameters are raw (unquantized) module tensors, carried as-is
@@ -536,6 +563,7 @@ class MLAttention(Module):
self.rope = None
self.w_uk_flat = None
self.w_uv_flat = None
+ self.tq_state = None
self.idx_kpool_ape = None
self.idx_kpool_gate = None
self._idx_kpool_gate_t = None
@@ -1141,6 +1169,13 @@ class MLAttention(Module):
)
k_pe = ckv_kpe[..., self.kv_lora_rank:].reshape(bsz, seqlen, 1, self.qk_rope_head_dim).contiguous()
_dbg_sync("kv_a_layernorm+slice", x.device)
+ if self.tq_state is not None:
+ # gamma-free latent n = c / gamma (gamma is folded into the weights): flat per-channel scale, much better TurboQuant KL
+ if ckv.numel() // self.kv_lora_rank > 1024: # prefill rows: one library GEMM
+ ckv = (ckv.reshape(-1, self.kv_lora_rank) @ self.tq_rot_g).view(ckv.shape)
+ else:
+ from .attention_fn.tq_triton import tq_rotate
+ ckv = tq_rotate(self.tq_rot_g, ckv)[0]
if self.rope is not None:
q_pe, k_pe = self.rope.apply(
@@ -1517,7 +1552,7 @@ class MLAttention(Module):
# Packed latent feeds the kernels directly (online dequant, rotated domain); the rope
# key pages are fp16 either way
ckv_cache, sk, kpe_cache, bits = layer.get_qc()
- qc = (sk, bits)
+ qc = (sk, bits, layer.state if getattr(layer, "tq", False) else None)
else:
ckv_cache, kpe_cache = layer.get_kv(cache_seqlens, block_table)
qc = None
diff --git a/exllamav3/modules/qsa_indexer.py b/exllamav3/modules/qsa_indexer.py
index 636255f..150c19b 100644
--- a/exllamav3/modules/qsa_indexer.py
+++ b/exllamav3/modules/qsa_indexer.py
@@ -879,6 +879,10 @@ class QSAIndexer(Module):
v_arg = layer.v.view(-1, attn.num_kv_heads, attn.head_dim)
qc, page_size = None, layer.k.shape[1]
q_rows = q.reshape(bsz * seq, attn.num_q_heads, attn.head_dim).contiguous()
+ tq = layer.get_tq() if getattr(layer, "tq", False) else None
+ if tq is not None:
+ # TurboQuant: the pool is in the rotated domain, so q goes in rotated and the output comes back through R^T
+ q_rows = tq.rotate(q_rows)
if (os.environ.get("EXL3_QSA_PF_HIP", "1") == "1" and qc is None and bsz == 1 and seq >= 64 and seq <= 4096 * 4
and (attn.num_q_heads, attn.num_kv_heads, attn.head_dim, page_size, indices.shape[1]) == (24, 2, 256, 256, 2080)
and q_rows.dtype == torch.half and k_arg.dtype == torch.half and _pf_hip_ready()):
@@ -887,7 +891,7 @@ class QSAIndexer(Module):
o = qsa_prefill_hip(q_rows, k_arg, v_arg, indices, attn.sm_scale, block_table[0].int().contiguous(), page_size)
return o.view(bsz, seq, attn.num_q_heads, attn.head_dim)
if (os.environ.get("EXL3_QSA_PF_HIP", "1") == "1" and os.environ.get("EXL3_QSA_PF_DEQ", "1") == "1" and qc is not None
- and qc[2] == 8 and qc[3] == 8 and bsz == 1 and seq >= 64 and seq <= 4096 * 4
+ and tq is None and qc[2] == 8 and qc[3] == 8 and bsz == 1 and seq >= 64 and seq <= 4096 * 4
and (attn.num_q_heads, attn.num_kv_heads, attn.head_dim, page_size, indices.shape[1]) == (24, 2, 256, 256, 2080)
and q_rows.dtype == torch.half and _pf_hip_ready()):
# stage the used pages as rotated-domain fp16 (one elementwise pass), run the proven fp16 HIP kernel on q rotated by H32/sqrt(32), rotate the output back
@@ -895,6 +899,25 @@ class QSAIndexer(Module):
n_used = (int(cache_seqlens_cpu.max().item()) + seq + page_size - 1) // page_size
o = qsa_prefill_q8(q_rows, qk, sk, qv, sv, indices, attn.sm_scale, block_table[0], n_used, page_size)
return o.view(bsz, seq, attn.num_q_heads, attn.head_dim)
+ if (os.environ.get("EXL3_QSA_PF_HIP", "1") == "1" and os.environ.get("EXL3_QSA_PF_DEQ", "1") == "1" and qc is not None
+ and tq is not None and bsz == 1 and seq >= 64 and seq <= 4096 * 4
+ and (attn.num_q_heads, attn.num_kv_heads, attn.head_dim, page_size, indices.shape[1]) == (24, 2, 256, 256, 2080)
+ and q_rows.dtype == torch.half and _pf_hip_ready()):
+ # TurboQuant prefill chunk: stage the used pages as rotated-domain fp16 (codebook lookup, one pass), run the fp16 HIP kernel
+ # on the rotated q, rotate the output back (the Triton split kernel below is ~70x slower per chunk on this shape)
+ from .attention_fn.qsa_prefill_hip import qsa_prefill_hip
+ from .attention_fn.tq_triton import tq_dequant_window
+ n_used = (int(cache_seqlens_cpu.max().item()) + seq + page_size - 1) // page_size
+ kd = torch.empty((n_used, page_size, attn.num_kv_heads, attn.head_dim), dtype = torch.half, device = q.device)
+ vd = torch.empty_like(kd)
+ bt = block_table[:, :n_used].int().contiguous()
+ sl = cache_seqlens_cpu[:1].to(device = q.device, dtype = torch.int32)
+ tq_dequant_window(qk, sk, tq.cbk, kd, sl, bt, page_size, seq, qc[2], attn.num_kv_heads, attn.head_dim)
+ tq_dequant_window(qv, sv, tq.cbv, vd, sl, bt, page_size, seq, qc[3], attn.num_kv_heads, attn.head_dim)
+ ids = torch.arange(n_used, dtype = torch.int32, device = q.device)
+ o = qsa_prefill_hip(q_rows, kd.view(-1, attn.num_kv_heads, attn.head_dim), vd.view(-1, attn.num_kv_heads, attn.head_dim),
+ indices, attn.sm_scale, ids, page_size)
+ return tq.unrotate(o).view(bsz, seq, attn.num_q_heads, attn.head_dim)
# Built only for the Triton fallback: the HIP paths above read block_table[0], and this copy is
# rows x pages x 4 B (33 MB per layer per 4096-row chunk at -c 524288) written for nothing
bt_rows = block_table.int().unsqueeze(1).expand(bsz, seq, -1) \
@@ -903,8 +926,10 @@ class QSAIndexer(Module):
q_rows,
k_arg, v_arg, indices, attn.sm_scale,
block_table = bt_rows, page_size = page_size,
- qc = qc, n_kv_heads = attn.num_kv_heads,
+ qc = qc, n_kv_heads = attn.num_kv_heads, tq = tq,
)
+ if tq is not None:
+ o = tq.unrotate(o)
return o.view(bsz, seq, attn.num_q_heads, attn.head_dim)
def sparse_attend_verify(self, layer, attn, q, q_idx, block_table, cache_seqlens_cpu) -> torch.Tensor:
diff --git a/exllamav3/version.py b/exllamav3/version.py
index 5228a4c..e1b4f0f 100644
--- a/exllamav3/version.py
+++ b/exllamav3/version.py
@@ -1 +1 @@
-__version__ = "1.8.2"
\ No newline at end of file
+__version__ = "1.8.3"
\ No newline at end of file
diff --git a/tests/test_mla.py b/tests/test_mla.py
index bc30d50..70aa22a 100644
--- a/tests/test_mla.py
+++ b/tests/test_mla.py
@@ -68,7 +68,7 @@ class FakeConfig:
def build(H = 8, hidden = 1024, kv_lora = 512, nope = 128, rope_dim = 64, v_head = 128,
- q_lora = None, nope_only = False, seed = 0, wscale = 0.085):
+ q_lora = None, nope_only = False, seed = 0, wscale = 0.085, pre_load = None):
"""Random-weight MLAttention plus the raw weights, for the reference forward.
wscale is chosen so pre-softmax scores land around unit standard deviation. The q and k paths
@@ -105,6 +105,7 @@ def build(H = 8, hidden = 1024, kv_lora = 512, nope = 128, rope_dim = 64, v_head
qk_rope_head_dim = rope_dim, v_head_dim = v_head, rope_settings = rope_settings,
q_lora_rank = q_lora, rms_norm_eps = 1e-6,
)
+ if pre_load: pre_load(module)
module.load(torch.device(device))
return module, {k: v.to(device) for k, v in t.items()}, key
@@ -585,7 +586,7 @@ def test_mla_gather_tile(bits):
out_r = torch.empty((e - a, D_r), dtype = torch.half, device = dev)
_mla_gather_tile_kernel[(triton.cdiv(e - a, 64),)](
ck, kp, sk, h32, bt, out_c, out_r, a, e - a, npages, 0,
- qbits, PS, D_c, D_r, 64, num_warps = 4, num_stages = 2,
+ qbits, 0, PS, D_c, D_r, 64, num_warps = 4, num_stages = 2,
)
err_c = (out_c.float() - want[a:e].float()).abs().max().item()
err_r = (out_r.float() - kpe_rows[0, a:e].float()).abs().max().item()
@@ -602,3 +603,30 @@ def test_mla_kv_b_export_roundtrip():
want = t[f"{key}.kv_b_proj.weight"]
assert got.shape == want.shape
assert torch.equal(got.cpu().half(), want.cpu().half()), "kv_b reconstruction differs"
+
+
+# ---- TurboQuant latent cache ---------------------------------------------------------------
+
+def _tq_pair(bits, **kw):
+ from exllamav3.cache import CacheLayer_MLA_tq
+ holder = {}
+ def pre(m):
+ holder["l"] = CacheLayer_MLA_tq(None, m, 0, 4 * PAGE_SIZE * 2, k_bits = bits)
+ module, t, key = build(pre_load = pre, **kw)
+ holder["l"].alloc(torch.device(device))
+ return module, t, key, holder["l"]
+
+
[email protected]("nope_only,geom", [(True, {}), (False, {}), (True, dict(rope_dim = 0, nope = 256, v_head = 256))])
[email protected]("bits", [6, 5])
+def test_mla_tq_cache_vs_reference(bits, nope_only, geom):
+ """TurboQuant latent cache (rotation + gamma folded into the weights) tracks the exact reference."""
+ module, t, key, layer = _tq_pair(bits, H = 8, q_lora = 256, seed = 31, nope_only = nope_only, **geom)
+ bsz, S = 2, 300
+ x = (torch.randn((bsz, S, module.hidden_size), device = device) * 0.5).half()
+ bt = torch.arange(4 * bsz, dtype = torch.int32, device = device).view(bsz, 4)
+ ref = ref_forward(module, t, key, x, torch.zeros((bsz,), dtype = torch.int32, device = device))
+ out = run_module(module, x, layer, bt)
+ outd = run_module(module, x, _tq_pair(bits, H = 8, q_lora = 256, seed = 31, nope_only = nope_only, **geom)[3], bt, chunk = 1)
+ print(f" tq{bits} vs reference: prefill {rel_err(out, ref):.3e} decode {rel_err(outd, ref):.3e}")
+ assert rel_err(out, ref) < 1e-1 and rel_err(outd, ref) < 1e-1
diff --git a/tests/test_mla_dsa.py b/tests/test_mla_dsa.py
index d8abec8..de297be 100644
--- a/tests/test_mla_dsa.py
+++ b/tests/test_mla_dsa.py
@@ -33,7 +33,7 @@ device = "cuda:0"
def build_dsa(H = 8, hidden = 512, kv_lora = 512, nope = 128, rope_dim = 64, v_head = 128,
q_lora = 256, idx_heads = 4, idx_dim = 128, topk = 64, mode = "full",
- seed = 0, wscale = 0.085):
+ seed = 0, wscale = 0.085, pre_load = None):
g = torch.Generator(device = "cpu").manual_seed(seed)
def rnd(*shape, scale = wscale):
@@ -70,6 +70,7 @@ def build_dsa(H = 8, hidden = 512, kv_lora = 512, nope = 128, rope_dim = 64, v_h
indexer_mode = mode, index_n_heads = idx_heads, index_head_dim = idx_dim,
index_topk = topk,
)
+ if pre_load: pre_load(module)
module.load(torch.device(device))
return module, {k: v.to(device) for k, v in t.items()}, key
@@ -435,3 +436,44 @@ def test_dsa_cached_quant_decode(bits):
tol = {8: 6e-3, 4: 2.5e-2}[bits]
e = rel_err(out, ref[:, prefill:])
assert e < tol, f"rel err {e:.3e} (tol {tol})"
+
+
[email protected]("bits", [6])
+def test_dsa_tq_cache_matches_fp16(bits):
+ """TurboQuant latent cache over a sparse (DSA) context: prefill chunks then single-token decode steps track the fp16 cache, and the
+ selected indices are the same (indexer planes are computed from the hidden state, never from the rotated latent)."""
+ from exllamav3.cache import CacheLayer_MLA_tq, CacheLayer_MLA_fp16
+ S, chunk, topk = 384, 128, 64
+ bsz = 1
+ x = None
+ res = {}
+ for name in ("fp16", "q", "tq"):
+ holder = {}
+ def pre(m):
+ if name == "tq":
+ holder["l"] = CacheLayer_MLA_tq(None, m, 0, 4 * PAGE_SIZE * bsz, k_bits = bits)
+ elif name == "q":
+ holder["l"] = CacheLayer_MLA_quant(None, m, 0, 4 * PAGE_SIZE * bsz, k_bits = bits)
+ else:
+ holder["l"] = CacheLayer_MLA_fp16(None, m, 0, 4 * PAGE_SIZE * bsz)
+ module, t, key = build_dsa(topk = topk, seed = 47, pre_load = pre)
+ layer = holder["l"]
+ layer.alloc(torch.device(device))
+ if x is None:
+ x = (torch.randn((bsz, S, module.hidden_size), device = device) * 0.5).half()
+ bt = torch.arange(4 * bsz, dtype = torch.int32, device = device).view(bsz, 4)
+ seqlens = torch.zeros((bsz,), dtype = torch.int32, device = device)
+ outs, idxs = [], []
+ pre_n = S - 16
+ for a, b in [(i, min(i + chunk, pre_n)) for i in range(0, pre_n, chunk)] + [(i, i + 1) for i in range(pre_n, S)]:
+ params = {"attn_mode": "flash_attn", "cache": layer, "block_table": bt, "cache_seqlens": seqlens, "positions": seqlens.clone()}
+ outs.append(module.forward(x[:, a:b].contiguous(), params))
+ idxs.append(params["dsa_topk_indices"].clone())
+ seqlens = seqlens + (b - a)
+ res[name] = (outs, idxs)
+ for i, (a, b) in enumerate(zip(res["tq"][0], res["fp16"][0])):
+ e = rel_err(a, b)
+ eq = rel_err(res["q"][0][i], b)
+ same = bool((res["tq"][1][i] == res["fp16"][1][i]).all())
+ print(f" step {i}: tq {e:.3e} quant {eq:.3e} same_idx {same}")
+ assert e < 8e-2, f"step {i}: rel err {e:.3e}"
diff --git a/tests/test_tq_cache.py b/tests/test_tq_cache.py
index 74a8c57..235031e 100644
--- a/tests/test_tq_cache.py
+++ b/tests/test_tq_cache.py
@@ -84,12 +84,26 @@ def test_triton_write_and_window_dequant_exact(D, bits):
tok = cs.long().unsqueeze(1) + torch.arange(length, device = DEV).unsqueeze(0)
rows = (bt.long().gather(1, tok // PAGE) * PAGE + tok % PAGE).reshape(-1)
wr, sr = tq.encode_ref(x.reshape(-1, D), st.cbk, st.midk, bits)
- assert torch.equal(words.view(-1, words.shape[-1])[rows], wr.view(rows.numel(), -1))
- assert torch.equal(sc.view(-1, HKV)[rows], sr.view(rows.numel(), -1))
+ wk = words.view(-1, words.shape[-1])[rows].reshape(-1, D // 32 * bits)
+ sk = sc.view(-1, HKV)[rows].reshape(-1)
+ # The kernel sums the squared norms in its own order, the reference in torch's: the fp32 norms differ in the last bit. A
+ # coordinate whose unit value sits within ~1e-6 of a midpoint may then take the neighbouring code, and the fp16 scale may land
+ # one step apart (together about 1 in 100 draws). Everything else must be exact.
+ from exllamav3.ext_fallbacks import _unpack_cache_codes
+ ck, cr = [_unpack_cache_codes(w.view(-1, D // 32, bits).to(torch.int64) & 0xffffffff, bits).reshape(-1, D) for w in (wk, wr)]
+ bad = ck != cr
+ if bad.any():
+ assert (ck - cr).abs().max() == 1
+ u = x.reshape(-1, D).float() / x.reshape(-1, D).float().norm(dim = -1, keepdim = True)
+ lo = torch.minimum(ck, cr).clamp_max(st.midk.numel() - 1)
+ assert (u[bad] - st.midk[lo[bad]]).abs().max() < 1e-6
+ nrm = x.reshape(-1, D).float().norm(dim = -1)
+ sc_k = (nrm / st.cbk[ck].norm(dim = -1)).to(torch.float16) # scale the kernel's own codes call for
+ assert (sk.view(torch.int16).int() - sc_k.view(torch.int16).int()).abs().max() <= 1
npps = bt.shape[1]
out = torch.zeros(bsz * npps, PAGE, HKV, D, dtype = torch.half, device = DEV)
T._tq_dequant_window_kernel[(bsz * npps * (PAGE // 16), HKV)](words, sc, st.cbk, out, bt, cs, length, npps, bits, PAGE, HKV, D, 16)
- ref = tq.decode_ref(wr, sr, st.cbk, bits, D)
+ ref = tq.decode_ref(wk, sk, st.cbk, bits, D) # the dequant is exact given the stored codes and scales
got = torch.stack([out[b * npps + int(tok[b, t]) // PAGE, int(tok[b, t]) % PAGE] for b in range(bsz) for t in range(length)]).reshape(ref.shape)
assert torch.equal(got, ref)
@@ -159,6 +173,32 @@ def test_dispatch_matches_dequantized_reference(hd, bits):
assert err < 6e-3, (hd, bits, n, L, err)
+@needs_gpu
[email protected]("bits", [5, 6])
+def test_verify_rows_beyond_one_pass_match_reference(bits):
+ """GQA 12 at head_dim 256: a verify step of more than 4 tokens does not fit one qdec_hip pass and runs as row chunks (ring included)"""
+ rig = Rig(bits, hd = 256, kvh = 2, qh = 24, pages = 8)
+ for n in (700, 1, 6, 8, 5, 3, 7):
+ q, o, L = rig.step(n)
+ r = rig.ref(q, L)
+ err = ((o.float() - r).norm() / r.norm()).item()
+ assert err < 6e-3, (bits, n, L, err)
+
+
+@needs_gpu
[email protected]("hd,kvh,qh,bits", [(128, 2, 8, 6), (128, 2, 16, 5), (256, 4, 24, 6), (256, 2, 8, 5)])
+def test_verify_rows_1_to_32_match_reference(hd, kvh, qh, bits):
+ """Spec / MTP verify steps and parallel-user rows: every row count 1..32 (rows = n x GQA group per kv head, 1..192) agrees with the
+ dequantized reference, whichever qdec kernel (qdec.cu, the many-row kernel) or Triton fallback serves it."""
+ rig = Rig(bits, hd = hd, kvh = kvh, qh = qh, pages = 6)
+ rig.step(600)
+ for n in range(1, 33):
+ q, o, L = rig.step(n)
+ r = rig.ref(q, L)
+ err = ((o.float() - r).norm() / r.norm()).item()
+ assert err < 6e-3, (hd, kvh, qh, bits, n, L, err)
+
+
@needs_gpu
@pytest.mark.parametrize("D", [128, 256])
def test_fused_rotation_matches_gemm(D):
diff --git a/tools/bench_kv_attn.py b/tools/bench_kv_attn.py
new file mode 100644
index 0000000..67425d0
--- /dev/null
+++ b/tools/bench_kv_attn.py
@@ -0,0 +1,90 @@
+"""Per-layer KV attention microbench: quant k6v6 / kw6 (k6v6 + sink/window ring) / tq6 through attn_dispatch, like the attention module drives it.
+usage: python tools/bench_kv_attn.py [--hd 256 --kvh 2 --qh 24] [--ctx 8192,131072] [--rows 1,2,3,4,5,8] [--modes k6v6,kw6,tq6]
+Prints ms per call (median) for decode / verify rows at each context, plus the prefill-chunk KV write cost (rotate + quantize/write)."""
+import os, sys, types, time, argparse
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
+import torch
+from exllamav3.cache.quant import CacheLayer_quant
+from exllamav3.cache.tq import CacheLayer_tq
+from exllamav3.cache.kvwin import KVWinLayerState, KVWinCtx, KVWinCfg
+from exllamav3.modules.attention_fn.dispatch import attn_dispatch
+
+ap = argparse.ArgumentParser()
+ap.add_argument("--hd", type=int, default=256); ap.add_argument("--kvh", type=int, default=2); ap.add_argument("--qh", type=int, default=24)
+ap.add_argument("--bits", type=int, default=6)
+ap.add_argument("--ctx", default="8192,131072"); ap.add_argument("--rows", default="1,2,3,4,5,8"); ap.add_argument("--modes", default="k6v6,kw6,tq6")
+ap.add_argument("--prof", type=int, default=0, help="rows T to profile (kernel breakdown)")
+ap.add_argument("--reps", type=int, default=40); ap.add_argument("--S", type=int, default=4); ap.add_argument("--W", type=int, default=128)
+a = ap.parse_args()
+DEV = "cuda:0"
+PAGE = 256
+
+def med(f, reps):
+ for _ in range(3): f()
+ torch.cuda.synchronize()
+ ts = []
+ for _ in range(reps):
+ e0, e1 = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
+ e0.record(); f(); e1.record(); torch.cuda.synchronize(); ts.append(e0.elapsed_time(e1))
+ ts.sort(); return ts[len(ts) // 2]
+
+def build(mode, ctx):
+ attn = types.SimpleNamespace(num_kv_heads=a.kvh, head_dim=a.hd, window_arg=lambda: -1, logit_softcapping=0.0)
+ pages = (ctx + 64) // PAGE + 2
+ cls = CacheLayer_tq if mode.startswith("tq") else CacheLayer_quant
+ cl = cls(None, attn, 0, pages * PAGE, a.bits, a.bits); cl.alloc(torch.device(DEV))
+ ring = None
+ if mode != "k6v6":
+ st = KVWinLayerState(attn, 2, 0, 0); st.cfg = KVWinCfg(a.S, a.W, a.W + 16, a.S + a.W + 16); st.cache_layer = cl; st.alloc(torch.device(DEV))
+ ring = KVWinCtx(st, torch.tensor([1], dtype=torch.int32, device=DEV))
+ bt = torch.arange(pages, dtype=torch.int32, device=DEV).view(1, -1)
+ return cl, ring, bt
+
+g = torch.Generator(device=DEV).manual_seed(0)
+def rnd(*s): return (torch.randn(*s, device=DEV, generator=g) * (0.5 + torch.rand(*s[:-1], 1, device=DEV, generator=g) * 2)).half()
+
+print(f"hd {a.hd} kvh {a.kvh} qh {a.qh} bits {a.bits} ring {a.S}:{a.W} (ms per layer call)")
+for ctx in map(int, a.ctx.split(",")):
+ for mode in a.modes.split(","):
+ cl, ring, bt = build(mode, ctx)
+ L = 0
+ while L < ctx: # fill the pool by staged prefill chunks
+ n = min(2048, ctx - L)
+ sl = torch.tensor([L], dtype=torch.int32, device=DEV)
+ attn_dispatch(rnd(1, n, a.qh, a.hd), rnd(1, n, a.kvh, a.hd), rnd(1, n, a.kvh, a.hd), cache=cl, causal=True, block_table=bt,
+ cache_seqlens=sl, max_kv_len=L, ov=ring)
+ L += n
+ out = []
+ for T in map(int, a.rows.split(",")):
+ q, k, v = rnd(1, T, a.qh, a.hd), rnd(1, T, a.kvh, a.hd), rnd(1, T, a.kvh, a.hd)
+ sl = torch.tensor([ctx - T], dtype=torch.int32, device=DEV)
+ f = lambda: attn_dispatch(q, k, v, cache=cl, causal=True, block_table=bt, cache_seqlens=sl, max_kv_len=ctx - T, ov=ring)
+ out.append(f"T{T} {med(f, a.reps):.3f}")
+ if a.prof:
+ from torch.profiler import profile, ProfilerActivity
+ T = a.prof
+ q, k, v = rnd(1, T, a.qh, a.hd), rnd(1, T, a.kvh, a.hd), rnd(1, T, a.kvh, a.hd)
+ sl = torch.tensor([ctx - T], dtype=torch.int32, device=DEV)
+ f = lambda: attn_dispatch(q, k, v, cache=cl, causal=True, block_table=bt, cache_seqlens=sl, max_kv_len=ctx - T, ov=ring)
+ for _ in range(5): f()
+ torch.cuda.synchronize()
+ with profile(activities=[ProfilerActivity.CUDA]) as pr:
+ for _ in range(20): f()
+ torch.cuda.synchronize()
+ tot = 0
+ for e in pr.key_averages():
+ dt = getattr(e, "device_time_total", 0) or getattr(e, "cuda_time_total", 0) or getattr(e, "self_device_time_total", 0)
+ if dt > 0:
+ print(f" {mode} T{T}: {e.key[:60]:60s} {dt / 20:8.1f} us/call x{e.count // 20}"); tot += dt / 20
+ print(f" {mode} T{T}: GPU total {tot:.1f} us")
+ # prefill KV write: rotate (tq) + quantize into the pool, 2048-row chunk
+ k2, v2 = rnd(1, 2048, a.kvh, a.hd), rnd(1, 2048, a.kvh, a.hd)
+ sl2 = torch.tensor([ctx - 2048], dtype=torch.int32, device=DEV)
+ def w():
+ kk, vv = k2, v2
+ if getattr(cl, "tq", False):
+ _, kk, vv = cl.get_tq().rotate(k2, k2, v2)
+ cl.update_kv_direct(sl2, bt, kk, vv, 2048)
+ out.append(f"write2048 {med(w, 20):.3f}")
+ print(f"ctx {ctx:>7} {mode:>5}: " + " ".join(out), flush=True)
+ del cl, ring; torch.cuda.empty_cache()
diff --git a/tools/depth/depth_profile.py b/tools/depth/depth_profile.py
index 1597a8b..d704423 100755
--- a/tools/depth/depth_profile.py
+++ b/tools/depth/depth_profile.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python
"""In-process depth profiler: per-step cost vs context depth in minutes, no real prefill.
- tools/depth/depth_profile.py MODEL_DIR --serve glm|qwen -o out.json [--depths 8192,...] [--cache-bits 16|8]
+ tools/depth/depth_profile.py MODEL_DIR --serve glm|qwen -o out.json [--depths 8192,...] [--cache-bits 16|8] [--kv-mode quant|tq]
[--ndt 2] [--chunk 4096] [--reps 3] [--kernels] [--no-prefill] [--no-decode]
Loads the model once with the SERVED environment (the SERVE_ENV / SPEED_ENV tables of tools/{qwen,glm}/serve.py,
@@ -48,6 +48,7 @@ def _main():
ap.add_argument("-o", "--out", required=True)
ap.add_argument("--depths", default="8192,32768,65536,131072,262144,500000")
ap.add_argument("--cache-bits", type=int, default=16)
+ ap.add_argument("--kv-mode", choices=["quant", "tq"], default="quant", help="tq: TurboQuant pages (the served default) at --cache-bits 4..6")
ap.add_argument("--ndt", type=int, default=2, help="drafted tokens: verify step = ndt + 1 rows")
ap.add_argument("--chunk", type=int, default=int(os.environ.get("EXL3_PREFILL_CHUNK", "4096")))
ap.add_argument("--steps", type=int, default=12)
@@ -91,6 +92,9 @@ def _main():
config = Config.from_directory(args.model)
model = Model.from_config(config)
qkw = dict(layer_type=CacheLayer_quant, k_bits=args.cache_bits, v_bits=args.cache_bits) if args.cache_bits < 16 else {}
+ if args.kv_mode == "tq" and args.cache_bits < 16:
+ from exllamav3.cache.tq import CacheLayer_tq
+ qkw["layer_type"] = CacheLayer_tq
cache = Cache(model, max_num_tokens=cap, max_history=max(3, R), max_batch_size=1, **qkw)
model.load(device="cuda:0", progressbar=False)
RES["load_s"] = round(time.time() - t0, 1)
diff --git a/tools/glm/serve.py b/tools/glm/serve.py
index 8be9a2f..514e5ea 100644
--- a/tools/glm/serve.py
+++ b/tools/glm/serve.py
@@ -642,7 +642,7 @@ class ResidentEngine:
row_budget = 0
def __init__(self, model_path: str, max_history: int = 1, max_ctx: int = 131072, num_draft: int = 1,
- vision: bool = True, sessions: int = 1, cache_bits: int = 0,
+ vision: bool = True, sessions: int = 1, cache_bits: int = 0, kv_mode: str = "quant",
image_cache_bytes: int | None = None, image_cache_items: int = 0,
image_cache_format: str = "fp32",
image_cache_dir: str | None = IMAGE_CACHE_DIR_DEFAULT,
@@ -689,6 +689,13 @@ class ResidentEngine:
# indexer and k-pool planes and the rope key stay fp16, so the saving is smaller than the latent-only ratio.
from exllamav3 import CacheLayer_quant
qkw = dict(layer_type=CacheLayer_quant, k_bits=cache_bits, v_bits=cache_bits) if cache_bits else {}
+ if kv_mode == "tq" and cache_bits:
+ # TurboQuant latent (rotated, gamma-folded; see cache/mla.py CacheLayer_MLA_tq): k{bits} over the 512-wide latent
+ from exllamav3.cache.tq import CacheLayer_tq, supported as tq_supported
+ if tq_supported(512, cache_bits):
+ qkw["layer_type"] = CacheLayer_tq
+ else:
+ print(f"serve: kv-mode tq: no TurboQuant codebook for the {cache_bits}-bit latent, keeping the quant cache", flush=True)
slots = max(sessions, int(os.environ.get("EXL3_GLM_SLOTS", "0") or 0))
# GLM_NGRAM = "gram,K,match[,cmin]": n-gram lookup of tools/qwen/spec_policy.install_lookup. When the
# last `match` tokens occurred before, the round verifies the K tokens that followed them instead of the drafter's
@@ -2082,9 +2089,12 @@ def main() -> None:
parser.add_argument("--sessions", type=int, default=1,
help=f"requests decoded together through the one Generator (1..{MAX_SESSIONS}); default 1 = one request at a time. "
"The KV pool (-c) is shared by all sessions")
+ parser.add_argument("--kv-mode", choices=("tq", "quant", "fp16"), default="tq",
+ help="latent cache format. tq (default): TurboQuant, rotated Lloyd-Max codes + one scale per token, 6 bits unless --cache-bits says otherwise "
+ "(KL below the quant cache, same decode speed); quant: packed per-32 group scales (--cache-bits 4/5/6/8, 8 if none given); fp16: the unpacked 16-bit pages")
parser.add_argument("-c", "--max-ctx", type=int, default=131072, help="context window (capped by max_position_embeddings)")
- parser.add_argument("--cache-bits", type=int, default=0, choices=(0, 8),
- help="bits per element of the MLA latent cache pages (0 = fp16, the default; 8 = packed int8; the DSA "
+ parser.add_argument("--cache-bits", type=int, default=None, choices=(0, 4, 5, 6, 8),
+ help="bits per element of the MLA latent cache pages (default: 6 with --kv-mode tq, else 0; 0 = fp16; 8 = packed int8; the DSA "
"indexer and k-pool planes and the rope key stay fp16; output differs token-wise from fp16; slot "
"files do not cross cache modes, and a cross-mode restore is rejected)")
parser.add_argument("--image-cache-mb", type=int, default=IMAGE_CACHE_MB_DEFAULT,
@@ -2124,14 +2134,26 @@ def main() -> None:
parser.add_argument("--default-reasoning-effort", choices=("low", "medium", "high", "max"), default=None,
help="thinking effort when a request omits it (default: medium)")
args = parser.parse_args()
+ if args.kv_mode == "fp16":
+ args.cache_bits = 0
+ elif args.cache_bits is None:
+ args.cache_bits = 6 if args.kv_mode == "tq" else 8 # default cache: TurboQuant 6-bit latent; --kv-mode quant alone = the packed int8 pages
if not 1 <= args.sessions <= MAX_SESSIONS:
parser.error(f"--sessions must be 1..{MAX_SESSIONS}")
if args.sessions > 1:
+ # chunked prefill beside decoding users (EXL3_SCHED_CHUNK_IL, generator/chunk_il.py): a big prefill runs one
+ # short chunk per step and shares the step with the decode round of every running session. Default on for
+ # multi-session ROCm serving (measured on gfx1151); EXL3_SCHED_CHUNK_IL=0 restores FIFO prefills.
+ import torch as _torch
+ if _torch.version.hip:
+ os.environ.setdefault("EXL3_SCHED_CHUNK_IL", "1")
+ os.environ.setdefault("EXL3_CIL_DECODE_PRIO", "1")
+ os.environ.setdefault("EXL3_CIL_SLICE_S", "0.35")
print(f"serve: --sessions {args.sessions}: up to {args.sessions} requests share the KV pool of -c {args.max_ctx} "
f"(per-session window = -c / sessions when all are busy); greedy output is not guaranteed equal to the same "
f"request run alone; slot save/restore waits for every running request and acts on the last prompt noted",
file=sys.stderr, flush=True)
- if args.cache_bits and args.sessions > 1:
+ if args.cache_bits and args.sessions > 1 and args.kv_mode != "tq":
print(f"serve: --cache-bits {args.cache_bits} with --sessions {args.sessions}: the packed int8 MLA pages are not "
f"row-invariant, so batched decode changes greedy output versus a single session (the rows still agree with "
f"each other). Slot files also do not cross cache modes.", file=sys.stderr, flush=True)
@@ -2167,7 +2189,7 @@ def main() -> None:
image_cache_size = (f"{args.image_cache_mb} MiB of host memory (--image-cache-mb)" if image_cache_bytes
else "no byte limit (--image-cache-mb 0)")
engine = ResidentEngine(args.model, max_history=args.max_history or max(args.num_draft, 1), max_ctx=args.max_ctx, num_draft=args.num_draft,
- vision=not args.no_vision, sessions=args.sessions, cache_bits=args.cache_bits,
+ vision=not args.no_vision, sessions=args.sessions, cache_bits=args.cache_bits, kv_mode=args.kv_mode,
image_cache_bytes=image_cache_bytes, image_cache_items=args.image_cache_items,
image_cache_format=args.image_cache_format,
image_cache_dir=args.image_cache_dir, image_cache_dir_max_gb=args.image_cache_dir_max_gb,
@@ -2176,7 +2198,7 @@ def main() -> None:
template = Path(args.chat_template or DEFAULT_TEMPLATE).expanduser().read_text(encoding="utf-8")
print(mem_line("loaded"), flush=True)
print(f"serve: vision={engine.supports_vision}", flush=True)
- print(f"serve: cache={'int' + str(args.cache_bits) + ' (slot files do not cross cache modes)' if args.cache_bits else 'fp16'}", flush=True)
+ print(f"serve: cache={args.kv_mode + str(args.cache_bits) + ' (slot files do not cross cache modes)' if args.cache_bits else 'fp16'}", flush=True)
print(f"serve: image cache {image_cache_size}, {'no count cap' if not engine.emb_cache.max_items else str(engine.emb_cache.max_items) + ' pictures max'}, "
f"{args.image_cache_format} rows, {engine.emb_cache.policy} policy, shared by {args.sessions} session(s)", flush=True)
if engine.emb_disk is not None:
diff --git a/tools/glm/tq_layer_dbg.py b/tools/glm/tq_layer_dbg.py
new file mode 100644
index 0000000..75730e4
--- /dev/null
+++ b/tools/glm/tq_layer_dbg.py
@@ -0,0 +1,85 @@
+"""Per-layer MLA attention outputs of one short prefill, fp16 vs tq cache (separate processes: a module cannot mix cache kinds).
+ tq_layer_dbg.py PACK DOCS.pt OUT.pt MODE(fp16|tq6) [N_TOKENS] [CHUNK]"""
+import sys
+import torch
+
+
+def main(pack, docs, out, mode, n=256, chunk=0):
+ from exllamav3 import Cache, CacheLayer_quant, Config, Model
+ from exllamav3.cache.tq import CacheLayer_tq
+ from exllamav3.modules.mla_attn import MLAttention
+ ids = torch.load(docs)["ids"][0][:n]
+ m = Model.from_config(Config.from_directory(pack))
+ kw = dict(max_num_tokens=(n + 255) // 256 * 256 + 256, max_batch_size=2, max_history=3)
+ cache = Cache(m, **kw) if mode == "fp16" else Cache(m, layer_type=CacheLayer_tq, k_bits=int(mode[2:]), v_bits=int(mode[2:]), **kw)
+ m.load(progressbar=False)
+ rec = []
+ orig = MLAttention.forward
+ saved = {}
+ from exllamav3.cache.tq import TQState
+ ro = TQState.rotate
+ cnt = [0]
+
+ def rot(self, *xs):
+ y = ro(self, *xs)
+ if cnt[0] < 3 and xs[0].shape[-1] == 512:
+ cnt[0] += 1
+ x0 = xs[0].float()
+ print("rotate in finite", bool(torch.isfinite(x0).all()), "max", x0.abs().max().item(), "out finite", bool(torch.isfinite(y.float()).all()), "rot_t", self.rot_t.dtype, bool(torch.isfinite(self.rot_t.float()).all()), flush=True)
+ return y
+ TQState.rotate = rot
+ if mode != "fp16":
+ from exllamav3.cache.mla import CacheLayer_MLA_tq
+ uo = CacheLayer_MLA_tq.update_kv_direct
+
+ def ukd(self, cache_seqlens, block_table, k, v, length):
+ saved.setdefault(id(self), []).append((int(cache_seqlens[0]), k.detach().clone()))
+ return uo(self, cache_seqlens, block_table, k, v, length)
+ CacheLayer_MLA_tq.update_kv_direct = ukd
+
+ def fwd(self, x, params, out_dtype=None):
+ o = orig(self, x, params, out_dtype) if out_dtype is not None else orig(self, x, params)
+ rec.append((self.key, o.detach().float().cpu()))
+ return o
+ MLAttention.forward = fwd
+ x = torch.tensor([ids])
+ bt = torch.arange((n + 256) // 256, dtype=torch.int32)[None]
+ chunk = chunk or n
+ with torch.inference_mode():
+ for a in range(0, n, chunk):
+ b = min(a + chunk, n)
+ m.prefill(x[:, a:b], {"attn_mode": "flash_attn", "cache": cache, "block_table": bt[:, : (b + 255) // 256],
+ "cache_seqlens": torch.tensor([a], dtype=torch.int32)})
+ if saved:
+ from exllamav3.modules.attention_fn.tq_triton import tq_dequant_rows
+ for lid, lst in list(saved.items())[:3]:
+ layer = [l for l in cache.layers.values() if id(l) == lid][0]
+ pg = torch.arange(len(lst) and 8, dtype=torch.int64, device=layer.qk.device)
+ G = 512 // 32
+ rows = sum(k.shape[1] for _, k in lst)
+ n_pg = (rows + 255) // 256
+ pc = layer.qk.reshape(-1, 256, G * layer.bits)[:n_pg].reshape(-1, G * layer.bits)
+ ps = layer.sk.reshape(-1, 256)[:n_pg].reshape(-1)
+ o = torch.empty((pc.shape[0], 512), dtype=torch.half, device=pc.device)
+ tq_dequant_rows(pc, ps, layer.state.cbk, o, layer.bits, 512)
+ ref = torch.cat([k.reshape(-1, 512) for _, k in lst]).float()
+ d = o[: ref.shape[0]].float()
+ bad = ~torch.isfinite(ref).all(-1); print("nan rows", int(bad.sum()), "of", ref.shape[0], "first", int(bad.nonzero()[0]) if bad.any() else -1, "chunks", [(a, tuple(k.shape)) for a, k in lst][:3]); ref = ref[~bad]; d = d[~bad]
+ print("roundtrip", lid, "rel", ((d - ref).norm() / ref.norm()).item(), "|ref|", ref.norm(dim=-1).mean().item(), "|dq|", d.norm(dim=-1).mean().item(), flush=True)
+ torch.save(rec, out)
+ print("saved", len(rec), flush=True)
+
+
+def cmp(a, b):
+ ra, rb = torch.load(a), torch.load(b)
+ for (k, x), (_, y) in zip(ra, rb):
+ e = ((x - y).abs().max() / y.abs().max().clamp_min(1e-6)).item()
+ print(k, f"rel {e:.3e}", f"|ref| {y.abs().max().item():.3g}")
+
+
+if __name__ == "__main__":
+ if sys.argv[1] == "cmp":
+ cmp(*sys.argv[2:4])
+ else:
+ a = sys.argv
+ main(a[1], a[2], a[3], a[4], int(a[5]) if len(a) > 5 else 256, int(a[6]) if len(a) > 6 else 0)
diff --git a/tools/glm/tq_mla_kl.py b/tools/glm/tq_mla_kl.py
new file mode 100644
index 0000000..5470f46
--- /dev/null
+++ b/tools/glm/tq_mla_kl.py
@@ -0,0 +1,149 @@
+"""Decode-faithful KL of MLA latent cache formats on one GLM pack, one model load.
+
+ tq_mla_kl.py PACK DOCS.pt OUT.json [N_PREFIX] [N_DECODE] [formats...]
+
+Formats: fp16 (reference), k8 / k6 / k5 (CacheLayer_MLA_quant), fq_tq6 / fq_tq5 (fake TurboQuant: rotate, Lloyd-Max encode, decode,
+un-rotate, store fp16: exact TurboQuant numerics with no kernel), tq6 / tq5 (CacheLayer_MLA_tq, the real layer).
+All caches are attached before the load; the prefix is prefilled into each in 2048-row chunks, then N_DECODE teacher-forced decode
+steps run through the engine's decode path. KL is against the fp16 cache's log-probs.
+Run with EXL3_BC_ATTN=0 for the fake formats (the graph path appends through its own kernel and bypasses update_kv_direct)."""
+import gc
+import json
+import os
+import sys
+import time
+
+import torch
+
+
+def fake_tq(bits, blocks=1, gamma=False):
+ from exllamav3.cache import CacheLayer_MLA_fp16, CacheLayer_fp16
+ from exllamav3.modules.mla_attn import MLAttention
+ orig = MLAttention.cache_layer_type
+ if not getattr(orig, 'patched', False):
+ def clt(self, default, kwargs):
+ mc = getattr(default, 'mla_cls', None)
+ return (mc, {}) if mc else orig(self, default, kwargs)
+ clt.patched = True
+ MLAttention.cache_layer_type = clt
+ from exllamav3.cache.tq import TQState, encode_ref, decode_ref
+
+ class FakeTQ(CacheLayer_MLA_fp16):
+ def update_kv_direct(self, cache_seqlens, block_table, k, v, length):
+ from exllamav3.modules.attention_fn.mla_triton import mla_kv_append
+ full = self.kv_lora_rank
+ dim = full // blocks
+ st = TQState.get(dim, bits, bits, k.device)
+ x = k.reshape(-1, full).float()
+ if gamma:
+ g = self.attention.kv_a_layernorm.weight.data.float().to(k.device)
+ x = x / g
+ x = x.reshape(-1, dim).half()
+ y = st.rotate(x)
+ words, sc = encode_ref(y, st.cbk, st.midk, bits)
+ xr = st.unrotate(decode_ref(words, sc, st.cbk, bits, dim)).reshape(-1, full)
+ if gamma:
+ xr = (xr.float() * g).half()
+ mla_kv_append(xr.reshape(k.shape[0], length, full), v.reshape(v.shape[0], length, self.qk_rope_head_dim),
+ self.k, self.v, block_table, cache_seqlens)
+ class Req(CacheLayer_fp16):
+ mla_cls = FakeTQ
+ return Req
+
+
+def main(pack, docs, out, n_prefix=16384, n_dec=64, fmts=None):
+ from exllamav3 import Cache, CacheLayer_quant, Config, Model
+ fmts = fmts or ["fp16", "k8", "k6", "fq_tq6", "fq_tq5"]
+ ids = torch.load(docs)["ids"][0][: n_prefix + n_dec]
+ T = len(ids)
+ e = T - n_dec
+ m = Model.from_config(Config.from_directory(pack))
+ caches = {}
+ for f in fmts:
+ kw = dict(max_num_tokens=(T + 255) // 256 * 256 + 256, max_batch_size=2, max_history=3)
+ if f == "fp16":
+ caches[f] = Cache(m, **kw)
+ elif f in ("k8", "k6", "k5"):
+ b = int(f[1:])
+ caches[f] = Cache(m, layer_type=CacheLayer_quant, k_bits=b, v_bits=b, **kw)
+ elif f.startswith("fq_tq"):
+ # fq_tq6 | fq_tq6g (gamma-normalized) | fq_tq6b4 (4 blocks of 128) | fq_tq6gb4
+ import re
+ mt = re.match(r"fq_tq(\d)(g?)(?:b(\d))?$", f)
+ caches[f] = Cache(m, layer_type=fake_tq(int(mt[1]), int(mt[3] or 1), bool(mt[2])), **kw)
+ elif f.startswith("tq"):
+ from exllamav3.cache.tq import CacheLayer_tq
+ b = int(f[2:])
+ caches[f] = Cache(m, layer_type=CacheLayer_tq, k_bits=b, v_bits=b, **kw)
+ m.load(progressbar=False)
+ x = torch.tensor([ids])
+ bt = torch.arange((T + 256) // 256, dtype=torch.int32)[None]
+ lps, res = {}, {}
+ import os
+ refp = os.path.join(os.path.expanduser(os.environ.get("TQ_MLA_KL_REF_DIR", "~/.cache/kyojin/tq_mla_kl")), f"ref_fp16_{n_prefix}_{n_dec}.pt") # fp16 reference logprobs (written by a run that includes the fp16 format)
+ prof = os.environ.get("PROF") == "1" # PROF=1: kernel time table of 4 decode steps, no KL
+ if "fp16" not in fmts and not prof:
+ lps["fp16"] = torch.load(refp)
+ for f in fmts:
+ cache = caches[f]
+ with torch.inference_mode():
+ st = cache.get_new_state() if cache.recurrent_state_cls is not None else None
+
+ def par(pos, t):
+ p = {"attn_mode": "flash_attn", "cache": cache, "block_table": bt[:, : (pos + t + 255) // 256], "cache_seqlens": torch.tensor([pos], dtype=torch.int32)}
+ if st is not None:
+ p["recurrent_states"] = [st]
+ return p
+ for a in range(0, e, 2048):
+ m.prefill(x[:, a: min(a + 2048, e)], par(a, min(a + 2048, e) - a))
+ rows = []
+ steps = []
+ if prof:
+ from exllamav3.modules.mla_attn import MLAttention
+ import collections
+ acc = collections.defaultdict(float)
+
+ def timed(cls, name):
+ f = getattr(cls, name)
+
+ def w(*a, **k):
+ torch.cuda.synchronize(); t = time.time()
+ r = f(*a, **k)
+ torch.cuda.synchronize(); acc[name] += time.time() - t
+ return r
+ setattr(cls, name, w)
+ for nm in ("_attend_pre", "_indexer_topk_kpool", "_indexer_topk", "_attend_sparse", "_attend_split", "decode_flash_attn"):
+ timed(MLAttention, nm)
+ for j in range(4):
+ m.forward(x[:, e + j: e + j + 1], par(e + j, 1))
+ acc.clear()
+ for j in range(4, 8):
+ m.forward(x[:, e + j: e + j + 1], par(e + j, 1))
+ print("PROF ms/step (sync'd)", {k: round(v / 4 * 1000, 2) for k, v in acc.items()}, flush=True)
+ return
+ for j in range(n_dec):
+ t0 = time.time()
+ lg = m.forward(x[:, e + j: e + j + 1], par(e + j, 1))
+ r = torch.log_softmax(lg.float().reshape(-1, lg.shape[-1])[-1], -1).cpu() # .cpu() syncs the step
+ steps.append(time.time() - t0)
+ rows.append(r)
+ dt = sorted(steps[4:] or steps)[len(steps[4:] or steps) // 2] # median step, first 4 (Triton compiles) dropped
+ if st is not None:
+ st.free()
+ lps[f] = torch.stack(rows)
+ if f == "fp16":
+ os.makedirs(os.path.dirname(refp), exist_ok=True)
+ torch.save(lps[f], refp)
+ if f != "fp16":
+ r = lps["fp16"]
+ kl = (r.exp() * (r - lps[f]).nan_to_num(0)).sum(-1)
+ res[f] = dict(kl_vs_fp16=kl.mean().item(), top1=(r.argmax(-1) == lps[f].argmax(-1)).float().mean().item(), s_per_tok=dt)
+ else:
+ res[f] = dict(s_per_tok=dt)
+ print(f, res[f], flush=True)
+ json.dump(res, open(out, "w"), indent=1)
+
+
+if __name__ == "__main__":
+ a = sys.argv
+ main(a[1], a[2], a[3], int(a[4]) if len(a) > 4 else 16384, int(a[5]) if len(a) > 5 else 64, a[6:] or None)
diff --git a/tools/qualify/gpu_eval.py b/tools/qualify/gpu_eval.py
index a60afb1..436447a 100644
--- a/tools/qualify/gpu_eval.py
+++ b/tools/qualify/gpu_eval.py
@@ -94,6 +94,8 @@ def kvmode(pack, docs, out, n=256, only=None):
e = T - n
cfg = Config.from_directory(pack)
hd = cfg.head_dim
+ if hd <= 0 or getattr(cfg, 'kv_lora_rank', 0):
+ hd = getattr(cfg, 'kv_lora_rank', hd) # MLA: the cached vector is the latent
fmts = [("k8v8", "quant", 8), ("k6v6", "quant", 6), ("kw6", "quant", 6)] + [(f"tq{b}", "tq", b) for b in (6, 5) if hd > 0 and tq.supported(hd, b)]
x = torch.tensor([ids])
npg = (T + 256) // 256
@@ -114,6 +116,11 @@ def kvmode(pack, docs, out, n=256, only=None):
os.environ["EXL3_KVWIN"] = "4:128" if name == "kw6" else "0" # the production formats at >= 6 bits run without the window; kw6 = the same cache with the ring
cache = Cache(m, max_num_tokens=T + 256, max_batch_size=2, max_history=3, layer_type=CacheLayer_quant, k_bits=b, v_bits=b)
os.environ.pop("EXL3_KVWIN")
+ if kind == "tq" and not tq.cache_is_tq(cache):
+ res[name] = dict(unsupported="the attention cache layers of this model do not take a TurboQuant cache (no TurboQuant layer for this attention type)")
+ print(name, res[name], flush=True)
+ del cache, m; gc.collect()
+ continue
m.load(progressbar=False)
with torch.inference_mode():
st = cache.get_new_state() if cache.recurrent_state_cls is not None else None
@@ -126,15 +133,17 @@ def kvmode(pack, docs, out, n=256, only=None):
m.prefill(x[:, a: min(a + 2048, e)], par(a, min(a + 2048, e) - a))
rows = []
t_dec = time.time()
- for j in range(n):
- lg = m.forward(x[:, e + j: e + j + 1], par(e + j, 1))
- rows.append(torch.log_softmax(lg.float().reshape(-1, lg.shape[-1])[-1], -1).half().cpu())
+ qs = int(os.environ.get("KVMODE_QS", "1")) # rows per decode step: >1 exercises the verify path (spec / MTP / parallel users)
+ for j in range(0, n, qs):
+ k = min(qs, n - j)
+ lg = m.forward(x[:, e + j: e + j + k], par(e + j, k))
+ rows.append(torch.log_softmax(lg.float().reshape(-1, lg.shape[-1])[-k:], -1).half().cpu())
t_dec = (time.time() - t_dec) / n
if st is not None:
st.free()
- lps[name] = torch.stack(rows).float()
+ lps[name] = torch.cat(rows).float()
if name == "k8v8":
- torch.save(lps[name].half(), out + ".k8v8.pt")
+ torch.save(lps[name], out + ".k8v8.pt")
free(m, cache)
if name != "k8v8":
r8 = lps["k8v8"]
diff --git a/tools/qualify/pack.py b/tools/qualify/pack.py
index d01502e..0051e8d 100644
--- a/tools/qualify/pack.py
+++ b/tools/qualify/pack.py
@@ -133,8 +133,7 @@ def serve_flags(meta: dict, *, port: int, ctx: int, sessions: int, k_bits: int,
"--draft-policy", draft or draft_policy(meta)]
if dflash_dir and (draft or "") == "dflash":
f += ["--dflash-dir", dflash_dir]
- if kv_mode != "quant":
- f += ["--kv-mode", kv_mode]
+ f += ["--kv-mode", kv_mode] # always explicit: the server's own default is tq where the backend has it
if kvwin:
f += ["--kvwin", kvwin]
if not meta["vision"]:
diff --git a/tools/qualify/rules.py b/tools/qualify/rules.py
index 27e2433..cf3e98b 100644
--- a/tools/qualify/rules.py
+++ b/tools/qualify/rules.py
@@ -19,7 +19,8 @@ def choose_kv(kl_vs_k8: dict[int, float], kl_max: float = KV_KL_MAX) -> tuple[in
KV_MODE_MARGIN = 0.9 # one 256-step doc is noisy (two docs of one model scatter by 10-30 %): a candidate has to beat k6v6 by this factor
-KV_DEFAULT_FORMATS = ("k6v6", "kw6") # tq6 / tq5 are measured and reported but stay opt-in (--kv-mode tq) in 1.8.1
+KV_TQ_MARGIN = 0.9 # same margin as kw6: a 256-step doc scatters 10-30 %, a tie is a coin flip, so a tq format must clearly beat k6v6 to be chosen
+KV_DEFAULT_FORMATS = ("k6v6", "kw6") # tq6 / tq5 are measured and reported but stay opt-in (QUALIFY_KV_TQ=1): the gate "tq6 >= default on every model" is not met yet
KV_WIN_SPEC = "4:128" # kw6 = k6v6 + the fp16 sink-4 / window-128 ring
@@ -27,11 +28,14 @@ KV_MODE_MAX_SLOWDOWN = 1.10 # a format whose decode step is > 10 % slower tha
def choose_kv_mode(kl: dict[str, float], bits_per_val: dict[str, float], base: str = "k6v6", margin: float = KV_MODE_MARGIN,
- allowed: tuple = KV_DEFAULT_FORMATS, dec_s: dict | None = None, max_slowdown: float = KV_MODE_MAX_SLOWDOWN) -> str:
- """Q6 rule for the KV format: any candidate (kw6, and with `allowed` extended tq6, tq5) whose decode-faithful KL vs k8v8 is <= margin x the
- k6v6 baseline's qualifies; the one with the fewest bytes per value wins (ties: lower KL), else k6v6. kl / bits_per_val: {format: value},
- both holding `base`. The wider-must-qualify check looks at every measured format, `allowed` or not."""
- ok = [n for n in kl if n != base and n in bits_per_val and kl[n] <= margin * kl[base]]
+ allowed: tuple = KV_DEFAULT_FORMATS, dec_s: dict | None = None, max_slowdown: float = KV_MODE_MAX_SLOWDOWN,
+ tq_margin: float = KV_TQ_MARGIN) -> str:
+ """Q6 rule for the KV format: a candidate whose decode-faithful KL vs k8v8 is <= its margin x the k6v6 baseline's qualifies (kw6: `margin`, the
+ ring is an extra only when it clearly helps; tq6 / tq5: `tq_margin`, the owner floor of "never worse than k6v6"); the one with the fewest bytes
+ per value wins (ties: lower KL), else k6v6. kl / bits_per_val: {format: value}, both holding `base`; a format missing from kl was not measured
+ (e.g. the model's attention cannot hold a TurboQuant cache). The wider-must-qualify check looks at every measured format, `allowed` or not."""
+ lim = lambda n: (tq_margin if n.startswith("tq") else margin) * kl[base]
+ ok = [n for n in kl if n != base and n in bits_per_val and kl[n] <= lim(n)]
# sanity: more bits can only help, so a format with fewer bits that beats the baseline while a wider tq format does not is measurement noise
ok = [n for n in ok if all(m in ok for m in kl if m != base and bits_per_val.get(m, 0) > bits_per_val[n])]
ok = [n for n in ok if n in allowed]
diff --git a/tools/qualify/stages.py b/tools/qualify/stages.py
index 8ecc476..680db25 100644
--- a/tools/qualify/stages.py
+++ b/tools/qualify/stages.py
@@ -265,14 +265,15 @@ def job_kv(c: Ctx) -> dict:
def job_kvmode(c: Ctx, docs) -> dict:
"""KV format auto-select, ONCE per model: decode-faithful 32K KL vs k8v8 of k6v6 (quant), kw6 (k6v6 + sink/window ring), tq6, tq5 (TurboQuant + ring).
- Q6 rule (rules.choose_kv_mode): kw6 when its KL <= 0.9 x k6v6's, else k6v6; the tq formats are measured and reported, opt-in only
- (QUALIFY_KV_TQ=1 lets them win: any tq format with KL <= 0.9 x k6v6's, then the fewest bytes per value)."""
+ Q6 rule (rules.choose_kv_mode): kw6 when its KL <= 0.9 x k6v6's; the tq formats are measured and reported, opt-in only (QUALIFY_KV_TQ=1 lets them win
+ under the same margin); the fewest bytes per value among the qualifying formats wins, else k6v6."""
for f in (c.out / "kvmode_raw.json", c.out / "kvmode_raw.json.k8v8.pt"):
f.unlink(missing_ok=True)
for fmt in ("k8v8", "k6v6", "kw6", "tq6", "tq5"): # one lock take per format (each is a model load + a 32K pass)
with c.locks(f"kvmode {fmt}"):
c.py("gpu_eval.py", "kvmode", c.meta["path"], docs, c.out / "kvmode_raw.json", c.args.get("kvmode_steps", 256), fmt, timeout=14400)
raw = json.loads((c.out / "kvmode_raw.json").read_text())
+ raw = {n: v for n, v in raw.items() if "kl_vs_k8" in v} # a format the model's attention cannot hold (tq on QSA layers) is recorded as unsupported, not measured
kl = {n: v["kl_vs_k8"] for n, v in raw.items()}
bpv = {n: v["bits_per_val"] for n, v in raw.items()}
dec = {n: v.get("decode_s_per_tok") for n, v in raw.items()}
diff --git a/tools/qualify/tests/fake_serve.py b/tools/qualify/tests/fake_serve.py
index a8095b1..8a983c3 100644
--- a/tools/qualify/tests/fake_serve.py
+++ b/tools/qualify/tests/fake_serve.py
@@ -6,6 +6,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
ap = argparse.ArgumentParser()
ap.add_argument("--port", type=int); ap.add_argument("-c", type=int); ap.add_argument("--sessions", type=int, default=1)
ap.add_argument("--model"); ap.add_argument("--model-id"); ap.add_argument("--k-bits"); ap.add_argument("--v-bits"); ap.add_argument("--draft-policy")
+ap.add_argument("--kv-mode"); ap.add_argument("--kvwin")
ap.add_argument("--no-vision", action="store_true"); ap.add_argument("--chat-template")
a = ap.parse_args()
LIMIT = int(os.environ.get("LIMIT", "50000"))
diff --git a/tools/qualify/tests/test_plan.py b/tools/qualify/tests/test_plan.py
index 22e87f3..fb04f49 100644
--- a/tools/qualify/tests/test_plan.py
+++ b/tools/qualify/tests/test_plan.py
@@ -299,17 +299,19 @@ class KvModeRule(unittest.TestCase):
self.assertEqual(rules.choose_kv_mode(kl, bpv), "kw6")
self.assertEqual(rules.choose_kv_mode(kl, bpv, dec_s={"k6v6": 0.0068, "kw6": 0.0090, "tq6": 0.0118, "tq5": 0.0070}), "k6v6") # ROCm 0.8B: ring +32 %
self.assertEqual(rules.choose_kv_mode(kl, bpv, dec_s={"k6v6": 0.0068, "kw6": 0.0071}), "kw6")
+ self.assertEqual(rules.choose_kv_mode(kl, bpv, allowed=self.TQ, dec_s={"k6v6": 0.0068, "kw6": 0.0090, "tq6": 0.0118, "tq5": 0.0070}), "k6v6")
def test_choose_kv_mode(self):
bpv = self.BPV
# tq opt-in (default): tq6 / tq5 never win, kw6 does when it beats k6v6 by the margin
self.assertEqual(rules.choose_kv_mode({"k6v6": 0.0536, "kw6": 0.0216, "tq6": 0.0319, "tq5": 0.0544}, bpv), "kw6") # Nanbeige 32K p1
self.assertEqual(rules.choose_kv_mode({"k6v6": 0.010, "kw6": 0.0095, "tq6": 0.004, "tq5": 0.009}, bpv), "k6v6") # kw6 inside the noise
- self.assertEqual(rules.choose_kv_mode({"k6v6": 0.002}, {"k6v6": 6.5}), "k6v6") # nothing else measured
- # with tq allowed (QUALIFY_KV_TQ=1): the old rule, fewest bytes among the qualifying formats
+ self.assertEqual(rules.choose_kv_mode({"k6v6": 0.002}, {"k6v6": 6.5}), "k6v6") # nothing else measured (tq unsupported by the model)
+ # with tq allowed (QUALIFY_KV_TQ=1): fewest bytes among the qualifying formats, a tq format needs the same 0.9 margin
kw = dict(allowed=self.TQ)
self.assertEqual(rules.choose_kv_mode({"k6v6": 0.010, "kw6": 0.005, "tq6": 0.004, "tq5": 0.009}, bpv, **kw), "tq5")
self.assertEqual(rules.choose_kv_mode({"k6v6": 0.010, "kw6": 0.005, "tq6": 0.008, "tq5": 0.020}, bpv, **kw), "tq6")
+ self.assertEqual(rules.choose_kv_mode({"k6v6": 0.010, "kw6": 0.005, "tq6": 0.0095, "tq5": 0.020}, bpv, **kw), "kw6") # tq6 inside the noise
self.assertEqual(rules.choose_kv_mode({"k6v6": 0.005, "kw6": 0.006, "tq6": 0.0125, "tq5": 0.0048}, bpv, **kw), "k6v6")
self.assertEqual(rules.choose_kv_mode({"k6v6": 0.002, "kw6": 0.0021, "tq6": 0.004, "tq5": 0.010}, bpv, **kw), "k6v6")
@@ -337,6 +339,7 @@ class KvModeRule(unittest.TestCase):
c.data = dict(kv=kv)
self.assertEqual((stages.chosen_kv_mode(c), stages.chosen_kvwin(c)), ("quant", "4:128"))
f = packmod.serve_flags(c.meta, port=1, ctx=4096, sessions=1, k_bits=6, v_bits=6, kvwin=stages.chosen_kvwin(c))
+ self.assertEqual(f[f.index("--kv-mode") + 1], "quant")
self.assertEqual(f[f.index("--kvwin") + 1], "4:128")
# QUALIFY_KV_TQ=1: tq6 wins the same table (fewer bytes than kw6; tq5 fails the margin)
os.environ["QUALIFY_KV_TQ"] = "1"
@@ -350,11 +353,26 @@ class KvModeRule(unittest.TestCase):
c.data = dict(kv=kv)
self.assertEqual(stages.chosen_kv_mode(c), "tq")
+ def test_job_kvmode_skips_an_unsupported_tq_format(self):
+ 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(unsupported="QSA"), "tq5": dict(unsupported="QSA"), "kw6": dict(kl_vs_k8=0.01, top1_vs_k8=0.99, bits_per_val=6.5),
+ "k6v6": dict(kl_vs_k8=0.01, top1_vs_k8=0.98, bits_per_val=6.5)}
+ def py(script, *a, **kw):
+ (out / "kvmode_raw.json").write_text(json.dumps(raw))
+ c = SimpleNamespace(out=out, args=dict(kvmode_steps=64), meta=dict(path=str(t / "pack")), py=py, locks=contextlib.nullcontext, repo=t, data={})
+ kv = stages.job_kvmode(c, out / "docs.pt")
+ self.assertEqual((kv["mode"], sorted(kv["modes"])), ("quant", ["k6v6", "kw6"]))
+
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")
self.assertEqual(f[f.index("--kv-mode") + 1], "tq")
- self.assertNotIn("--kv-mode", packmod.serve_flags(meta, port=1, ctx=4096, sessions=1, k_bits=6, v_bits=6))
+ g = packmod.serve_flags(meta, port=1, ctx=4096, sessions=1, k_bits=6, v_bits=6)
+ self.assertEqual(g[g.index("--kv-mode") + 1], "quant") # always explicit
self.assertLess(packmod.kv_bytes_per_token(meta, 5, 5, "tq"), packmod.kv_bytes_per_token(meta, 6, 6))
diff --git a/tools/qwen/serve.py b/tools/qwen/serve.py
index 7e54ded..b931449 100644
--- a/tools/qwen/serve.py
+++ b/tools/qwen/serve.py
@@ -742,6 +742,16 @@ class QwenEngine:
if sessions > 1 and not on_cuda: # speculative rounds of N requests verify N * (depth + 1) rows: cap the depth so they stay in one 8-row forward
# (NVIDIA keeps the spec_policy default: a 16-row budget for a dense model, no cap for a MoE model)
os.environ.setdefault("QWSPEC_LOAD_ROWS", os.environ.get("EXL3_ROW_INV_GROUP_ROWS") or "8")
+ # chunked prefill beside decoding users, ROCm only (gfx1151, 4 streams + one 32K prompt, EXL3_ROW_INV_GROUPS=1):
+ # without it every running stream waits one full 4096-row chunk (0.4 tok/s each); with the decode-priority
+ # chunk the streams decode in the same step as the leader's chunk, 4.2 tok/s each (+10x) for a 2.1x TTFT
+ # of the new prompt (19.8 s -> 40.9 s). Pure chunk steps (EXL3_CIL_SLICE_S=0) only reached 2.2 tok/s.
+ # Opt out with EXL3_SCHED_CHUNK_IL=0. CUDA sets the same three above; the other non-CUDA backends
+ # (Apple) are left on the FIFO prefill until measured there.
+ if torch.version.hip:
+ os.environ.setdefault("EXL3_SCHED_CHUNK_IL", "1")
+ os.environ.setdefault("EXL3_CIL_DECODE_PRIO", "1")
+ os.environ.setdefault("EXL3_CIL_SLICE_S", "0.35")
from exllamav3 import Cache, Config, Generator, Job, Model, Tokenizer
torch.set_grad_enabled(False)
self.torch, self.Generator, self.Job = torch, Generator, Job
@@ -769,17 +779,20 @@ class QwenEngine:
from exllamav3 import CacheLayer_quant
qkw = dict(layer_type=CacheLayer_quant, k_bits=k_bits, v_bits=v_bits) if (k_bits and v_bits) else {}
assert bool(k_bits) == bool(v_bits), "set both --k-bits and --v-bits (or --cache-bits)"
- if kv_mode == "tq":
- # TurboQuant KV pages (rotation + Lloyd-Max codebook + one fp16 norm per head vector) with the fp16 sink + window ring
+ if kv_mode == "tq" and k_bits and v_bits:
+ # TurboQuant KV pages (rotation + Lloyd-Max codebook + one fp16 norm per head vector) with the fp16 sink + window ring. Widths outside 4..6 and head dims without a codebook keep the per-32 quant pages
from exllamav3.cache.tq import CacheLayer_tq, supported as tq_supported
hd = getattr(self.config, "head_dim", None)
- assert k_bits in (4, 5, 6) and v_bits in (4, 5, 6), "--kv-mode tq needs --k-bits and --v-bits in 4..6"
- if hd and tq_supported(hd, k_bits) and tq_supported(hd, v_bits):
+ if k_bits in (4, 5, 6) and v_bits in (4, 5, 6) and hd and tq_supported(hd, k_bits) and tq_supported(hd, v_bits):
qkw["layer_type"] = CacheLayer_tq
else:
- print(f"qserve: --kv-mode tq: head_dim {hd} is not supported, keeping the quant cache", flush=True)
+ print(f"qserve: kv-mode tq: k{k_bits}v{v_bits} at head_dim {hd} has no TurboQuant codebook, keeping the quant cache", flush=True)
# one recurrent (GDN) slot per session; the Generator caps its batch at the slot count
self.cache = Cache(self.model, max_num_tokens=ctx, max_history=max(3, ndt), max_batch_size=sessions, **qkw)
+ if qkw.get("layer_type") is not None and getattr(qkw["layer_type"], "tq", False):
+ from exllamav3.cache.tq import cache_is_tq
+ if not cache_is_tq(self.cache):
+ print("qserve: kv-mode tq: this model's attention cache layers (QSA sparse attention) keep the quant cache", flush=True)
if os.environ.get("EXL3_WARM_DENSE", "1") != "0":
from exllamav3.model.dense_warmup import seed_dense_tune
seed_dense_tune()
@@ -2272,6 +2285,10 @@ def load_all(args: argparse.Namespace):
except (ValueError, KeyError, OSError) as e:
print(f"qserve: ignoring {kvp}: {e}", flush=True)
args.kv_mode = args.kv_mode or "quant"
+ if args.kv_mode == "fp16":
+ args.k_bits = args.v_bits = args.cache_bits = 0
+ elif args.kv_mode == "tq" and not (args.k_bits or args.v_bits or args.cache_bits):
+ args.k_bits = args.v_bits = 4 if (torch.version.cuda and not torch.version.hip) else 6 # TurboQuant default width: 6 bits; the NVIDIA lanes keep their K4V4 preset
if args.kvwin:
os.environ.setdefault("EXL3_KVWIN", args.kvwin) # before the model is built: the attention modules declare the ring state from it
t0 = time.time()
@@ -2299,6 +2316,13 @@ def load_all(args: argparse.Namespace):
kv = sum(l.storage_size() for c in (engine.cache, engine.draft_cache) if c is not None for l in c.layers.values()) / 2**20 / args.ctx
lazy = getattr(engine.draft_model, "lazy_vram_bytes", lambda: 0)() / 2**20 if engine.draft_model is not None else 0.0
print(f"qserve: VRAM left after load: {free_mib:.0f} MiB, {lazy:.0f} MiB of it taken later by the draft-head subset (ctx={args.ctx}, sessions={args.sessions})", flush=True)
+ # KV format actually in use (CacheLayer_tq / CacheLayer_quant) + per-token cost: the two numbers a KV-mode A/B and the
+ # max-context gate are decided on, read straight from the allocated pages instead of guessed from the flags
+ _lay = next(iter(engine.cache.layers.values()), None)
+ _kv_max = int((free_mib - lazy) / kv + args.ctx) // 256 * 256 if kv > 0 else 0
+ print(f"qserve: KV {type(_lay).__name__} k{args.k_bits}v{args.v_bits}"
+ f" {kv:.4f} MiB/token/session = {kv * args.ctx:.0f} MiB at ctx {args.ctx}; "
+ f"~{_kv_max} tokens would fit with {free_mib - lazy:.0f} MiB free", flush=True)
min_free = float(os.environ.get("EXL3_MIN_FREE_MIB") or MIN_FREE_MIB)
warm_peak = getattr(engine, "warm_peak_mib", None)
if warm_peak is not None:
@@ -2326,8 +2350,10 @@ def main() -> None:
help="bits per K/V element of the attention cache pages (0 = fp16, the default; 8 = packed int8, about 40 %% smaller pages, saves 2.6 GiB at 256K, greedy output differs from the 16-bit cache; with EXL3_ROW_INV_GROUPS=1 four parallel sessions matched solo runs, 16 of 16)")
parser.add_argument("--k-bits", type=int, default=0, choices=(0, 2, 3, 4, 5, 6, 7, 8), help="K bits of the quantized attention cache (with --v-bits; overrides --cache-bits)")
parser.add_argument("--v-bits", type=int, default=0, choices=(0, 2, 3, 4, 5, 6, 7, 8), help="V bits of the quantized attention cache")
- parser.add_argument("--kv-mode", choices=("quant", "tq"), default=None,
- help="KV cache format with --k-bits / --v-bits: quant = per-32 scale pages (default); tq = TurboQuant pages (rotation + Lloyd-Max codebook + one fp16 norm per head vector, 4..6 bits) with the fp16 sink-4 + window-128 ring")
+ parser.add_argument("--kv-mode", choices=("quant", "tq", "fp16"), default=None,
+ help="KV cache format. quant (default): per-32 scale pages (--k-bits / --v-bits), fp16 pages when no bits are given; "
+ "tq: TurboQuant pages (rotation + Lloyd-Max codebook + one fp16 norm per head vector) with the fp16 sink-4 + window-128 ring, "
+ "6 bits when no --k-bits / --v-bits / --cache-bits / lane preset says otherwise; fp16 = unquantized pages")
parser.add_argument("--kvwin", default=None, metavar="SINK:WINDOW",
help="fp16 sink + window ring of the quantized cache (EXL3_KVWIN, e.g. 4:128; an EXL3_KVWIN already set wins); written by tools/qualify as the kw6 choice")
parser.add_argument("--ndt", type=int, default=7, help="max draft tokens per round (default 7; the rule drafts up to 3 for most rounds, deeper only on confident chains)")
diff --git a/tools/qwen/test_chunk_il.py b/tools/qwen/test_chunk_il.py
index f3cb534..69514b7 100644
--- a/tools/qwen/test_chunk_il.py
+++ b/tools/qwen/test_chunk_il.py
@@ -158,8 +158,23 @@ def solo_big_ttft(n=45000):
class DecodePriorityTests(unittest.TestCase):
"""EXL3_CIL_DECODE_PRIO=1: a running stream waits one short chunk, not the whole big prefill (3 users on one 3090)."""
+ def setUp(self):
+ os.environ["EXL3_CIL_DPRIO_CHUNK"] = "768" # these cases simulate the pinned 768-row chunk
+
def tearDown(self):
os.environ.pop("EXL3_SCHED_CHUNK_IL", None)
+ os.environ.pop("EXL3_CIL_DPRIO_CHUNK", None)
+
+ def test_dprio_chunk_follows_measured_row_time(self):
+ os.environ.pop("EXL3_CIL_DPRIO_CHUNK")
+ p = chunk_il.ChunkPlanner(row_s=0.0006)
+ self.assertEqual(p.dprio_chunk, 2048) # fast model: capped
+ p.row_s = 0.00134
+ self.assertEqual(p.dprio_chunk, 1024) # slow model: ~1.5 s per chunk
+ p.row_s = 1.0
+ self.assertEqual(p.dprio_chunk, 256) # floor
+ os.environ["EXL3_CIL_DPRIO_CHUNK"] = "768"
+ self.assertEqual(chunk_il.ChunkPlanner(row_s=0.0006).dprio_chunk, 768) # pin wins
def run_case(self, flag, **kw):
s = Sim(flag, **kw)