Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
KV cache: TurboQuant mode (rotation + Lloyd-Max codebook + one fp16 norm per head vector)
YanissAmz81808caccedc
diff --git a/exllamav3/cache/__init__.py b/exllamav3/cache/__init__.pyindex 5d42ae1..934e240 100644--- a/exllamav3/cache/__init__.py+++ b/exllamav3/cache/__init__.py@@ -4,3 +4,4 @@ from .quant import CacheLayer_quantfrom .mla import CacheLayer_MLA_fp16, CacheLayer_MLA_quantfrom .dsa import CacheLayer_dsafrom .recurrent import RecurrentCache+from .tq import CacheLayer_tqdiff --git a/exllamav3/cache/kvwin.py b/exllamav3/cache/kvwin.pyindex c53ab75..ec44e9b 100644--- a/exllamav3/cache/kvwin.py+++ b/exllamav3/cache/kvwin.py@@ -138,6 +138,8 @@ class KVWinLayerState:from .quant import CacheLayer_quantfrom .qsa import QSAPlanescfg = env_cfg(getattr(cache_layer, "k_bits", None), getattr(cache_layer, "v_bits", None))+ if cfg is None and getattr(cache_layer, "tq", False) and os.environ.get("EXL3_KVWIN") is None:+ cfg = parse_spec(DEFAULT_SPEC) # the tq modes are the windowed ones (tq5w / tq6w) on every platformm = self.moduleif (cfg is None or not isinstance(cache_layer, CacheLayer_quant) or isinstance(cache_layer, QSAPlanes) orcache_layer.compand_a != 0.0 or@@ -267,6 +269,10 @@ class KVWinLayerState:dim = m.num_kv_heads * m.head_dimG = dim // 32rows = ring_rows(pos, cfg)+ if getattr(cl, "tq", False):+ for dst, x in zip((self.ov_k, self.ov_v), cl.read_rot(tok)): # the ring holds rotated vectors+ dst[slot].index_copy_(0, rows, x)+ returnfor q, s, bits, dst in ((cl.qk, cl.sk, cl.k_bits, self.ov_k), (cl.qv, cl.sv, cl.v_bits, self.ov_v)):qr = q.reshape(-1, G * bits).index_select(0, tok).contiguous()sr = s.reshape(-1, G).index_select(0, tok).contiguous()diff --git a/exllamav3/cache/tq.py b/exllamav3/cache/tq.pynew file mode 100644index 0000000..9e9f72a--- /dev/null+++ b/exllamav3/cache/tq.py@@ -0,0 +1,206 @@+"""+TurboQuant KV cache layer ("tq"): per KV head vector, rotation + Lloyd-Max codebook + one fp16 norm.++Write: x -> y = R x (R = Hadamard x random signs, orthonormal), n = ||y||, codes = nearest Lloyd-Max centroid of y / n+(the codebook of one coordinate of a random unit vector in R^head_dim), stored scale s = n / ||c|| (norm correction: the+centroid vector c is re-normalised before scaling, so the reconstruction has exactly the norm of the input). Read:+x^ = R^T (s * c). The scale is ONE fp16 per head vector, so b-bit codes cost b + 16 / head_dim bits per value.++The cache lives in the ROTATED domain: R is orthonormal, so q . k = (R q) . (R k) and o = R^T (sum p (R v)). The attention+dispatcher rotates q, k and v on the way in and the output on the way out, so the paged pool, the KVWIN ring and every+kernel see rotated vectors; the Triton loaders expand a code with a codebook gather and a single per-head scale instead+of the per-32 midpoint grid. The packed code layout (32-value groups, power-of-two bit planes) is CacheLayer_quant's, so+copy_page, save / restore and the prefix disk cache move the same four tensors (codes + scales) as before.+"""+from __future__ import annotations+import math+import os+from functools import lru_cache+import torch+from typing_extensions import override+from ..constants import PAGE_SIZE+from .quant import CacheLayer_quant++TQ_SEED = 20240611+_REF_WRITE = os.environ.get("EXL3_TQ_REF_WRITE") == "1" # torch reference writer (A/B and debugging)+++@lru_cache(maxsize = None)+def codebook(dim: int, bits: int) -> torch.Tensor:+ """Lloyd-Max centroids (fp32 CPU, ascending) for a coordinate of a uniform random unit vector in R^dim."""+ from .tq_codebooks import CODEBOOKS+ assert (dim, bits) in CODEBOOKS, f"no TurboQuant codebook for head_dim {dim}, {bits} bits (have {sorted(CODEBOOKS)})"+ return torch.tensor(CODEBOOKS[dim, bits], dtype = torch.float32)+++def supported(dim: int, bits: int) -> bool:+ from .tq_codebooks import CODEBOOKS+ return (dim, bits) in CODEBOOKS+++@lru_cache(maxsize = None)+def rotation(dim: int) -> torch.Tensor:+ """M with y = x @ M.T = H diag(s) x / sqrt(dim): fp32 CPU, orthonormal."""+ h = torch.ones(1, 1, dtype = torch.float64)+ while h.shape[0] < dim:+ h = torch.cat([torch.cat([h, h], 1), torch.cat([h, -h], 1)], 0)+ g = torch.Generator().manual_seed(TQ_SEED)+ s = torch.where(torch.rand(dim, generator = g) < 0.5, -1.0, 1.0).double()+ return ((h / math.sqrt(dim)) * s).float()+++class TQState:+ """Per (head_dim, k_bits, v_bits, device) constants shared by all layers: rotation, codebooks, midpoints."""+ _cache = {}++ @classmethod+ def get(cls, dim: int, k_bits: int, v_bits: int, device) -> "TQState":+ key = (dim, k_bits, v_bits, str(device))+ if key not in cls._cache:+ cls._cache[key] = cls(dim, k_bits, v_bits, device)+ return cls._cache[key]++ def __init__(self, dim, k_bits, v_bits, device):+ self.dim = dim+ self.device = device+ m = rotation(dim)+ self.rot_t = m.t().contiguous().to(device, torch.float16) # x @ rot_t = R x (rotate)+ self.rot = m.contiguous().to(device, torch.float16) # y @ rot = R^T y (un-rotate)+ self.rot_t32 = m.t().contiguous().to(device)+ self.rot32 = m.contiguous().to(device)+ self.cbk = codebook(dim, k_bits).to(device)+ self.cbv = codebook(dim, v_bits).to(device)+ self.cbk16 = self.cbk.half().contiguous()+ self.cbv16 = self.cbv.half().contiguous()+ self.midk = ((self.cbk[1:] + self.cbk[:-1]) / 2).contiguous()+ self.midv = ((self.cbv[1:] + self.cbv[:-1]) / 2).contiguous()+ self.eye32 = torch.eye(32, dtype = torch.float16, device = device) # the kernels' H32 slot: rotation is already outside++ def rotate(self, x: torch.Tensor) -> torch.Tensor:+ """x [..., dim] fp16 -> R x"""+ return (x.reshape(-1, self.dim) @ self.rot_t).view(x.shape)++ def unrotate(self, y: torch.Tensor) -> torch.Tensor:+ return (y.reshape(-1, self.dim) @ self.rot).view(y.shape)+++def encode_ref(y: torch.Tensor, cb: torch.Tensor, mid: torch.Tensor, bits: int):+ """Reference writer. y [N, dim] (rotated, fp16 or fp32) -> (words int32 [N, dim/32*bits], scale fp16 [N])."""+ from ..ext_fallbacks import _pack_cache_codes+ n, dim = y.shape+ yf = y.float()+ nrm = yf.norm(dim = -1, keepdim = True).clamp_min(1e-12)+ codes = torch.bucketize(yf / nrm, mid)+ cn = cb[codes].norm(dim = -1, keepdim = True).clamp_min(1e-12)+ words = _pack_cache_codes(codes.view(n, dim // 32, 32), bits).reshape(n, dim // 32 * bits)+ return words, (nrm / cn).squeeze(-1).to(torch.float16)+++def decode_ref(words: torch.Tensor, scale: torch.Tensor, cb: torch.Tensor, bits: int, dim: int) -> torch.Tensor:+ """Inverse of encode_ref in the rotated domain: -> fp16 [N, dim]."""+ 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)+++class CacheLayer_tq(CacheLayer_quant):+ """TurboQuant KV pool. Tensors: qk / qv packed codes (CacheLayer_quant layout), sk / sv one fp16 scale per head vector."""++ tq = True++ def __init__(self, config, attention, cache_id: int, max_num_tokens: int, k_bits: int, v_bits: int, compand_a: float = 0.0):+ assert compand_a == 0.0+ super().__init__(config, attention, cache_id, max_num_tokens, k_bits, v_bits, 0.0)+ assert attention is not None and supported(attention.head_dim, k_bits) and supported(attention.head_dim, v_bits), \+ f"tq cache: head_dim {attention.head_dim} with {k_bits}/{v_bits} bits is not supported"+ self.head_dim = attention.head_dim+ self.num_kv_heads = attention.num_kv_heads+ self.qshape_s = (max_num_tokens // PAGE_SIZE, PAGE_SIZE, self.num_kv_heads)+ self.state: TQState | None = None++ @override+ def alloc(self, device: torch.device):+ super().alloc(device)+ self.state = TQState.get(self.head_dim, self.k_bits, self.v_bits, device)++ @override+ def free(self):+ super().free()+ self.state = None++ def get_tq(self) -> TQState:+ return self.state++ # -- writers / readers (rotated domain) -------------------------------------------------------------------------+ def _rows(self, cache_seqlens, block_table, bsz: int, length: int):+ """Physical pool row (page * PAGE_SIZE + offset) of each of the bsz x length new positions."""+ tok = cache_seqlens.long().unsqueeze(1) + torch.arange(length, device = cache_seqlens.device).unsqueeze(0)+ page = block_table.long().gather(1, tok // PAGE_SIZE)+ return (page * PAGE_SIZE + tok % PAGE_SIZE).reshape(-1)++ def write_rot(self, cache_seqlens, block_table, k, v, length: int):+ """k, v: rotated fp16 [bsz, length, kvh, hd] (contiguous). Reference writer."""+ st = self.state+ bsz = block_table.shape[0]+ rows = self._rows(cache_seqlens, block_table, bsz, length)+ for x, q, s, bits, cb, mid in ((k, self.qk, self.sk, self.k_bits, st.cbk, st.midk),+ (v, self.qv, self.sv, self.v_bits, st.cbv, st.midv)):+ words, sc = encode_ref(x.reshape(-1, self.head_dim), cb, mid, bits)+ q.view(-1, q.shape[-1]).index_copy_(0, rows, words.view(rows.numel(), -1))+ s.view(-1, self.num_kv_heads).index_copy_(0, rows, sc.view(rows.numel(), -1))++ def read_rot(self, rows: torch.Tensor):+ """Dequantized rotated K, V fp16 [len(rows), kvh, hd] for physical pool rows."""+ st = self.state+ out = []+ for q, s, bits, cb in ((self.qk, self.sk, self.k_bits, st.cbk), (self.qv, self.sv, self.v_bits, st.cbv)):+ w = q.view(-1, q.shape[-1]).index_select(0, rows).reshape(-1, self.head_dim // 32 * bits)+ sc = s.view(-1, self.num_kv_heads).index_select(0, rows).reshape(-1)+ out.append(decode_ref(w, sc, cb, bits, self.head_dim).view(rows.numel(), self.num_kv_heads, self.head_dim))+ return out++ @override+ def update_kv_direct(self, cache_seqlens, block_table, k, v, length: int):+ # k, v are already rotated by the dispatcher+ k, v = k.contiguous(), v.contiguous()+ if k.is_cuda and not _REF_WRITE:+ from ..modules.attention_fn.tq_triton import tq_write+ st = self.state+ tq_write(k, self.qk, self.sk, st.cbk, st.midk, cache_seqlens, block_table, self.k_bits, self.num_kv_heads, self.head_dim, PAGE_SIZE)+ tq_write(v, self.qv, self.sv, st.cbv, st.midv, cache_seqlens, block_table, self.v_bits, self.num_kv_heads, self.head_dim, PAGE_SIZE)+ else:+ self.write_rot(cache_seqlens, block_table, k, v, length)++ @override+ def get_kv(self, cache_seqlens, block_table, sliding_window: int = -1):+ """Natural-domain fp16 K / V of the whole pool (callers outside the quant-direct path expect plain vectors)."""+ st = self.state+ k = torch.empty(self.shape, dtype = torch.half, device = self.device)+ v = torch.empty(self.shape, dtype = torch.half, device = self.device)+ n = self.shape[0] * PAGE_SIZE+ for lo in range(0, n, 1 << 16):+ rows = torch.arange(lo, min(n, lo + (1 << 16)), device = self.device)+ kr, vr = self.read_rot(rows)+ k.view(n, *self.shape[2:])[lo:lo + rows.numel()] = st.unrotate(kr)+ v.view(n, *self.shape[2:])[lo:lo + rows.numel()] = st.unrotate(vr)+ return k, v++ @override+ def update_kv(self, cache_seqlens, block_table, k, v, length: int):+ # k, v: natural-domain fp16 pool-shaped scratch (get_kv layout): re-encode the new rows+ st = self.state+ bsz = block_table.shape[0]+ rows = self._rows(cache_seqlens, block_table, bsz, length)+ kr = st.rotate(k.view(-1, self.num_kv_heads, self.head_dim).index_select(0, rows))+ vr = st.rotate(v.view(-1, self.num_kv_heads, self.head_dim).index_select(0, rows))+ # scatter back through write_rot's row logic+ for x, q, s, bits, cb, mid in ((kr, self.qk, self.sk, self.k_bits, st.cbk, st.midk),+ (vr, self.qv, self.sv, self.v_bits, st.cbv, st.midv)):+ words, sc = encode_ref(x.reshape(-1, self.head_dim), cb, mid, bits)+ q.view(-1, q.shape[-1]).index_copy_(0, rows, words.view(rows.numel(), -1))+ s.view(-1, self.num_kv_heads).index_copy_(0, rows, sc.view(rows.numel(), -1))++ @override+ def tp_export(self, plan):+ raise NotImplementedError("the tq KV cache does not support tensor parallel loading")diff --git a/exllamav3/cache/tq_codebooks.py b/exllamav3/cache/tq_codebooks.pynew file mode 100644index 0000000..99ddd84--- /dev/null+++ b/exllamav3/cache/tq_codebooks.py@@ -0,0 +1,140 @@+"""Lloyd-Max centroids of one coordinate of a uniform random unit vector in R^D, (D, bits) -> ascending list (fp64 solve, stored as fp32 values).+Generated by the Lloyd iteration on the density (1-t^2)^((D-3)/2); see cache/tq.py."""+CODEBOOKS = {+ (64, 4): [+ -0.33074527978897095, -0.2528544068336487, -0.19879400730133057, -0.15486541390419006,+ -0.11643224954605103, -0.08126740902662277, -0.04806011915206909, -0.015909498557448387,+ 0.01590452343225479, 0.048055149614810944, 0.08126243948936462, 0.11642728745937347,+ 0.15486259758472443, 0.19879400730133057, 0.2528544068336487, 0.33074527978897095,+ ],+ (64, 5): [+ -0.3880903720855713, -0.3232688009738922, -0.27978938817977905, -0.245649054646492,+ -0.2168390154838562, -0.19148829579353333, -0.16856415569782257, -0.1474212408065796,+ -0.1276273876428604, -0.10887894034385681, -0.09094265103340149, -0.07363530993461609,+ -0.05680711939930916, -0.04033255577087402, -0.02410297840833664, -0.008019482716917992,+ 0.008014488965272903, 0.02409798465669155, 0.040327563881874084, 0.05680212751030922,+ 0.07363031804561615, 0.09093765914440155, 0.10887394845485687, 0.12762239575386047,+ 0.14741624891757965, 0.16855916380882263, 0.1914833039045334, 0.21683403849601746,+ 0.24564409255981445, 0.2797844409942627, 0.32326391339302063, 0.38808581233024597,+ ],+ (64, 6): [+ -0.42331260442733765, -0.36531782150268555, -0.3270800709724426, -0.297568678855896,+ -0.2731202244758606, -0.2520291805267334, -0.23335996270179749, -0.2165384739637375,+ -0.20118291676044464, -0.18703152239322662, -0.1738928258419037, -0.1616206020116806,+ -0.15009714663028717, -0.1392318457365036, -0.1289505660533905, -0.11919178068637848,+ -0.10990341752767563, -0.1010359451174736, -0.09254972636699677, -0.08440997451543808,+ -0.07658186554908752, -0.06903308629989624, -0.06173625588417053, -0.05466143786907196,+ -0.04778127372264862, -0.04107079282402992, -0.034507591277360916, -0.028071686625480652,+ -0.021735619753599167, -0.015476950444281101, -0.009270694106817245, -0.0030894011724740267,+ 0.0030844020657241344, 0.00926569476723671, 0.015471951104700565, 0.02173062041401863,+ 0.028066687285900116, 0.03450259193778038, 0.04106579348444939, 0.047776274383068085,+ 0.05465644225478172, 0.061731260269880295, 0.0690280869603157, 0.07657687366008759,+ 0.08440497517585754, 0.09254472702741623, 0.10103094577789307, 0.10989841818809509,+ 0.11918678879737854, 0.12894555926322937, 0.13922683894634247, 0.15009215474128723,+ 0.16161800920963287, 0.1738928258419037, 0.18703152239322662, 0.20118291676044464,+ 0.2165384739637375, 0.23335996270179749, 0.2520291805267334, 0.2731202244758606,+ 0.297568678855896, 0.3270800709724426, 0.36531782150268555, 0.42331260442733765,+ ],+ (128, 4): [+ -0.23762281239032745, -0.18078890442848206, -0.14175525307655334, -0.11023858189582825,+ -0.0827830582857132, -0.0577348992228508, -0.03412646800279617, -0.011294822208583355,+ 0.01129042636603117, 0.034122075885534286, 0.05773050710558891, 0.08277866989374161,+ 0.11023420095443726, 0.14175090193748474, 0.18078459799289703, 0.2376188486814499,+ ],+ (128, 5): [+ -0.28060710430145264, -0.23250362277030945, -0.2006063163280487, -0.17574602365493774,+ -0.15488150715827942, -0.13660143315792084, -0.1201292872428894, -0.1049799770116806,+ -0.09082579612731934, -0.07743936777114868, -0.06465330719947815, -0.05233139172196388,+ -0.040360912680625916, -0.028652740642428398, -0.017123816534876823, -0.005697738844901323,+ 0.005693325772881508, 0.017119403928518295, 0.02864832803606987, 0.04035649821162224,+ 0.052326980978250504, 0.06464888900518417, 0.0774349570274353, 0.09082138538360596,+ 0.10497556626796722, 0.12012488394975662, 0.13659702241420746, 0.15487709641456604,+ 0.17574162781238556, 0.20060193538665771, 0.23249928653240204, 0.2806030511856079,+ ],+ (128, 6): [+ -0.3072315752506256, -0.263621062040329, -0.23521403968334198, -0.2134648561477661,+ -0.19554923474788666, -0.1801668107509613, -0.16660109162330627, -0.1544143259525299,+ -0.1433236300945282, -0.13312450051307678, -0.12366984784603119, -0.11485400795936584,+ -0.10659264773130417, -0.09881617873907089, -0.09147036075592041, -0.08450695872306824,+ -0.07788462191820145, -0.07157041132450104, -0.06553594022989273, -0.05975477397441864,+ -0.054198358207941055, -0.04884476214647293, -0.0436696857213974, -0.0386534258723259,+ -0.03378273546695709, -0.02903331071138382, -0.024387603625655174, -0.019834555685520172,+ -0.015352090820670128, -0.010924804024398327, -0.00654164794832468, -0.002180551178753376,+ 0.002176132518798113, 0.0065372297540307045, 0.010920385830104351, 0.015347672626376152,+ 0.019830137491226196, 0.0243831854313612, 0.029028892517089844, 0.033778317272663116,+ 0.03864900767803192, 0.043665267527103424, 0.048840343952178955, 0.05419394001364708,+ 0.059750355780124664, 0.06553152203559875, 0.07156599313020706, 0.07788020372390747,+ 0.08450254052877426, 0.09146595001220703, 0.09881176054477692, 0.10658823698759079,+ 0.11484959721565247, 0.12366543710231781, 0.1331200748682022, 0.14331920444965363,+ 0.15440991520881653, 0.1665966808795929, 0.18016240000724792, 0.19554482400417328,+ 0.21346046030521393, 0.235209658741951, 0.2636167109012604, 0.3072274625301361,+ ],+ (256, 4): [+ -0.16938146948814392, -0.12855473160743713, -0.10066360235214233, -0.07821600139141083,+ -0.058701179921627045, -0.04092295467853546, -0.024183209985494614, -0.008003042079508305,+ 0.007999934256076813, 0.024180101230740547, 0.04091985151171684, 0.058698076754808426,+ 0.07821290194988251, 0.1006605252623558, 0.1285516768693924, 0.1693786382675171,+ ],+ (256, 5): [+ -0.20067812502384186, -0.16582781076431274, -0.14285434782505035, -0.1250145137310028,+ -0.11008388549089432, -0.09703247249126434, -0.08529040217399597, -0.0745031014084816,+ -0.0644363984465599, -0.05492452532052994, -0.04584331065416336, -0.03709806129336357,+ -0.02860899455845356, -0.02030843123793602, -0.012136178091168404, -0.004038180690258741,+ 0.004035060293972492, 0.012133057229220867, 0.020306849852204323, 0.02860899455845356,+ 0.03709806129336357, 0.04584331065416336, 0.05492303520441055, 0.06443475186824799,+ 0.0745016410946846, 0.08528728038072586, 0.09702935814857483, 0.1100807785987854,+ 0.1250113993883133, 0.14285124838352203, 0.1658247411251068, 0.20067524909973145,+ ],+ (256, 6): [+ -0.22014178335666656, -0.18833738565444946, -0.16774427890777588, -0.15203975141048431,+ -0.13914182782173157, -0.1280912160873413, -0.11836604028940201, -0.10964564979076385,+ -0.10171680152416229, -0.09443400800228119, -0.08769290894269943, -0.0814126506447792,+ -0.07553227245807648, -0.07000245153903961, -0.06478016078472137, -0.05983305722475052,+ -0.05513327196240425, -0.050654470920562744, -0.04637500271201134, -0.04227463901042938,+ -0.03833635896444321, -0.03454456850886345, -0.03088216297328472, -0.027333572506904602,+ -0.023886362090706825, -0.020526472479104996, -0.017241470515727997, -0.01402198988944292,+ -0.010852416977286339, -0.007723425514996052, -0.004624068737030029, -0.0015403173165395856,+ 0.0015371928457170725, 0.004620944149792194, 0.007720300927758217, 0.010849292390048504,+ 0.014018865302205086, 0.017238346859812737, 0.020523346960544586, 0.023883236572146416,+ 0.027330446988344193, 0.03087903931736946, 0.03454144299030304, 0.038333237171173096,+ 0.04227151721715927, 0.04637187719345093, 0.05065134912729263, 0.05513014644384384,+ 0.05982993543148041, 0.06477703899145126, 0.0699993297457695, 0.07552915066480637,+ 0.0814095288515091, 0.08768978714942932, 0.09443088620901108, 0.10171368718147278,+ 0.10964252799749374, 0.1183629259467125, 0.1280881017446518, 0.13913871347904205,+ 0.152036651968956, 0.16774232685565948, 0.18833649158477783, 0.22013887763023376,+ ],+ (512, 4): [+ -0.12025641649961472, -0.0911591574549675, -0.07133294641971588, -0.0554020069539547,+ -0.04156791418790817, -0.028973806649446487, -0.017120173200964928, -0.0056653437204658985,+ 0.005663146264851093, 0.017117975279688835, 0.028971612453460693, 0.04156571999192238,+ 0.0553998202085495, 0.07133077085018158, 0.09115700423717499, 0.12025441974401474,+ ],+ (512, 5): [+ -0.1427084505558014, -0.11776427924633026, -0.1013677716255188, -0.08865982294082642,+ -0.07803760468959808, -0.06876077502965927, -0.060422383248806, -0.052769895642995834,+ -0.04563198983669281, -0.03889099135994911, -0.032458677887916565, -0.026263916864991188,+ -0.020251423120498657, -0.014374407939612865, -0.008589198812842369, -0.0028576022014021873,+ 0.002856496023014188, 0.008589198812842369, 0.014374407939612865, 0.020251423120498657,+ 0.026263916864991188, 0.032458677887916565, 0.03889099135994911, 0.04563198983669281,+ 0.052769895642995834, 0.060422383248806, 0.06876077502965927, 0.07803760468959808,+ 0.08865982294082642, 0.1013677716255188, 0.11776427924633026, 0.1427084505558014,+ ],+ (512, 6): [+ -0.15670321881771088, -0.13386626541614532, -0.11912287771701813, -0.10790243744850159,+ -0.09870021045207977, -0.09082639962434769, -0.08390287309885025, -0.07769869267940521,+ -0.07206156849861145, -0.06688794493675232, -0.06210148334503174, -0.0576443187892437,+ -0.05347191542387009, -0.049548614770174026, -0.04584715887904167, -0.04234129562973976,+ -0.03901036083698273, -0.03583676740527153, -0.03280523791909218, -0.02990143746137619,+ -0.02711336314678192, -0.024429962038993835, -0.021838048473000526, -0.01932772621512413,+ -0.016890184953808784, -0.014514388516545296, -0.012191545218229294, -0.009913922287523746,+ -0.0076727066189050674, -0.005461279768496752, -0.0032697063870728016, -0.0010891675483435392,+ 0.0010869582183659077, 0.00326749705709517, 0.005459070671349764, 0.0076704975217580795,+ 0.009911713190376759, 0.012189336121082306, 0.014512178488075733, 0.016887975856661797,+ 0.019325517117977142, 0.02183583937585354, 0.024427752941846848, 0.027111155912280083,+ 0.029899228364229202, 0.03280302882194519, 0.03583455830812454, 0.03900815173983574,+ 0.04233908653259277, 0.04584495350718498, 0.04954640567302704, 0.0534697100520134,+ 0.05764210969209671, 0.06209927424788475, 0.06688573956489563, 0.07205935567617416,+ 0.0776975080370903, 0.08390187472105026, 0.0908251702785492, 0.09870021045207977,+ 0.10790243744850159, 0.11912287771701813, 0.13386626541614532, 0.15670321881771088,+ ],+}diff --git a/exllamav3/modules/attention_fn/bc_attn.py b/exllamav3/modules/attention_fn/bc_attn.pyindex d993bb6..00a7a45 100644--- a/exllamav3/modules/attention_fn/bc_attn.py+++ b/exllamav3/modules/attention_fn/bc_attn.py@@ -757,6 +757,10 @@ def build_bc_attn(module, layer):# KVWIN: the graph writes the pool inside the captured block and would leave the fp16 ring stale_trace_build(m, None, "attn")return None+ if getattr(layer, "tq", False):+ # TurboQuant: rotation + codebook reads live in the Triton path+ _trace_build(m, None, "attn")+ return Noneqsa_idx = getattr(m, "qsa_indexer", None)if not (_module_eligible(m) anddiff --git a/exllamav3/modules/attention_fn/common.py b/exllamav3/modules/attention_fn/common.pyindex 6e57b24..114d404 100644--- a/exllamav3/modules/attention_fn/common.py+++ b/exllamav3/modules/attention_fn/common.py@@ -30,6 +30,7 @@ class AttnArgs(NamedTuple):v_dim: int | None = None # V lanes in use when V is zero-padded to dim (MiMo 128 of 192)ov: object | None = None # KVWIN: KVWinCtx of a quant-direct call (fp16 sink + window ring next to the pool)+ tq: object | None = None # TurboQuant cache (cache.tq.TQState): q / k / v / ring are already rotated, codes read through a codebookdef sanity_check(self):# Cache must be pageddiff --git a/exllamav3/modules/attention_fn/dispatch.py b/exllamav3/modules/attention_fn/dispatch.pyindex c66742c..5b5b7f6 100644--- a/exllamav3/modules/attention_fn/dispatch.py+++ b/exllamav3/modules/attention_fn/dispatch.py@@ -117,6 +117,7 @@ def attn_dispatch(# materialized as full fp16 cache-sized temporariesq_cache = Noneov_attend = False+ tq = Noneif cache is not None:assert block_table is not Noneassert cache_seqlens is not None@@ -129,6 +130,10 @@ def attn_dispatch(dim <= 512 and dim % 32 == 0 and # packed groups of 32; non-pow2 dims run zero-paddedcu_seqlens is None):+ tq = layer.get_tq() if getattr(layer, "tq", False) else None+ if tq is not None:+ # TurboQuant: the pool, the ring and the kernels live in the rotated domain (see cache/tq.py)+ q, k, v = tq.rotate(q), tq.rotate(k), tq.rotate(v)layer.update_kv_direct(cache_seqlens, block_table, k, v, q_len)q_cache = layer.get_qkv()k_cache, v_cache = None, None@@ -172,6 +177,7 @@ def attn_dispatch(max_kv_len = max_kv_len,v_dim = v_dim,ov = ov if q_cache is not None and ov_attend else None,+ tq = tq,)# Quant-direct calls select among the qc-aware backends only; a separate hint slot keeps a function that# won a cache-less or fp16-cache call from being retried on quant-direct arguments (it cannot see q_cache@@ -198,6 +204,8 @@ def attn_dispatch(if ov is not None and q_cache is not None and q_len > MAX_DRAFT:ov_write(ov, k, v, cache_seqlens, q_len)+ if tq is not None:+ o = tq.unrotate(o)# Update cache (quant-direct mode already wrote the new K/V before the attention call)if cache is not None and q_cache is None:diff --git a/exllamav3/modules/attention_fn/tq_triton.py b/exllamav3/modules/attention_fn/tq_triton.pynew file mode 100644index 0000000..69c1bce--- /dev/null+++ b/exllamav3/modules/attention_fn/tq_triton.py@@ -0,0 +1,137 @@+"""TurboQuant cache kernels (Triton, ROCm + CUDA): paged window dequant for the prefill staging scratch.++The pool layout is CacheLayer_quant's (32-value groups, power-of-two bit planes, plane order 8 4 2 1) with one fp16 scale+per head vector instead of per group; see cache/tq.py. Values stay in the rotated domain."""+import torch+import triton+import triton.language as tl+++def _tq_dequant_window_kernel(+ words, scales, cb, out, block_table, cache_seqlens,+ bonus, npps,+ BITS: tl.constexpr,+ PAGE: tl.constexpr,+ HKV: tl.constexpr,+ D: tl.constexpr,+ TB: tl.constexpr,+):+ """Program (page slot of the block table x TB-token tile, kv head): dequantize TB tokens to fp16 (compact scratch layout:+ scratch page b * npps + p holds table slot p of sequence b)."""+ pid = tl.program_id(0)+ h = tl.program_id(1)+ TPP: tl.constexpr = PAGE // TB+ bp = pid // TPP+ sub = pid - bp * TPP+ b = bp // npps+ p = bp - b * npps+ limit = tl.load(cache_seqlens + b) + bonus+ toff = sub * TB + tl.arange(0, TB)+ tmask = (p * PAGE + toff) < limit+ phys = tl.load(block_table + b * npps + p)+ row = phys * PAGE + toff+ d = tl.arange(0, D)+ g = d // 32+ r = d - g * 32+ G: tl.constexpr = D // 32+ base = row[:, None] * (HKV * G * BITS) + h * (G * BITS) + g[None, :] * BITS+ m2 = tmask[:, 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 * HKV + h, mask = tmask, other = 0.0).to(tl.float32)+ val = (tl.load(cb + raw) * sc[:, None]).to(tl.float16)+ dst = ((bp * PAGE + toff)[:, None].to(tl.int64) * HKV + h) * D + d[None, :]+ tl.store(out + dst, val, mask = m2)+++def tq_dequant_window(words, scales, cb, out, cache_seqlens, block_table, page_size, bonus_len, bits, n_kv_heads, head_dim):+ """Dequantize the table-mapped pages of every sequence (positions < cache_seqlens + bonus_len) into the compact scratch+ `out` [>= bsz * npps pages, page_size, kvh, hd] fp16, rotated domain."""+ bsz, npps = block_table.shape+ tb = 16+ with torch.cuda.device(words.device):+ _tq_dequant_window_kernel[(bsz * npps * (page_size // tb), n_kv_heads)](+ words, scales, cb, out, block_table, cache_seqlens, bonus_len, npps,+ bits, page_size, n_kv_heads, head_dim, tb,+ num_warps = 4, num_stages = 1,+ )+++def _tq_write_kernel(+ x, words, scales, cb, mid, block_table, cache_seqlens,+ length, npps,+ BITS: tl.constexpr,+ PAGE: tl.constexpr,+ HKV: tl.constexpr,+ D: tl.constexpr,+):+ """One program per (sequence b, new position t, kv head): y -> unit vector -> nearest Lloyd-Max centroid per coordinate+ (count of midpoints below it) -> bit planes (8 4 2 1, high bits first) + fp16 scale = norm / ||centroid vector||."""+ bt = tl.program_id(0)+ h = tl.program_id(1)+ b = bt // length+ t = bt - b * length+ tok = tl.load(cache_seqlens + b) + t+ phys = tl.load(block_table + b * npps + tok // PAGE)+ row = phys.to(tl.int64) * PAGE + tok % PAGE+ d = tl.arange(0, D)+ y = tl.load(x + (bt.to(tl.int64) * HKV + h) * D + d).to(tl.float32)+ nrm = tl.maximum(tl.sqrt(tl.sum(y * y, axis = 0)), 1e-12)+ u = y / nrm+ code = tl.zeros((D,), tl.int32)+ for i in range((1 << BITS) - 1):+ code += (u > tl.load(mid + i)).to(tl.int32)+ c = tl.load(cb + code)+ cn = tl.maximum(tl.sqrt(tl.sum(c * c, axis = 0)), 1e-12)+ tl.store(scales + row * HKV + h, (nrm / cn).to(tl.float16))+ G: tl.constexpr = D // 32+ wbase = words + row * (HKV * G * BITS) + h * (G * BITS)+ if BITS & 8:+ _tq_pack_plane(wbase, code, 8, BITS, 0, BITS - 8, G, D)+ if BITS & 4:+ _tq_pack_plane(wbase, code, 4, BITS, (BITS & 8), BITS - (BITS & 8) - 4, G, D)+ if BITS & 2:+ _tq_pack_plane(wbase, code, 2, BITS, (BITS & 12), BITS - (BITS & 12) - 2, G, D)+ if BITS & 1:+ _tq_pack_plane(wbase, code, 1, BITS, (BITS & 14), 0, G, D)+++def _tq_pack_plane(wbase, code, W: tl.constexpr, BITS: tl.constexpr, pbase: tl.constexpr, shift: tl.constexpr,+ G: tl.constexpr, D: tl.constexpr):+ VPW: tl.constexpr = 32 // W+ nib = (code >> shift) & ((1 << W) - 1)+ nib2 = tl.reshape(nib, (G * W, VPW))+ sh = (tl.arange(0, VPW) * W)[None, :]+ word = tl.sum(nib2 << sh, axis = 1)+ wi = tl.arange(0, G * W)+ tl.store(wbase + (wi // W) * BITS + pbase + (wi % W), word)+++def tq_write(x, words, scales, cb, mid, cache_seqlens, block_table, bits, n_kv_heads, head_dim, page_size):+ """x: rotated fp16 [bsz, length, kvh, hd] contiguous -> pool rows at cache_seqlens .. + length."""+ bsz, length = x.shape[0], x.shape[1]+ with torch.cuda.device(x.device):+ _tq_write_kernel[(bsz * length, n_kv_heads)](+ x, words, scales, cb, mid, block_table, cache_seqlens,+ length, block_table.shape[1],+ bits, page_size, n_kv_heads, head_dim,+ num_warps = 2, num_stages = 1,+ )diff --git a/exllamav3/modules/attention_fn/triton_paged.py b/exllamav3/modules/attention_fn/triton_paged.pyindex e5badf2..bfd3485 100644--- a/exllamav3/modules/attention_fn/triton_paged.py+++ b/exllamav3/modules/attention_fn/triton_paged.py@@ -798,7 +798,8 @@ def _qc_plane_v(qwords_head, row_words, mask_n, pbase,@triton.jitdef _qc_load_kt(qwords, scales, tok_rows, kv_head, offs_d, mask_n,- BITS: tl.constexpr, n_kv_heads: tl.constexpr, head_dim: tl.constexpr, HD_PAD: tl.constexpr):+ BITS: tl.constexpr, n_kv_heads: tl.constexpr, head_dim: tl.constexpr, HD_PAD: tl.constexpr,+ cb = None, TQ: tl.constexpr = 0):"""(HD_PAD, BLOCK_N) fp16 tile from the packed cache, linear midpoint grid, values stayin the rotated domain. The cache packs each group into power-of-two bit planes (BITS = sumof its set bits), so every width expands with vectorized shifts; no gathers, no straddling.@@ -829,22 +830,29 @@ def _qc_load_kt(qwords, scales, tok_rows, kv_head, offs_d, mask_n,if BITS & 1:p = _qc_plane_kt(qh, row_words, mask_n, pbase, 1, BITS, head_dim, HD_PAD)raw = p if first else (raw << 1) | p- sgb = kv_head * G- garr = tl.arange(0, G_PAD)- if G_PAD > G:- sc = tl.load(scales + tok_rows[None, :] * GPT + (sgb + garr)[:, None],- mask = mask_n[None, :] & (garr < G)[:, None], other = 0.0)+ 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)else:- sc = tl.load(scales + tok_rows[None, :] * GPT + (sgb + garr)[:, None], mask = mask_n[None, :], other = 0.0)- scx = tl.reshape(tl.broadcast_to(sc[:, None, :], (G_PAD, 32, sc.shape[1])), (HD_PAD, sc.shape[1]))- mh = (1 << (BITS - 1)) - 0.5- inv_m = 1.0 / (1 << (BITS - 1))- return ((raw.to(tl.float32) - mh) * (scx.to(tl.float32) * inv_m)).to(tl.float16)+ sgb = kv_head * G+ garr = tl.arange(0, G_PAD)+ if G_PAD > G:+ sc = tl.load(scales + tok_rows[None, :] * GPT + (sgb + garr)[:, None],+ mask = mask_n[None, :] & (garr < G)[:, None], other = 0.0)+ else:+ sc = tl.load(scales + tok_rows[None, :] * GPT + (sgb + garr)[:, None], mask = mask_n[None, :], other = 0.0)+ scx = tl.reshape(tl.broadcast_to(sc[:, None, :], (G_PAD, 32, sc.shape[1])), (HD_PAD, sc.shape[1]))+ mh = (1 << (BITS - 1)) - 0.5+ inv_m = 1.0 / (1 << (BITS - 1))+ res = ((raw.to(tl.float32) - mh) * (scx.to(tl.float32) * inv_m)).to(tl.float16)+ return res@triton.jitdef _qc_load_v(qwords, scales, tok_rows, kv_head, offs_d, mask_n,- BITS: tl.constexpr, n_kv_heads: tl.constexpr, head_dim: tl.constexpr, HD_PAD: tl.constexpr):+ BITS: tl.constexpr, n_kv_heads: tl.constexpr, head_dim: tl.constexpr, HD_PAD: tl.constexpr,+ cb = None, TQ: tl.constexpr = 0):"""(BLOCK_N, HD_PAD) fp16 tile, transposed orientation of _qc_load_kt."""GPT: tl.constexpr = n_kv_heads * head_dim // 32G: tl.constexpr = head_dim // 32@@ -872,17 +880,22 @@ def _qc_load_v(qwords, scales, tok_rows, kv_head, offs_d, mask_n,if BITS & 1:p = _qc_plane_v(qh, row_words, mask_n, pbase, 1, BITS, head_dim, HD_PAD)raw = p if first else (raw << 1) | p- sgb = kv_head * G- garr = tl.arange(0, G_PAD)- if G_PAD > G:- sc = tl.load(scales + tok_rows[:, None] * GPT + (sgb + garr)[None, :],- mask = mask_n[:, None] & (garr < G)[None, :], other = 0.0)+ 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)else:- sc = tl.load(scales + tok_rows[:, None] * GPT + (sgb + garr)[None, :], mask = mask_n[:, None], other = 0.0)- scx = tl.reshape(tl.broadcast_to(sc[:, :, None], (sc.shape[0], G_PAD, 32)), (sc.shape[0], HD_PAD))- mh = (1 << (BITS - 1)) - 0.5- inv_m = 1.0 / (1 << (BITS - 1))- return ((raw.to(tl.float32) - mh) * (scx.to(tl.float32) * inv_m)).to(tl.float16)+ sgb = kv_head * G+ garr = tl.arange(0, G_PAD)+ if G_PAD > G:+ sc = tl.load(scales + tok_rows[:, None] * GPT + (sgb + garr)[None, :],+ mask = mask_n[:, None] & (garr < G)[None, :], other = 0.0)+ else:+ sc = tl.load(scales + tok_rows[:, None] * GPT + (sgb + garr)[None, :], mask = mask_n[:, None], other = 0.0)+ scx = tl.reshape(tl.broadcast_to(sc[:, :, None], (sc.shape[0], G_PAD, 32)), (sc.shape[0], HD_PAD))+ mh = (1 << (BITS - 1)) - 0.5+ inv_m = 1.0 / (1 << (BITS - 1))+ res = ((raw.to(tl.float32) - mh) * (scx.to(tl.float32) * inv_m)).to(tl.float16)+ return res@triton.jit@@ -923,6 +936,9 @@ def _paged_attn_decode_split_kernel(BLOCK_ROWS: tl.constexpr,BLOCK_N: tl.constexpr,KEY_LO: tl.constexpr = 0, # KVWIN: the pool pass skips the sink positions < KEY_LO (the ring serves them)+ k_cb = None, # TurboQuant codebooks (fp32) and flag: rotation is outside the kernel, H32 slot unused+ v_cb = None,+ TQ: tl.constexpr = 0,):"""Flash-decoding phase 1: one program per (batch, kv_head, h_block, kv split). GQA siblingq heads and query positions share the row axis so K/V tiles are read once per group."""@@ -946,7 +962,7 @@ def _paged_attn_decode_split_kernel(d_mask = offs_d < head_dimq_base = ((batch * q_len + row_q) * n_q_heads + q_head) * head_dimq_tile = tl.load(q + q_base[:, None] + offs_d[None, :], mask=valid_row[:, None] & d_mask[None, :], other=0.0)- if QCK > 0:+ if QCK > 0 and TQ == 0:q_tile = _rot_h32(q_tile, h32, BLOCK_ROWS, HD_PAD)total_k_len = tl.load(cache_seqlens + batch) + kv_append_len@@ -971,7 +987,7 @@ def _paged_attn_decode_split_kernel(if QCK > 0:tok_rows = phys * page_size + page_off- k_tile = _qc_load_kt(k_cache, k_scales, tok_rows, kv_head, offs_d, offs_n < n_end, QCK, n_kv_heads, head_dim, HD_PAD)+ k_tile = _qc_load_kt(k_cache, k_scales, tok_rows, kv_head, offs_d, offs_n < n_end, QCK, n_kv_heads, head_dim, HD_PAD, k_cb, TQ)else:k_ptrs = k_cache + (((phys[None, :] * page_size + page_off[None, :]) * n_kv_heads + kv_head) * head_dim + offs_d[:, None])if HD_PAD > head_dim:@@ -1003,7 +1019,7 @@ def _paged_attn_decode_split_kernel(if QCV > 0:tok_rows_v = phys * page_size + page_off- v_tile = _qc_load_v(v_cache, v_scales, tok_rows_v, kv_head, offs_d, offs_n < n_end, QCV, n_kv_heads, head_dim, HD_PAD)+ v_tile = _qc_load_v(v_cache, v_scales, tok_rows_v, kv_head, offs_d, offs_n < n_end, QCV, n_kv_heads, head_dim, HD_PAD, v_cb, TQ)else:v_ptrs = v_cache + (((phys[:, None] * page_size + page_off[:, None]) * n_kv_heads + kv_head) * head_dim + offs_d[None, :])if HD_PAD > head_dim:@@ -1022,7 +1038,7 @@ def _paged_attn_decode_split_kernel(acc = acc * alpha_s[:, None]l = l * alpha_s + tl.exp(sink - m_top)out_tile = acc / tl.where(l[:, None] == 0.0, 1.0, l[:, None])- if QCV > 0:+ if QCV > 0 and TQ == 0:out_tile = _rot_h32(out_tile, h32, BLOCK_ROWS, HD_PAD)out_base = ((batch * q_len + row_q) * n_q_heads + q_head) * head_dimtl.store(out + out_base[:, None] + offs_d[None, :], out_tile, mask=valid_row[:, None] & d_mask[None, :])@@ -1197,6 +1213,7 @@ def paged_attn_triton_decode(num_stages: int = 2,split_batch: int | None = None, # batch size the split count is derived from (default: bsz)ring = None, # KVWIN: KVWinCtx; pool pass over [S, q-W], fp16 ring partial for the sinks + window+ tq = None, # TurboQuant (cache.tq.TQState): q / ring already rotated, codes read through the codebook) -> torch.Tensor:"""Flash-decoding paged attention for short queries: the kv sequence is split acrossprograms (sized from the block table, so no host sync on cache_seqlens) and reduced in a@@ -1218,12 +1235,12 @@ def paged_attn_triton_decode(_k = (tuple(q.shape), tuple(k_cache.shape), str(window_size), qc is not None, split_batch)if _k not in _ATTN16_SEEN:_ATTN16_SEEN.add(_k); print(" -- attn16 eager decode", _k, "new" if ATTN16 and (qc is not None or _normalize_window(window_size)[0] >= 0) else "old", flush = True)- if qc is not None and _QDEC_HIP and k is None:+ if qc is not None and _QDEC_HIP and k is None and tq is None:out_hip = _qdec_hip_decode(q, k_cache, v_cache, block_table, cache_seqlens, causal, softmax_scale, window_size, softcap,sinks, out, num_splits, max_kv_len, qc, pre_appended_len, n_kv_heads_override, ring)if out_hip is not None:return out_hip- if ATTN16 and (qc is not None or _normalize_window(window_size)[0] >= 0):+ if ATTN16 and tq is None and (qc is not None or _normalize_window(window_size)[0] >= 0):from .triton_paged_cu import paged_attn_triton_decode_cu, NoFittingConfigtry:return paged_attn_triton_decode_cu(@@ -1283,7 +1300,7 @@ def paged_attn_triton_decode(if qc is not None:k_scales, v_scales, qck, qcv = qc- h32 = _get_h32(q.device)+ h32 = tq.eye32 if tq is not None else _get_h32(q.device)else:k_scales, v_scales, qck, qcv = q, q, 0, 0h32 = q@@ -1346,19 +1363,20 @@ def paged_attn_triton_decode(page_size, head_dim, hd_pad, float(softmax_scale),bool(causal), int(window_left), int(window_right), float(softcap or 0.0),ns_total == 1, has_sinks, block_m, block_h, block_rows, block_n, key_lo,+ *((tq.cbk, tq.cbv, 1) if tq is not None else ()),num_warps=num_warps, num_stages=num_stages,)if ring is not None:from .kvwin_triton import ring_splitring_split(ring, q, cache_seqlens, h32, partial_o, partial_ml, ns_total, programs,- q_len, n_q_heads, n_kv_heads, head_dim, hd_pad, softmax_scale, qcv > 0, 1,+ q_len, n_q_heads, n_kv_heads, head_dim, hd_pad, softmax_scale, qcv > 0 and tq is None, 1,block_m, block_h, block_rows)if ns_total > 1:_paged_attn_decode_combine_kernel[(programs,)](partial_o, partial_ml, out, h32,- ns_total, sinks, qcv, has_sinks, q_len, n_q_heads, n_kv_heads, head_dim, hd_pad,+ ns_total, sinks, 0 if tq is not None else qcv, has_sinks, q_len, n_q_heads, n_kv_heads, head_dim, hd_pad,block_m, block_h, block_rows,num_warps=4, num_stages=1,)@@ -1915,6 +1933,7 @@ def paged_attn_triton_prefill(v_new: torch.Tensor | None = None,v_dim: int | None = None,ring = None, # KVWIN: KVWinCtx; the staged scratch gets exact sinks / window / chunk rows+ tq = None, # TurboQuant (cache.tq.TQState): always staged, the scratch is the rotated domain) -> torch.Tensor:"""Prefill (large q_len) attention over the paged cache.@@ -2016,8 +2035,10 @@ def paged_attn_triton_prefill(# the allocator sees a handful of distinct sizes. Context-shaped workspaces are not# kept as statics: the old pool-sized static held a full fp16 copy of the cache# (1 GiB per 512k tokens on Qwen3.8) for the life of the process- if (_qc_staging == 1 and q_len >= (_qc_prefill_two_pass_min_q if ring is None else min(_qc_prefill_two_pass_min_q, 17))- and new_kv_mode == 0 and k is None and causal):+ if tq is not None and not (new_kv_mode == 0 and k is None and causal):+ raise ValueError("TurboQuant cache: prefill is causal, staged, without appended k/v only")+ if (tq is not None or (_qc_staging == 1 and q_len >= (_qc_prefill_two_pass_min_q if ring is None else min(_qc_prefill_two_pass_min_q, 17))+ and new_kv_mode == 0 and k is None and causal)):from ...ext import exllamav3_ext as extnpps_w = block_table.shape[1]if max_kv_len is not None:@@ -2027,10 +2048,15 @@ def paged_attn_triton_prefill(pages_alloc = max(1, 1 << (bsz * npps_w - 1).bit_length())kd = torch.empty((pages_alloc, page_size, n_kvh, head_dim), dtype = torch.half, device = q.device)vd = torch.empty((pages_alloc, page_size, n_kvh, head_dim), dtype = torch.half, device = q.device)- ext.dequant_cache_paged_window(- k_cache, k_scales, kd, v_cache, v_scales, vd,- cache_seqlens, block_table, page_size, kv_append_len, 0.0,- )+ if tq is not None:+ from .tq_triton import tq_dequant_window+ tq_dequant_window(k_cache, k_scales, tq.cbk, kd, cache_seqlens, block_table, page_size, kv_append_len, qck, n_kvh, head_dim)+ tq_dequant_window(v_cache, v_scales, tq.cbv, vd, cache_seqlens, block_table, page_size, kv_append_len, qcv, n_kvh, head_dim)+ else:+ ext.dequant_cache_paged_window(+ k_cache, k_scales, kd, v_cache, v_scales, vd,+ cache_seqlens, block_table, page_size, kv_append_len, 0.0,+ )if ring is not None:from .kvwin_triton import stage_patchstage_patch(ring, kd, vd, cache_seqlens, npps_w * page_size, q_len)@@ -2488,6 +2514,7 @@ def fn_triton_paged_attn_decode_qc(args: AttnArgs) -> torch.Tensor | None:n_kv_heads_override=args.num_kv_heads,max_kv_len=args.max_kv_len,ring=args.ov,+ tq=args.tq,)@@ -2504,6 +2531,8 @@ def fn_triton_paged_attn_prefill_qc(args: AttnArgs) -> torch.Tensor | None:# Span chunks of any length expand into per-span reads over the packed cache (the decode# qc fn declines spans, so short span chunks land here too)if args.non_causal_spans:+ if args.tq is not None:+ raise NotImplementedError("TurboQuant KV cache with non-causal spans (VLM image chunks)")arglist = get_non_causal_span_arglist(args)return torch.cat([paged_attn_triton_prefill(**a) for a in arglist], dim=1)@@ -2523,4 +2552,5 @@ def fn_triton_paged_attn_prefill_qc(args: AttnArgs) -> torch.Tensor | None:n_kv_heads_override=args.num_kv_heads,max_kv_len=args.max_kv_len,ring=args.ov,+ tq=args.tq,)diff --git a/tests/test_tq_cache.py b/tests/test_tq_cache.pynew file mode 100644index 0000000..f9da18c--- /dev/null+++ b/tests/test_tq_cache.py@@ -0,0 +1,144 @@+"""TurboQuant KV cache (cache/tq.py): codec reference, Triton writer / window dequant bit-exactness, and the dispatched attention+(rotation outside the kernels, codebook loaders, KVWIN ring, staged prefill) against a torch reference over the dequantized pool.++Tiny shapes on any GPU, or on CPU through the Triton interpreter: TQ_TEST_CPU=1 pytest tests/test_tq_cache.py"""+import os, sys, types, math, contextlib+CPU = os.environ.get("TQ_TEST_CPU") == "1"+if CPU:+ os.environ["TRITON_INTERPRET"] = "1"+import torch++sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))+import pytest++from exllamav3.cache import tq+from exllamav3.cache.kvwin import KVWinLayerState, KVWinCtx, KVWinCfg, parse_spec++DEV = "cpu" if CPU else "cuda:0"+PAGE = 256+needs_gpu = pytest.mark.skipif(not CPU and not torch.cuda.is_available(), reason = "needs a GPU (or TQ_TEST_CPU=1)")++[email protected](autouse = True)+def cpu_env(monkeypatch):+ if not CPU:+ return+ from exllamav3.modules.attention_fn import triton_paged, triton_paged_cu+ props = types.SimpleNamespace(multi_processor_count = 8, major = 8, minor = 6, shared_memory_per_block_optin = 99 * 1024)+ monkeypatch.setattr(torch.cuda, "device", lambda d: contextlib.nullcontext())+ monkeypatch.setattr(torch.cuda, "get_device_properties", lambda d: props)+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda d = None: (8, 6))+ monkeypatch.setattr(torch.cuda, "synchronize", lambda *a, **k: None)+ for mod in (triton_paged, triton_paged_cu):+ monkeypatch.setattr(mod, "_check_tensor", lambda *a, **k: None)+ monkeypatch.setattr(mod, "_same_device", lambda *a, **k: True)+++def test_codec_unbiased_norm():+ # norm correction: the decoded vector has exactly the input norm (up to the fp16 scale)+ for D in (128, 256):+ for b in (5, 6):+ st = tq.TQState.get(D, b, b, "cpu")+ x = torch.randn(512, D) * 3+ y = (x @ st.rot_t32)+ w, s = tq.encode_ref(y, st.cbk, st.midk, b)+ r = tq.decode_ref(w, s, st.cbk, b, D).float()+ assert ((r.norm(dim = -1) / y.norm(dim = -1)) - 1).abs().max() < 2e-3+ assert ((r @ st.rot32 - x).norm() / x.norm()) < {5: 0.055, 6: 0.03}[b]+++def test_rotation_orthonormal():+ for D in (64, 128, 256):+ m = tq.rotation(D)+ assert torch.allclose(m @ m.t(), torch.eye(D), atol = 1e-5)+++@needs_gpu[email protected]("D,bits", [(128, 5), (128, 6), (256, 5), (256, 6)])+def test_triton_write_and_window_dequant_exact(D, bits):+ from exllamav3.modules.attention_fn import tq_triton as T+ HKV = 2+ st = tq.TQState.get(D, bits, bits, DEV)+ bsz, length, pages = 2, 3, 6+ bt = torch.tensor([[3, 1, 5], [0, 4, 2]], dtype = torch.int32, device = DEV)+ cs = torch.tensor([PAGE - 1, 2 * PAGE - 2], dtype = torch.int32, device = DEV) # straddle page boundaries+ x = torch.randn(bsz, length, HKV, D, device = DEV).half()+ words = torch.zeros(pages, PAGE, HKV * D // 32 * bits, dtype = torch.int32, device = DEV)+ sc = torch.zeros(pages, PAGE, HKV, dtype = torch.half, device = DEV)+ T._tq_write_kernel[(bsz * length, HKV)](x, words, sc, st.cbk, st.midk, bt, cs, length, bt.shape[1], bits, PAGE, HKV, D)+ 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))+ 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)+ 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)+++class Rig:+ """TQ pool + KVWIN ring for one sequence, driven through attn_dispatch like the attention module does."""++ def __init__(self, bits, hd = 128, kvh = 2, qh = 8, pages = 4, S = 4, W = 32, seed = 0):+ from exllamav3.cache.tq import CacheLayer_tq+ self.bits, self.hd, self.kvh, self.qh, self.S, self.W = bits, hd, kvh, qh, S, W+ self.g = torch.Generator(device = DEV).manual_seed(seed)+ attn = types.SimpleNamespace(num_kv_heads = kvh, head_dim = hd, window_arg = lambda: -1, logit_softcapping = 0.0)+ self.cl = CacheLayer_tq(None, attn, 0, pages * PAGE, bits, bits)+ self.cl.alloc(torch.device(DEV))+ self.st = KVWinLayerState(attn, 2, 0, 0)+ self.st.cfg = KVWinCfg(S, W, W + 16, S + W + 16)+ self.st.cache_layer = self.cl+ self.st.alloc(torch.device(DEV))+ self.slots = torch.tensor([1], dtype = torch.int32, device = DEV)+ self.bt = torch.arange(pages, dtype = torch.int32, device = DEV).view(1, -1)+ self.len = 0+ self.K = torch.empty(0, kvh, hd, dtype = torch.half, device = DEV)+ self.V = torch.empty(0, kvh, hd, dtype = torch.half, device = DEV)++ def rnd(self, *shape):+ x = torch.randn(*shape, device = DEV, generator = self.g)+ return (x * (0.5 + torch.rand(*shape[:-1], 1, device = DEV, generator = self.g) * 2)).half()++ def step(self, n):+ from exllamav3.modules.attention_fn.dispatch import attn_dispatch+ q, k, v = self.rnd(1, n, self.qh, self.hd), self.rnd(1, n, self.kvh, self.hd), self.rnd(1, n, self.kvh, self.hd)+ sl = torch.tensor([self.len], dtype = torch.int32, device = DEV)+ o = attn_dispatch(q, k, v, cache = self.cl, causal = True, block_table = self.bt, cache_seqlens = sl,+ max_kv_len = self.len + n, ov = KVWinCtx(self.st, self.slots))+ L = self.len+ self.K = torch.cat([self.K, k[0]]); self.V = torch.cat([self.V, v[0]]); self.len += n+ return q[0], o[0], L++ def ref(self, q, L): # q [n, qh, hd] at positions L..L+n-1+ """fp32 reference: sinks + window rows exact, every other position from the dequantized (natural domain) pool."""+ st = self.cl.get_tq()+ k, v = self.cl.get_kv(None, None)+ kd = k.view(-1, self.kvh, self.hd)[: self.len].float(); vd = v.view(-1, self.kvh, self.hd)[: self.len].float()+ ke, ve = self.K.float(), self.V.float()+ out = torch.empty(q.shape, dtype = torch.float32, device = DEV)+ grp = self.qh // self.kvh+ for i in range(q.shape[0]):+ qa = L + i+ pos = torch.arange(qa + 1, device = DEV)+ # decode / verify (n <= 16): per-row window; prefill chunk: the past window [L-W, L) and every chunk row are exact+ exact = (pos < self.S) | ((pos > qa - self.W) if q.shape[0] <= 16 else (pos >= L - self.W))+ kk = torch.where(exact[:, None, None], ke[: qa + 1], kd[: qa + 1]).repeat_interleave(grp, dim = 1)+ vv = torch.where(exact[:, None, None], ve[: qa + 1], vd[: qa + 1]).repeat_interleave(grp, dim = 1)+ s = torch.einsum("hd,thd->ht", q[i].float(), kk) / math.sqrt(self.hd)+ out[i] = torch.einsum("ht,thd->hd", s.softmax(-1), vv)+ return out+++@needs_gpu[email protected]("hd,bits", [(128, 5), (128, 6), (256, 5), (256, 6)])+def test_dispatch_matches_dequantized_reference(hd, bits):+ rig = Rig(bits, hd = hd)+ for n in (300, 1, 1, 5, 40, 1): # staged prefill chunk, decode, verify, a second chunk+ q, o, L = rig.step(n)+ r = rig.ref(q, L)+ err = ((o.float() - r).norm() / r.norm()).item()+ assert err < 6e-3, (hd, bits, n, L, err)diff --git a/tools/qwen/serve.py b/tools/qwen/serve.pyindex dd9cc60..d8d3317 100644--- a/tools/qwen/serve.py+++ b/tools/qwen/serve.py@@ -715,7 +715,7 @@ class QwenEngine:def __init__(self, model_path: str, ctx: int, ndt: int = 7, draft_policy: str = "mix",vision: bool = True, max_chunk_size: int = 2048, cache_bits: int = 0, sessions: int = 1,- k_bits: int = 0, v_bits: int = 0, dflash_dir: str = ""):+ k_bits: int = 0, v_bits: int = 0, dflash_dir: str = "", kv_mode: str = "quant"):# The measured Qwen serving configuration. Read at import time by the engine:# set before importing exllamav3. The caller's environment wins.import torch@@ -769,6 +769,15 @@ class QwenEngine:from exllamav3 import CacheLayer_quantqkw = 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+ 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):+ qkw["layer_type"] = CacheLayer_tq+ else:+ print(f"qserve: --kv-mode tq: head_dim {hd} is not supported, keeping the quant cache", flush=True)# one recurrent (GDN) slot per session; the Generator caps its batch at the slot countself.cache = Cache(self.model, max_num_tokens=ctx, max_history=max(3, ndt), max_batch_size=sessions, **qkw)if os.environ.get("EXL3_WARM_DENSE", "1") != "0":@@ -2253,7 +2262,7 @@ def load_all(args: argparse.Namespace):f"defaults={ {k: v for k, v in defaults.items() if v is not None} }", flush=True)engine = QwenEngine(model_dir, args.ctx, ndt=args.ndt, draft_policy=args.draft_policy, vision=not args.no_vision,cache_bits=args.cache_bits, sessions=args.sessions,- k_bits=args.k_bits, v_bits=args.v_bits, dflash_dir=str(Path(args.dflash_dir).expanduser()))+ k_bits=args.k_bits, v_bits=args.v_bits, dflash_dir=str(Path(args.dflash_dir).expanduser()), kv_mode=args.kv_mode)env = {k: v for k, v in sorted(os.environ.items()) if k.startswith(("EXL3_", "MPW"))}print(f"qserve: effective env {env}", flush=True)from exllamav3.generator.slot_store import SlotStore@@ -2300,6 +2309,8 @@ 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="quant",+ 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("--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)")parser.add_argument("--draft-policy", choices=("mix", "mtp", "dflash", "off"), default="mix",help="mix = shipped rule (MTP + n-gram lookup, lossless), mtp = fixed MTP chain, dflash = DFlash2 block drafter "