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: fp16 sink + recent-window ring next to the quantized pool (EXL3_KVWIN=sink:window, default off)
YanissAmz874a523c04ef
diff --git a/exllamav3/cache/cache.py b/exllamav3/cache/cache.pyindex a177da4..f6259f8 100644--- a/exllamav3/cache/cache.py+++ b/exllamav3/cache/cache.py@@ -168,7 +168,9 @@ class Cache:self.recurrent_layers = {}for layer in rl:for instance in self.model.get_layer_instances(layer.layer_idx):- self.recurrent_layers[instance] = layer.layer_state_cls(layer, max_batch_size, max_history, id(self))+ self.recurrent_layers[instance] = state = layer.layer_state_cls(layer, max_batch_size, max_history, id(self))+ if hasattr(state, "bind"):+ state.bind(self.layers.get(instance))# Attachself.recurrent_instances = {}diff --git a/exllamav3/cache/kvwin.py b/exllamav3/cache/kvwin.pynew file mode 100644index 0000000..2c5c6cd--- /dev/null+++ b/exllamav3/cache/kvwin.py@@ -0,0 +1,251 @@+"""+KVWIN: exact (fp16) sink tokens + recent window on top of a quantized KV cache.++The paged quantized pool stays complete and unchanged (save/restore, prefix disk, fork and copy_page never see+the overlay). Next to it every active job owns one RING of fp16 K/V rows per full-attention layer: S sink rows+(positions 0..S-1) and a cyclic region of Rc = W + MAX_DRAFT rows holding the last Rc positions. Attention reads+the quantized pool for positions [S, q-W] and the ring for the sinks and [q-W+1, q] (an extra partial merged by the+existing flash-decoding combine), so a speculative verify of up to MAX_DRAFT rows never evicts a live window row.++The ring is per-job state with the lifecycle of the job's recurrent state: it rides the recurrent-state slot+(Cache.get_new_state / new_from_stashed / free), is stashed with the checkpoints (RecurrentCache, tail stash,+prefix disk) and restored bitwise with them. A stash without a ring blob (written with the switch off) restores+as "cold": the ring is rebuilt from the dequantized pool the first time the job attends (fill).++EXL3_KVWIN=S:W (e.g. 4:128) turns it on for CacheLayer_quant layers of models that have recurrent state slots;+unset / 0 / empty = off, which leaves every code path bit-identical to a build without this file.+"""+from __future__ import annotations+import os+from typing import NamedTuple+import torch+from ..constants import PAGE_SIZE++ANY_ACTIVE = False # a bound ring exists in this process: the whole-forward graph declines (it cannot fill cold rings)+MAX_DRAFT = 16 # rows one verify step writes at once (BC_Attention MAX_QLEN, the decode kernels' q_len cap)+++class KVWinCfg(NamedTuple):+ S: int # sink rows+ W: int # window rows+ Rc: int # cyclic rows (W + MAX_DRAFT)+ R: int # ring rows (S + Rc)+++def parse_spec(spec: str | None) -> KVWinCfg | None:+ """'S:W' -> KVWinCfg; None / '' / '0' / 'off' -> None."""+ if spec is None:+ return None+ spec = spec.strip().lower()+ if spec in ("", "0", "off", "false"):+ return None+ try:+ s, w = spec.split(":")+ S, W = int(s), int(w)+ except ValueError:+ raise ValueError(f"EXL3_KVWIN must be 'sink:window' (e.g. 4:128), got {spec!r}")+ if S < 0 or W < 1 or S + W > PAGE_SIZE * 8:+ raise ValueError(f"EXL3_KVWIN={spec}: need sink >= 0 and 1 <= window, sink + window <= {PAGE_SIZE * 8}")+ return KVWinCfg(S, W, W + MAX_DRAFT, S + W + MAX_DRAFT)+++def env_cfg() -> KVWinCfg | None:+ return parse_spec(os.environ.get("EXL3_KVWIN"))+++def ring_rows(pos: torch.Tensor, cfg: KVWinCfg) -> torch.Tensor:+ """Ring row of absolute position(s) pos."""+ return torch.where(pos < cfg.S, pos, cfg.S + (pos - cfg.S) % cfg.Rc)+++def ring_positions(end: int, cfg: KVWinCfg) -> torch.Tensor:+ """Position held by every ring row once positions < end were written; -1 = row never written."""+ r = torch.arange(cfg.R)+ last = end - 1+ p = torch.where(r < cfg.S, r, last - (last - cfg.S - (r - cfg.S)) % cfg.Rc)+ return torch.where((r < cfg.S) & (r > last) | (r >= cfg.S) & (p < cfg.S), torch.full_like(p, -1), p)+++def ov_write_ref(ov_k, ov_v, slot: int, k: torch.Tensor, v: torch.Tensor, start: int, cfg: KVWinCfg):+ """Reference writer, one sequence: k, v [q_len, kvh, hd] are positions start..start+q_len-1."""+ for t in range(k.shape[0]):+ p = start + t+ row = p if p < cfg.S else cfg.S + (p - cfg.S) % cfg.Rc+ ov_k[slot, row] = k[t]+ ov_v[slot, row] = v[t]+++class KVWinCtx(NamedTuple):+ """What attn_dispatch needs for one attention call: the layer's ring tensors and the per-row slots."""+ state: "KVWinLayerState"+ slots: torch.Tensor # [bsz] int32 on the layer's device+ chunk_k: torch.Tensor | None = None # prefill only: the chunk's own fp16 K / V rows [bsz, q_len, kvh, hd]+ chunk_v: torch.Tensor | None = None++ @property+ def cfg(self) -> KVWinCfg:+ return self.state.cfg+++class KVWinLayerState:+ """Recurrent-layer-state protocol (see SWALayerState / GDNLayerState) for the ring of one full-attention layer."""++ kvwin = True+ rewind_noop = True # positional ring: a rewind of <= MAX_DRAFT rows just leaves stale rows to be overwritten++ def __init__(self, module, max_batch_size: int, max_history: int, cache_id: int):+ self.module = module+ self.max_batch_size = max_batch_size+ self.max_history = max_history+ self.cache_id = cache_id+ self.cfg: KVWinCfg | None = None+ self.cache_layer = None+ self.device = None+ self.ov_k = None+ self.ov_v = None+ self.cold = [False] * max_batch_size++ # -- Cache.__init__ hook ---------------------------------------------------------------------------------------+ def bind(self, cache_layer):+ """Called once the cache layer of this attention exists. Inert unless EXL3_KVWIN is set and the layer is a+ plain quantized cache."""+ from .quant import CacheLayer_quant+ cfg = env_cfg()+ m = self.module+ if (cfg is None or not isinstance(cache_layer, CacheLayer_quant) or cache_layer.compand_a != 0.0 or+ m.head_dim % 32 != 0 or m.window_arg() not in (None, -1, (-1, -1)) or m.logit_softcapping):+ return+ self.cfg = cfg+ self.cache_layer = cache_layer+ global ANY_ACTIVE+ ANY_ACTIVE = True+ cache_layer.kvwin = self # BC_Attention (graph decode) and the whole-forward graph decline such layers++ @property+ def active(self) -> bool:+ return self.cfg is not None and self.ov_k is not None++ def _shape(self):+ m = self.module+ return (self.max_batch_size, self.cfg.R, m.num_kv_heads, m.head_dim)++ # -- recurrent layer state protocol ----------------------------------------------------------------------------+ def alloc(self, device):+ self.device = device+ if self.cfg is not None:+ self.ov_k = torch.zeros(self._shape(), dtype = torch.half, device = device)+ self.ov_v = torch.zeros(self._shape(), dtype = torch.half, device = device)+ self.cold = [False] * self.max_batch_size++ def free(self):+ self.ov_k = None+ self.ov_v = None+ self.device = None++ def clear(self, idx: int):+ if self.active:+ self.ov_k[idx].zero_()+ self.ov_v[idx].zero_()+ self.cold[idx] = False++ def get_checkpoint_size(self):+ if self.cfg is None:+ return 0+ m = self.module+ return 2 * self.cfg.R * m.num_kv_heads * m.head_dim * 2++ def storage_size(self):+ if self.cfg is None:+ return 0+ return 2 * int(torch.Size(self._shape()).numel()) * 2++ def get_state_tensors(self):+ return (self.ov_k, self.ov_v) if self.active else ()++ def rewind(self, slot: int, last_history: int, num_tokens: int):+ pass++ def stash(self, slot, position: int = 0, pinned: bool = False):+ if not self.active:+ return None+ if pinned:+ out = tuple(torch.empty(t.shape[1:], dtype = t.dtype, pin_memory = True) for t in (self.ov_k, self.ov_v))+ for d, s in zip(out, (self.ov_k[slot], self.ov_v[slot])):+ d.copy_(s, non_blocking = True)+ return out+ return (self.ov_k[slot].cpu(), self.ov_v[slot].cpu())++ def unstash(self, slot, stashed, position: int = 0):+ if not self.active:+ return+ if stashed is None:+ self.cold[slot] = True+ return+ k, v = stashed+ self.ov_k[slot].copy_(k)+ self.ov_v[slot].copy_(v)+ self.cold[slot] = False++ def unstash_missing(self, slot):+ """The checkpoint carries no ring (written with KVWIN off): rebuild from the pool at the first attention."""+ if self.active:+ self.cold[slot] = True++ def tp_export(self, plan):+ raise NotImplementedError("EXL3_KVWIN does not support tensor parallel loading")++ # -- fill from the quantized pool --------------------------------------------------------------------------------+ def fill(self, slot: int, block_table_row: torch.Tensor, length: int):+ """Rebuild slot's ring for a sequence of `length` positions from the dequantized pool: sink rows and the last+ W positions (all that attention reads next). block_table_row: [pages] int32."""+ from exllamav3.ext import exllamav3_ext as ext+ cfg, cl = self.cfg, self.cache_layer+ self.ov_k[slot].zero_()+ self.ov_v[slot].zero_()+ pos = torch.cat([+ torch.arange(0, min(cfg.S, length)),+ torch.arange(max(cfg.S, length - cfg.W), length),+ ])+ self.cold[slot] = False+ if pos.numel() == 0:+ return+ pos = pos.to(block_table_row.device)+ page = block_table_row.index_select(0, pos // PAGE_SIZE).long()+ tok = page * PAGE_SIZE + pos % PAGE_SIZE+ m = self.module+ dim = m.num_kv_heads * m.head_dim+ G = dim // 32+ rows = ring_rows(pos, cfg)+ for 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()+ out = torch.empty((pos.numel(), dim), dtype = torch.half, device = q.device)+ ext.dequant_cache_cont(qr, sr, out, cl.compand_a)+ dst[slot].index_copy_(0, rows, out.view(-1, m.num_kv_heads, m.head_dim))+++def make_ctx(cache_layer_state: KVWinLayerState | None, params: dict, device, bsz: int) -> KVWinCtx | None:+ """Ring context of one attention call from params["recurrent_states"] (one state per batch row), or None+ when the ring is inert or the call has no job states (plain batched forward: quantized cache only)."""+ st = cache_layer_state+ if st is None or not st.active:+ return None+ rs = params.get("recurrent_states")+ if not rs or len(rs) != bsz or "recurrent_slots" not in params:+ return None+ from ..util.tensor import get_for_device+ return KVWinCtx(st, get_for_device(params, "recurrent_slots", device))+++def ensure_filled(ctx: KVWinCtx | None, params: dict, block_table: torch.Tensor):+ """Rebuild the rings of cold slots (restored from a checkpoint without a ring) before they are attended."""+ if ctx is None:+ return+ st = ctx.state+ cold = [i for i, r in enumerate(params["recurrent_states"]) if st.cold[r.slot]]+ if not cold:+ return+ from ..util.tensor import get_for_device+ seqlens = get_for_device(params, "cache_seqlens", "cpu")+ for i in cold:+ st.fill(params["recurrent_states"][i].slot, block_table[i], int(seqlens[i]))diff --git a/exllamav3/model/cuda_graph.py b/exllamav3/model/cuda_graph.pyindex 25f7fe5..fac08ae 100644--- a/exllamav3/model/cuda_graph.py+++ b/exllamav3/model/cuda_graph.py@@ -311,6 +311,9 @@ class CudaGraphRunner:return "no_block_table"if params.get("indexed_embeddings"):return "state"+ from ..cache import kvwin+ if kvwin.ANY_ACTIVE:+ return "kvwin" # the ring writes / cold fills run in Python between layersrs = params.get("recurrent_states")if self.has_gdn or self.has_conv or self.has_mamba or self.has_swa:slots = params.get("recurrent_slots")diff --git a/exllamav3/model/model.py b/exllamav3/model/model.pyindex 1fa01b8..25957cf 100644--- a/exllamav3/model/model.py+++ b/exllamav3/model/model.py@@ -69,7 +69,11 @@ class Model(Model_TPMixin, Model_LSMixin):@cached_propertydef _get_recurrent_layers(self):- return [m for m in self if m.caps.get("recurrent_cache")]+ rl = [m for m in self if m.caps.get("recurrent_cache")]+ if self.recurrent_state_cls is None:+ # KVWIN rings ride the job's recurrent state: a model without recurrent state slots has none+ rl = [m for m in rl if not getattr(getattr(m, "layer_state_cls", None), "kvwin", False)]+ return rldef get_recurrent_layers(self):return self._get_recurrent_layersdiff --git a/exllamav3/modules/attention_fn/bc_attn.py b/exllamav3/modules/attention_fn/bc_attn.pyindex f9014c6..d993bb6 100644--- a/exllamav3/modules/attention_fn/bc_attn.py+++ b/exllamav3/modules/attention_fn/bc_attn.py@@ -324,14 +324,14 @@ class BCAttn:} | {n: "constexpr" for n in ("QCK", "QCV", "q_len", "kv_append_len", "n_q_heads", "n_kv_heads","page_size", "head_dim", "HD_PAD", "scale", "CAUSAL", "WINDOW_LEFT", "WINDOW_RIGHT",- "SOFTCAP", "FINAL", "HAS_SINKS") + (() if ATTN16 else ("BLOCK_M", "BLOCK_H")) + ("BLOCK_ROWS", "BLOCK_N")}+ "SOFTCAP", "FINAL", "HAS_SINKS") + (() if ATTN16 else ("BLOCK_M", "BLOCK_H")) + ("BLOCK_ROWS", "BLOCK_N", "KEY_LO")}consts = dict(QCK = self.k_bits, QCV = self.v_bits,q_len = q_len, kv_append_len = q_len, n_q_heads = qh, n_kv_heads = kvh,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,+ BLOCK_ROWS = block_rows, BLOCK_N = block_n, KEY_LO = 0,)if not ATTN16:consts |= dict(BLOCK_M = block_m, BLOCK_H = block_h)@@ -753,6 +753,10 @@ def build_bc_attn(module, layer):from ...cache.qsa import QSAPlanesm = 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+ _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 82c5894..6e57b24 100644--- a/exllamav3/modules/attention_fn/common.py+++ b/exllamav3/modules/attention_fn/common.py@@ -29,6 +29,7 @@ class AttnArgs(NamedTuple):# block-table span; e.g. QSA's dense regime)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)def sanity_check(self):# Cache must be pageddiff --git a/exllamav3/modules/attention_fn/dispatch.py b/exllamav3/modules/attention_fn/dispatch.pyindex f6c27d0..c66742c 100644--- a/exllamav3/modules/attention_fn/dispatch.py+++ b/exllamav3/modules/attention_fn/dispatch.py@@ -1,6 +1,8 @@import torchfrom ...cache import CacheLayer, Cache, CacheLayer_quantfrom .common import AttnArgs, AttnFn+from ...cache.kvwin import MAX_DRAFT+from .kvwin_triton import ov_writefrom .bighead_scalar import fn_bighead_scalar_attnfrom .torch import fn_torch_sdpa_fallback_cache, fn_torch_sdpa_fallback_nocachefrom .xformers import fn_xformers_cutlass_fallback_cache, fn_xformers_cutlass_fallback_nocache@@ -98,6 +100,7 @@ def attn_dispatch(dispatch_cache: dict | None = None,max_kv_len: int | None = None,v_dim: int | None = None,+ ov = None,):"""Select and run the first compatible attention implementation for the supplied tensors.@@ -113,6 +116,7 @@ def attn_dispatch(# kernels when possible: new K/V are quantized into the cache up front and never# materialized as full fp16 cache-sized temporariesq_cache = None+ ov_attend = Falseif cache is not None:assert block_table is not Noneassert cache_seqlens is not None@@ -128,6 +132,17 @@ def attn_dispatch(layer.update_kv_direct(cache_seqlens, block_table, k, v, q_len)q_cache = layer.get_qkv()k_cache, v_cache = None, None+ # KVWIN: decode / verify rows enter the ring before attending (the ring pass includes the row's own key);+ # a prefill chunk attends the ring as it was before the chunk (window patch of the staged scratch) and+ # enters it afterwards+ # (every quant-direct call writes the ring, even one that cannot attend it, so no row is ever stale)+ ov_attend = ov is not None and causal and not non_causal_spans and not softcap and \+ window_size in (None, -1, (-1, -1))+ if ov is not None:+ if q_len <= MAX_DRAFT:+ ov_write(ov, k, v, cache_seqlens, q_len)+ else:+ ov = ov._replace(chunk_k = k, chunk_v = v)else:# Only the left bound governs how much of the paged cache has to be fetched_wl = window_size[0] if isinstance(window_size, tuple) else window_size@@ -156,6 +171,7 @@ def attn_dispatch(sinks,max_kv_len = max_kv_len,v_dim = v_dim,+ ov = ov if q_cache is not None and ov_attend else None,)# 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@@ -180,6 +196,9 @@ def attn_dispatch(if dispatch_cache is not None:dispatch_cache[hint_key] = fn+ 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)+# 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:if isinstance(cache, CacheLayer):diff --git a/exllamav3/modules/attention_fn/kvwin_triton.py b/exllamav3/modules/attention_fn/kvwin_triton.pynew file mode 100644index 0000000..6f1aecf--- /dev/null+++ b/exllamav3/modules/attention_fn/kvwin_triton.py@@ -0,0 +1,221 @@+"""KVWIN kernels (see cache/kvwin.py): ring writer and the fp16 ring partial of the flash-decoding split."""+import torch+import triton+import triton.language as tl+from ...cache.kvwin import KVWinCtx+++def _ov_write_kernel(+ k, v, ov_k, ov_v, slots, seqlens,+ q_len, S, Rc, R,+ n_kv_heads: tl.constexpr,+ head_dim: tl.constexpr,+ HD_PAD: tl.constexpr,+):+ """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+ twice with the same bytes."""+ b = tl.program_id(0)+ j = tl.program_id(1)+ h = tl.program_id(2)+ L = tl.load(seqlens + b)+ slot = tl.load(slots + b)+ 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))+ row = tl.where(p < S, p, S + (p - S) % Rc)+ offs = tl.arange(0, HD_PAD)+ m = (offs < head_dim) & ok+ src = ((b * q_len + t) * n_kv_heads + h).to(tl.int64) * head_dim+ dst = ((slot.to(tl.int64) * R + row) * n_kv_heads + h) * head_dim+ tl.store(ov_k + dst + offs, tl.load(k + src + offs, mask = m, other = 0.0), mask = m)+ tl.store(ov_v + dst + offs, tl.load(v + src + offs, mask = m, other = 0.0), mask = m)+++def ov_write(ctx: KVWinCtx, k: torch.Tensor, v: torch.Tensor, cache_seqlens: torch.Tensor, q_len: int):+ """Write the K/V rows just appended to the pool (k, v: [bsz, q_len, kvh, hd] fp16, positions cache_seqlens[b]..+q_len)+ into the ring: the sinks that lie in this call and its last Rc rows (earlier rows of a long prefill chunk would be+ overwritten inside the same call)."""+ st, slots = ctx.state, ctx.slots+ cfg = st.cfg+ bsz, _, n_kv_heads, head_dim = k.shape+ k = k.contiguous()+ v = v.contiguous()+ 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,+ n_kv_heads, head_dim, triton.next_power_of_2(head_dim),+ num_warps = 1,+ )+++def _ring_split_kernel(+ q, ov_k, ov_v, slots, cache_seqlens, h32,+ partial_o, partial_ml,+ ns_total, # runtime: partial stride (quant splits + 1); the ring partial is the last one+ sinks_n, win, Rc, R, # runtime: S, W, Rc, R+ q_len: tl.constexpr,+ n_q_heads: tl.constexpr,+ n_kv_heads: tl.constexpr,+ head_dim: tl.constexpr,+ HD_PAD: tl.constexpr,+ scale: tl.constexpr,+ ROT_V: tl.constexpr, # quantized V: the partial must live in the H32-rotated domain like the pool partials+ DENSE: tl.constexpr, # row layout: True = dense (query, head) rows (CUDA kernels), False = padded (legacy kernel)+ BLOCK_M: tl.constexpr,+ BLOCK_H: tl.constexpr,+ BLOCK_ROWS: tl.constexpr,+ BLOCK_N: tl.constexpr,+):+ """fp16 pass over the ring: sinks (positions < S) and the window [q-W+1, q] of every query row, stored as one more+ flash-decoding partial (m, l, unnormalised acc) for the existing combine."""+ pid = tl.program_id(0)+ group_size = n_q_heads // n_kv_heads+ rows = tl.arange(0, BLOCK_ROWS)+ if DENSE:+ h_blocks = tl.cdiv(q_len * group_size, BLOCK_ROWS)+ h_block = pid % h_blocks+ bh = pid // h_blocks+ row_idx = h_block * BLOCK_ROWS + rows+ row_q = row_idx % q_len+ row_h_local = row_idx // q_len+ valid_row = row_idx < q_len * group_size+ else:+ h_blocks = tl.cdiv(group_size, BLOCK_H)+ h_block = pid % h_blocks+ bh = pid // h_blocks+ row_q = rows % BLOCK_M+ row_h_local = h_block * BLOCK_H + (rows // BLOCK_M)+ valid_row = (row_q < q_len) & (row_h_local < group_size)+ batch = bh // n_kv_heads+ kv_head = bh - batch * n_kv_heads+ q_head = kv_head * group_size + row_h_local++ offs_d = tl.arange(0, HD_PAD)+ d_mask = offs_d < head_dim+ q_base = ((batch * q_len + row_q) * n_q_heads + q_head) * head_dim+ q_tile = tl.load(q + q_base[:, None] + offs_d[None, :], mask = valid_row[:, None] & d_mask[None, :], other = 0.0)++ L = tl.load(cache_seqlens + batch)+ slot = tl.load(slots + batch).to(tl.int64)+ q_abs = L + row_q+ last = L + q_len - 1 # newest position in the ring++ m = tl.full((BLOCK_ROWS,), -float("inf"), tl.float32)+ l = tl.zeros((BLOCK_ROWS,), tl.float32)+ acc = tl.zeros((BLOCK_ROWS, HD_PAD), tl.float32)+ for r0 in range(0, R, BLOCK_N):+ offs = r0 + tl.arange(0, BLOCK_N)+ in_ring = offs < R+ # position stored in ring row `offs` (rows >= S are cyclic: the one of the last Rc positions with that residue)+ back = (last - sinks_n - (offs - sinks_n)) % Rc+ back = tl.where(back < 0, back + Rc, back)+ pos = tl.where(offs < sinks_n, offs, last - back)+ base = ((slot * R + offs) * n_kv_heads + kv_head) * head_dim+ k_tile = tl.load(ov_k + base[None, :] + offs_d[:, None], mask = in_ring[None, :] & d_mask[:, None], other = 0.0)+ scores = tl.dot(q_tile, k_tile) * scale+ is_sink = (offs < sinks_n)[None, :]+ pos2 = pos[None, :]+ ok = tl.where(+ is_sink,+ pos2 <= q_abs[:, None],+ (pos2 >= sinks_n) & (pos2 <= q_abs[:, None]) & (pos2 > q_abs[:, None] - win),+ )+ valid = valid_row[:, None] & in_ring[None, :] & ok+ scores = tl.where(valid, scores, -float("inf"))+ m_new = tl.maximum(m, tl.max(scores, axis = 1))+ m_exp = tl.where(m_new == -float("inf"), 0.0, m_new)+ p = tl.exp(scores - m_exp[:, None])+ p = tl.where(valid, p, 0.0)+ alpha = tl.where(m == -float("inf"), 0.0, tl.exp(m - m_exp))+ l = l * alpha + tl.sum(p, axis = 1)+ v_tile = tl.load(ov_v + base[:, None] + offs_d[None, :], mask = in_ring[:, None] & d_mask[None, :], other = 0.0)+ acc = acc * alpha[:, None] + tl.dot(p.to(v_tile.dtype), v_tile)+ m = m_new++ if ROT_V:+ hm = tl.load(h32 + tl.arange(0, 32)[:, None] * 32 + tl.arange(0, 32)[None, :]).to(tl.float32)+ acc = tl.reshape(tl.dot(tl.reshape(acc, (BLOCK_ROWS * HD_PAD // 32, 32)), hm, input_precision = "ieee"),+ (BLOCK_ROWS, HD_PAD))+ s_idx = ns_total - 1+ po_base = (pid * ns_total + s_idx) * BLOCK_ROWS * HD_PAD+ tl.store(partial_o + po_base + rows[:, None] * HD_PAD + offs_d[None, :], acc)+ ml_base = (pid * ns_total + s_idx) * BLOCK_ROWS * 2+ tl.store(partial_ml + ml_base + rows * 2, m)+ tl.store(partial_ml + ml_base + rows * 2 + 1, l)+++def ring_split(ctx: KVWinCtx, q, cache_seqlens, h32, partial_o, partial_ml, ns_total, programs,+ q_len, n_q_heads, n_kv_heads, head_dim, hd_pad, scale, rot_v, dense, block_m, block_h, block_rows):+ cfg = ctx.cfg+ st = ctx.state+ with torch.cuda.device(q.device):+ _ring_split_kernel[(programs,)](+ q, st.ov_k, st.ov_v, ctx.slots, cache_seqlens, h32,+ partial_o, partial_ml,+ ns_total, cfg.S, cfg.W, cfg.Rc, cfg.R,+ q_len, n_q_heads, n_kv_heads, head_dim, hd_pad, float(scale), bool(rot_v), bool(dense),+ block_m, block_h, block_rows, 64,+ num_warps = 4, num_stages = 1,+ )+++def _stage_patch_kernel(+ k_new, v_new, kd, vd, ov_k, ov_v, slots, seqlens,+ stride, q_len, S, W, Rc, R,+ n_kv_heads: tl.constexpr,+ head_dim: tl.constexpr,+ HD_PAD: tl.constexpr,+ HAS_CHUNK: tl.constexpr,+):+ """Overwrite rows of the dequantized prefill scratch (kd / vd, batch b's tokens at b * stride + position) with exact+ values: the sinks and the last W positions of the past from the ring (as it was before this chunk) and, with+ HAS_CHUNK, every row of the chunk from the fp16 K/V that was just quantized."""+ b = tl.program_id(0)+ j = tl.program_id(1)+ h = tl.program_id(2)+ L = tl.load(seqlens + b)+ slot = tl.load(slots + b).to(tl.int64)+ offs = tl.arange(0, HD_PAD)+ dmask = offs < head_dim+ is_sink = j < S+ is_win = (j >= S) & (j < S + W)+ t = j - S - W+ pos = tl.where(is_sink, j, tl.where(is_win, L - W + (j - S), L + t))+ from_ring = is_sink | is_win+ ok_ring = from_ring & (pos >= 0) & (pos < L) & (is_sink | (pos >= S)) & (slot >= 0)+ dst = ((b * stride + pos).to(tl.int64) * n_kv_heads + h) * head_dim+ row = tl.where(pos < S, pos, S + (pos - S) % Rc)+ rsrc = ((slot * R + row) * n_kv_heads + h) * head_dim+ m_ring = dmask & ok_ring+ tl.store(kd + dst + offs, tl.load(ov_k + rsrc + offs, mask = m_ring, other = 0.0), mask = m_ring)+ tl.store(vd + dst + offs, tl.load(ov_v + rsrc + offs, mask = m_ring, other = 0.0), mask = m_ring)+ if HAS_CHUNK:+ ok_new = (j >= S + W) & (t < q_len)+ csrc = ((b * q_len + t).to(tl.int64) * n_kv_heads + h) * head_dim+ m_new = dmask & ok_new+ tl.store(kd + dst + offs, tl.load(k_new + csrc + offs, mask = m_new, other = 0.0), mask = m_new)+ tl.store(vd + dst + offs, tl.load(v_new + csrc + offs, mask = m_new, other = 0.0), mask = m_new)+++def stage_patch(ctx: KVWinCtx, kd, vd, cache_seqlens, stride: int, q_len: int):+ """kd / vd: [pages, page_size, kvh, hd] dequantized scratch in block-table order, stride = tokens per batch row."""+ cfg, st = ctx.cfg, ctx.state+ bsz = ctx.slots.shape[0]+ n_kv_heads, head_dim = kd.shape[2], kd.shape[3]+ has_chunk = ctx.chunk_k is not None+ ck = ctx.chunk_k.contiguous() if has_chunk else kd+ cv = ctx.chunk_v.contiguous() if has_chunk else vd+ n_rows = cfg.S + cfg.W + (q_len if has_chunk else 0)+ with torch.cuda.device(kd.device):+ _stage_patch_kernel[(bsz, n_rows, n_kv_heads)](+ ck, cv, kd, vd, st.ov_k, st.ov_v, ctx.slots, cache_seqlens,+ stride, q_len, cfg.S, cfg.W, cfg.Rc, cfg.R,+ n_kv_heads, head_dim, triton.next_power_of_2(head_dim), has_chunk,+ num_warps = 1,+ )diff --git a/exllamav3/modules/attention_fn/triton_paged.py b/exllamav3/modules/attention_fn/triton_paged.pyindex bd6aacc..5205193 100644--- a/exllamav3/modules/attention_fn/triton_paged.py+++ b/exllamav3/modules/attention_fn/triton_paged.py@@ -906,6 +906,7 @@ def _paged_attn_decode_split_kernel(BLOCK_H: tl.constexpr,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)):"""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."""@@ -973,6 +974,8 @@ def _paged_attn_decode_split_kernel(valid = valid & (offs_n[None, :] >= q_abs[:, None] - WINDOW_LEFT)if WINDOW_RIGHT >= 0:valid = valid & (offs_n[None, :] <= q_abs[:, None] + WINDOW_RIGHT)+ if KEY_LO > 0:+ valid = valid & (offs_n[None, :] >= KEY_LO)scores = tl.where(valid, scores, -float("inf"))m_new = tl.maximum(m, tl.max(scores, axis=1))@@ -1176,10 +1179,14 @@ def paged_attn_triton_decode(num_warps: int = 4,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) -> 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 asecond pass. GQA sibling q heads share K/V tiles within a program."""+ if ring is not None and (qc is None or not causal or softcap or _normalize_window(window_size)[0] >= 0+ or _normalize_window(window_size)[1] >= 0 or k is not None):+ raise ValueError("KVWIN ring: quantized, causal, pre-appended, unwindowed decode only")if qc is not None and not os.environ.get("FLINT_ATTN_KEEP"):# quantized cache decode (3090, head_dim 128, k/v 4-8 bit): 64-key tiles, single stage = -15..-25 % kernel time# vs the 16-bit-sized default (profile at 60K ctx: kv8 2.47 -> 1.90 ms, kv4 2.22 -> 1.69 ms, 49 layers)@@ -1194,7 +1201,7 @@ 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 ring 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)if out_hip is not None:@@ -1205,7 +1212,7 @@ def paged_attn_triton_decode(return paged_attn_triton_decode_cu(q, k, v, k_cache, v_cache, block_table, cache_seqlens, causal, softmax_scale, window_size,softcap, sinks, out, block_n, num_splits, max_kv_len, qc, pre_appended_len,- n_kv_heads_override, num_warps, num_stages, split_batch)+ n_kv_heads_override, num_warps, num_stages, split_batch, ring)except NoFittingConfig:if _ATTN16_DEBUG: print(" -- attn16 NoFittingConfig -> pre-1.6 kernels", flush = True)pass # nothing fits this device's shared memory: the pre-1.6 kernels below@@ -1293,9 +1300,14 @@ def paged_attn_triton_decode(num_splits = max(1, min(target // programs_split, triton.cdiv(max_k_len, (4 if torch.version.hip else 1) * block_n), 128))split_len = triton.cdiv(triton.cdiv(max_k_len, num_splits), block_n) * block_n- if num_splits > 1:- partial_o = torch.empty(programs * num_splits * block_rows * hd_pad, dtype = torch.float32, device = q.device)- partial_ml = torch.empty(programs * num_splits * block_rows * 2, dtype = torch.float32, device = q.device)+ # KVWIN: the pool pass attends [S, q-W] (its causal bound shifted by W, sinks cut by KEY_LO) and the fp16 ring pass is+ # one more partial in the slot after the pool splits, so the combine below needs no change but its split count+ pool_seqlens, key_lo, ns_total = cache_seqlens, 0, num_splits+ if ring is not None:+ pool_seqlens, key_lo, ns_total = cache_seqlens - ring.cfg.W, ring.cfg.S, num_splits + 1+ if ns_total > 1:+ partial_o = torch.empty(programs * ns_total * block_rows * hd_pad, dtype = torch.float32, device = q.device)+ partial_ml = torch.empty(programs * ns_total * block_rows * 2, dtype = torch.float32, device = q.device)else:partial_o = q # unusedpartial_ml = q # unused@@ -1310,20 +1322,26 @@ def paged_attn_triton_decode()_paged_attn_decode_split_kernel[(programs, num_splits)](- q, k_cache, v_cache, block_table, cache_seqlens, out, partial_o, partial_ml,+ q, k_cache, v_cache, block_table, pool_seqlens, out, partial_o, partial_ml,k_scales, v_scales, h32,- split_len, num_pages_per_seq, num_splits, sinks,+ split_len, num_pages_per_seq, ns_total, sinks,qck, qcv, q_len, kv_append_len, n_q_heads, n_kv_heads,page_size, head_dim, hd_pad, float(softmax_scale),bool(causal), int(window_left), int(window_right), float(softcap or 0.0),- num_splits == 1, has_sinks, block_m, block_h, block_rows, block_n,+ ns_total == 1, has_sinks, block_m, block_h, block_rows, block_n, key_lo,num_warps=num_warps, num_stages=num_stages,)- if num_splits > 1:+ if ring is not None:+ from .kvwin_triton import ring_split+ ring_split(ring, q, cache_seqlens, h32, partial_o, partial_ml, ns_total, programs,+ q_len, n_q_heads, n_kv_heads, head_dim, hd_pad, softmax_scale, qcv > 0, False,+ block_m, block_h, block_rows)++ if ns_total > 1:_paged_attn_decode_combine_kernel[(programs,)](partial_o, partial_ml, out, h32,- num_splits, sinks, qcv, has_sinks, q_len, n_q_heads, n_kv_heads, head_dim, hd_pad,+ ns_total, sinks, 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,)@@ -1871,6 +1889,7 @@ def paged_attn_triton_prefill(k_new: torch.Tensor | None = None,v_new: torch.Tensor | None = None,v_dim: int | None = None,+ ring = None, # KVWIN: KVWinCtx; the staged scratch gets exact sinks / window / chunk rows) -> torch.Tensor:"""Prefill (large q_len) attention over the paged cache.@@ -1972,7 +1991,7 @@ 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 (_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]@@ -1987,6 +2006,9 @@ def paged_attn_triton_prefill(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_patch+ stage_patch(ring, kd, vd, cache_seqlens, npps_w * page_size, q_len)k_cache, v_cache = kd, vdblock_table = torch.arange(bsz * npps_w, dtype = torch.int32, device = q.device).view(bsz, npps_w)qc = None@@ -2433,6 +2455,7 @@ def fn_triton_paged_attn_decode_qc(args: AttnArgs) -> torch.Tensor | None:pre_appended_len=args.q_len,n_kv_heads_override=args.num_kv_heads,max_kv_len=args.max_kv_len,+ ring=args.ov,)@@ -2467,4 +2490,5 @@ def fn_triton_paged_attn_prefill_qc(args: AttnArgs) -> torch.Tensor | None:pre_appended_len=args.q_len,n_kv_heads_override=args.num_kv_heads,max_kv_len=args.max_kv_len,+ ring=args.ov,)diff --git a/exllamav3/modules/attention_fn/triton_paged_cu.py b/exllamav3/modules/attention_fn/triton_paged_cu.pyindex 755bca7..87c1681 100644--- a/exllamav3/modules/attention_fn/triton_paged_cu.py+++ b/exllamav3/modules/attention_fn/triton_paged_cu.py@@ -375,6 +375,7 @@ def _paged_attn_decode_split_kernel(HAS_SINKS: tl.constexpr,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)):"""Flash-decoding phase 1: one program per (batch, kv_head, row block, kv split). The rows of akv head are its (query position, sibling q head) pairs packed densely (decode_row_layout), so a@@ -486,6 +487,8 @@ def _paged_attn_decode_split_kernel(valid = valid & (offs_n[None, :] >= q_abs[:, None] - WINDOW_LEFT)if WINDOW_RIGHT >= 0:valid = valid & (offs_n[None, :] <= q_abs[:, None] + WINDOW_RIGHT)+ if KEY_LO > 0:+ valid = valid & (offs_n[None, :] >= KEY_LO)scores = tl.where(valid, scores, -float("inf"))m_new = tl.maximum(m, tl.max(scores, axis=1))@@ -696,6 +699,7 @@ def paged_attn_triton_decode_cu(num_warps: int | None = None,num_stages: int | None = None,split_batch: int | None = None, # batch size the split count is derived from (default: bsz)+ ring = None, # KVWIN: KVWinCtx; pool pass over [S, q-W], fp16 ring partial for the sinks + window) -> 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@@ -783,7 +787,7 @@ def paged_attn_triton_decode_cu(programs_split = programs if split_batch is None else programs // bsz * split_batchreq_splits = num_splits- if qc is not None and qck > 0 and qcv > 0:+ if qc is not None and qck > 0 and qcv > 0 and ring is None:from . import qdec_cudaqcfg = 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)@@ -821,26 +825,34 @@ def paged_attn_triton_decode_cu(_QDEC_STATS.append((d, mx, d / max(mx, 1e-9), q_len, head_dim, qck, qcv))return out+ pool_seqlens, key_lo = cache_seqlens, 0+ if ring is not None:+ if qc is None or not causal or softcap or window_left >= 0 or window_right >= 0 or k is not None:+ raise ValueError("KVWIN ring: quantized, causal, pre-appended, unwindowed decode only")+ pool_seqlens, key_lo = cache_seqlens - ring.cfg.W, ring.cfg.S+def prepare(block_n):"""Split count, partial buffers and the split kernel's argument list for one kv tile."""splits = req_splitsif splits is None:splits = max(1, min(target // programs_split, triton.cdiv(max_k_len, 1 * block_n), 128))split_len = triton.cdiv(triton.cdiv(max_k_len, splits), block_n) * block_n- if splits > 1:- partial_o = torch.empty(programs * splits * block_rows * hd_pad, dtype = torch.float32, device = q.device)- partial_ml = torch.empty(programs * splits * block_rows * 2, dtype = torch.float32, device = q.device)+ # KVWIN: one more partial after the pool splits holds the ring pass (see paged_attn_triton_decode)+ ns_total = splits + (1 if ring is not None else 0)+ if ns_total > 1:+ partial_o = torch.empty(programs * ns_total * block_rows * hd_pad, dtype = torch.float32, device = q.device)+ partial_ml = torch.empty(programs * ns_total * block_rows * 2, dtype = torch.float32, device = q.device)else:partial_o = q # unusedpartial_ml = q # unusedargs = (- q, k_cache, v_cache, block_table, cache_seqlens, out, partial_o, partial_ml,+ q, k_cache, v_cache, block_table, pool_seqlens, out, partial_o, partial_ml,k_scales, v_scales, h32,- split_len, num_pages_per_seq, splits, sinks,+ split_len, num_pages_per_seq, ns_total, sinks,qck, qcv, q_len, kv_append_len, n_q_heads, n_kv_heads,page_size, head_dim, hd_pad, float(softmax_scale),bool(causal), int(window_left), int(window_right), float(softcap or 0.0),- splits == 1, has_sinks, block_rows, block_n,+ ns_total == 1, has_sinks, block_rows, block_n, key_lo,)return args, splits, partial_o, partial_ml@@ -870,11 +882,19 @@ def paged_attn_triton_decode_cu(*args, num_warps = num_warps, num_stages = num_stages,)- if num_splits > 1:+ ns_total = num_splits+ if ring is not None:+ from .kvwin_triton import ring_split+ ns_total = num_splits + 1+ ring_split(ring, q, cache_seqlens, h32, partial_o, partial_ml, ns_total, programs,+ q_len, n_q_heads, n_kv_heads, head_dim, hd_pad, softmax_scale, qcv > 0, True,+ 1, 1, block_rows)++ if ns_total > 1:rows_sub, d_sub = combine_subtiles(block_rows, hd_pad)_paged_attn_decode_combine_kernel[(programs, (block_rows // rows_sub) * (hd_pad // d_sub))](partial_o, partial_ml, out, h32,- num_splits, sinks, qcv, has_sinks, q_len, n_q_heads, n_kv_heads, head_dim, hd_pad, head_dim,+ ns_total, sinks, qcv, has_sinks, q_len, n_q_heads, n_kv_heads, head_dim, hd_pad, head_dim,block_rows, rows_sub, d_sub,num_warps=4, num_stages=1,)diff --git a/exllamav3/modules/attn.py b/exllamav3/modules/attn.pyindex 918fd0d..73f54c6 100644--- a/exllamav3/modules/attn.py+++ b/exllamav3/modules/attn.py@@ -43,6 +43,7 @@ def _sim_kvq_inplace(t: torch.Tensor, bits: int | None, compand_a: float):from ..util.tensor import g_tensor_cachefrom .attention_fn import attn_dispatch+from ..cache.kvwin import env_cfg as _kvwin_cfg, make_ctx as _kvwin_ctx, ensure_filled as _kvwin_fill, KVWinLayerState"""@@ -440,6 +441,12 @@ class Attention(Module):"kv_cache": True})+ # KVWIN (EXL3_KVWIN=sink:window): the fp16 sink + window ring of a quantized cache is a per-job recurrent layer state+ self.recurrent_layers = []+ if _kvwin_cfg() is not None and self.num_kv_heads > 0:+ self.caps["recurrent_cache"] = True+ self.layer_state_cls = KVWinLayerState+self.cache_layers = []self.tp_cache_lookup = {}self.multi_kv = None@@ -487,6 +494,8 @@ class Attention(Module):# Cachefor cl in self.cache_layers:cl.alloc(device)+ for rl in self.recurrent_layers:+ rl.alloc(device)if self.rope_settings:self.rope = RoPE(@@ -633,6 +642,8 @@ class Attention(Module):for cl in self.cache_layers:cl.free()+ for rl in self.recurrent_layers:+ rl.free()self.rope = Noneself.sinks = None@@ -1264,6 +1275,18 @@ class Attention(Module):self.forward(x, p2)+ def kvwin_ctx(self, cache, params: dict, bsz: int, block_table: torch.Tensor):+ """KVWIN ring context of this attention call (None when off, inert or the call has no job states)."""+ if not self.caps.get("recurrent_cache"):+ return None+ rl = getattr(cache, "recurrent_layers", None)+ if not rl:+ return None+ ctx = _kvwin_ctx(rl.get((self.layer_idx, params.get("layer_instance") or 0)), params, self.device, bsz)+ _kvwin_fill(ctx, params, block_table)+ return ctx++def decode_flash_attn(self,x: torch.Tensor,@@ -1281,6 +1304,7 @@ class Attention(Module):position = params.get("position", 0)positions = get_for_device(params, "positions", self.device, None)position_ids = get_for_device(params, "position_ids", self.device, None)+ ov = self.kvwin_ctx(cache, params, bsz, block_table)inv_freq = get_for_device(params, "inv_freq", self.device, None)causal = params.get("causal", True)non_causal_spans = params.get("non_causal_spans")@@ -1390,6 +1414,7 @@ class Attention(Module):dispatch_cache = self.dispatch_cache,max_kv_len = max_kv_len,v_dim = self.v_head_dim if self.v_head_dim != self.head_dim else None,+ ov = ov,) for i in range(seqlen)], dim = 1)else:o = attn_dispatch(@@ -1410,6 +1435,7 @@ class Attention(Module):dispatch_cache = self.dispatch_cache,max_kv_len = max_kv_len,v_dim = self.v_head_dim if self.v_head_dim != self.head_dim else None,+ ov = ov,)if self.headwise_gate:@@ -1457,6 +1483,7 @@ class Attention(Module):positions = get_for_device(params, "positions", self.device, None)inv_freq = get_for_device(params, "inv_freq", self.device, None)causal = params.get("causal", True)+ ov_all = self.kvwin_ctx(cache, params, bsz, block_table)qsa_layer = qsa_cpu = Noneif self.qsa_indexer is not None:from ..cache import CacheLayer as _CL@@ -1505,6 +1532,7 @@ class Attention(Module):window_size = self.window_arg(), softcap = self.logit_softcapping, non_causal_spans = None,sinks = self.sinks, dispatch_cache = self.dispatch_cache, max_kv_len = max_kv_len,v_dim = self.v_head_dim if self.v_head_dim != self.head_dim else None,+ ov = ov_all._replace(slots = ov_all.slots[sl]) if ov_all is not None else None,)if rows is None:outs.append(call(q[sl], k[sl], v[sl], cs_b))diff --git a/exllamav3/modules/gated_delta_net.py b/exllamav3/modules/gated_delta_net.pyindex a03e5c6..a34fc82 100644--- a/exllamav3/modules/gated_delta_net.py+++ b/exllamav3/modules/gated_delta_net.py@@ -202,9 +202,11 @@ class GDNState:l._set_base(self.slot, 0)return ent[1]jobs = _collect_rewind_jobs(layers.values(), self.slot, self.last_history, num_tokens)- if all(isinstance(l, GDNLayerState) for l in layers.values()):+ # KVWIN ring states rewind as a no-op, so they do not break the pointer-only memo+ if all(isinstance(l, GDNLayerState) or getattr(l, "rewind_noop", False) for l in layers.values()):reps = {}- for l in layers.values(): reps.setdefault(l.cache_id, l)+ for l in layers.values():+ if isinstance(l, GDNLayerState): reps.setdefault(l.cache_id, l)memo[key] = (_alloc_epoch, jobs, list(reps.values()))return jobs@@ -276,7 +278,10 @@ class GDNState:assert self.position == stashed["position"]if not self.cache.model.loaded_tp:for k, l in self.cache.get_all_recurrent_layers().items():- l.unstash(self.slot, stashed[k])+ if k in stashed or not hasattr(l, "unstash_missing"):+ l.unstash(self.slot, stashed[k])+ else:+ l.unstash_missing(self.slot) # KVWIN ring absent from a checkpoint written with the switch offelse:cp_handle = stashed["tp_handle"]self.cache.model.tp_dispatch_all(mp_cache_recurrent_unstash, (id(self.cache), cp_handle, self.slot))diff --git a/tests/kvwin_off_scenario.py b/tests/kvwin_off_scenario.pynew file mode 100644index 0000000..73ae7ab--- /dev/null+++ b/tests/kvwin_off_scenario.py@@ -0,0 +1,32 @@+"""Deterministic quantized-cache attention scenario WITHOUT the KVWIN ring (prefill chunk, decode, verify block) through+attn_dispatch. Usage: python kvwin_off_scenario.py <exllamav3 tree> <out.pt>; run it on a tree before and after the KVWIN+change: the saved outputs must be bit-identical (EXL3_KVWIN unset = today)."""+import sys, types, torch+tree, out = sys.argv[1], sys.argv[2]+sys.path[:0] = sys.argv[3:] + [tree] # optional directory holding only the built exllamav3_ext (wins over a .so inside the tree)+from exllamav3.cache.quant import CacheLayer_quant+from exllamav3.modules.attention_fn.dispatch import attn_dispatch++dev = "cuda:0"+torch.manual_seed(0)+kvh, qh, hd = 2, 8, 128+res = {}+for bits in ((4, 4), (6, 6), (8, 8)):+ attn = types.SimpleNamespace(num_kv_heads = kvh, head_dim = hd)+ cl = CacheLayer_quant(None, attn, 0, 8 * 256, *bits)+ cl.alloc(torch.device(dev))+ bt = torch.tensor([[5, 2, 7, 0]], dtype = torch.int32, device = dev)+ L = 0+ outs = []+ for q_len in (300, 1, 5, 16, 1, 40, 1):+ q = torch.randn(1, q_len, qh, hd, device = dev).half()+ k = torch.randn(1, q_len, kvh, hd, device = dev).half()+ v = torch.randn(1, q_len, kvh, hd, device = dev).half()+ sl = torch.tensor([L], dtype = torch.int32, device = dev)+ o = attn_dispatch(q = q, k = k, v = v, cache = cl, cache_idx = 0, block_table = bt, cache_seqlens = sl,+ causal = True, sm_scale = hd ** -0.5, max_kv_len = L)+ outs.append(o.cpu())+ L += q_len+ res[bits] = outs+torch.save(res, out)+print("saved", out)diff --git a/tests/test_kvwin.py b/tests/test_kvwin.pynew file mode 100644index 0000000..9b86172--- /dev/null+++ b/tests/test_kvwin.py@@ -0,0 +1,418 @@+"""KVWIN (fp16 sink + recent-window ring next to a quantized KV pool): ring write / merge / rollback / restore checks.++Tiny shapes on any GPU (CUDA or ROCm); run with pytest or `python tests/test_kvwin.py`. The references are fp32 torch.+"""+import os, sys, types, math, contextlib+# KVWIN_TEST_CPU=1: run the Triton kernels in the Triton interpreter on CPU tensors (no GPU, slow); set before triton is imported+CPU = os.environ.get("KVWIN_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++pytestmark = pytest.mark.skipif(not CPU and not torch.cuda.is_available(), reason = "needs a GPU (or KVWIN_TEST_CPU=1)")++if torch.cuda.is_available():+ from exllamav3.cache.quant import CacheLayer_quant+ from exllamav3.cache import kvwin+ from exllamav3.cache.kvwin import KVWinLayerState, KVWinCtx, KVWinCfg, ring_rows, ring_positions, ov_write_ref, parse_spec+ from exllamav3.modules.attention_fn.kvwin_triton import ov_write+ from exllamav3.modules.attention_fn.triton_paged import paged_attn_triton_decode, paged_attn_triton_prefill, _get_h32++DEV = "cpu" if CPU else "cuda:0"+PAGE = 256++[email protected](autouse = True)+def cpu_env(monkeypatch):+ """CPU/interpreter mode: the launch wrappers query the CUDA device (context, SM count, shared memory); stub those."""+ 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)+ monkeypatch.setattr(triton_paged_cu, "pick_config", lambda device, name, key, candidates, probe: candidates[0])++[email protected](autouse = True, params = ["legacy", "cu"])+def impl(request, monkeypatch):+ """Both decode wrappers: the pre-1.6 kernels (ROCm default) and the 1.6 ones (CUDA default; run here on whatever GPU)."""+ from exllamav3.modules.attention_fn import triton_paged+ monkeypatch.setattr(triton_paged, "ATTN16", request.param == "cu")+ return request.param+++class Rig:+ """A quantized pool + KVWIN ring for nseq sequences (slot i of sequence i unless slots given)."""++ def __init__(self, cfg, kvh = 2, qh = 8, hd = 128, kb = 4, vb = 4, pages = 8, nslots = 4, slots = (2, 0), seed = 0):+ self.cfg, self.kvh, self.qh, self.hd, self.kb, self.vb = cfg, kvh, qh, hd, kb, vb+ 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_quant(None, attn, 0, pages * PAGE, kb, vb)+ self.cl.alloc(torch.device(DEV))+ self.st = KVWinLayerState(attn, nslots, 0, 0)+ self.st.cfg = cfg+ self.st.cache_layer = self.cl+ self.st.alloc(torch.device(DEV))+ self.nseq = len(slots)+ self.slots = torch.tensor(slots, dtype = torch.int32, device = DEV)+ # non-trivial page order: sequence b owns pages perm[b*pp : (b+1)*pp]+ pp = pages // self.nseq+ perm = torch.randperm(pages, generator = torch.Generator().manual_seed(seed + 1))+ self.bt = perm[: pp * self.nseq].view(self.nseq, pp).to(torch.int32).to(DEV)+ self.len = [0] * self.nseq+ self.K = [torch.empty(0, kvh, hd, dtype = torch.half, device = DEV) for _ in slots]+ self.V = [torch.empty(0, kvh, hd, dtype = torch.half, device = DEV) for _ in slots]++ def rnd(self, *shape):+ # K/V with per-token scale variation so quantization error is visible+ 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 ctx(self, rows = None):+ rows = list(range(self.nseq)) if rows is None else rows+ return KVWinCtx(self.st, self.slots[rows].contiguous())++ def append(self, b, n, ring = True, k = None, v = None):+ """Quantize n new rows of sequence b into the pool and (ring) into the ring, like attn_dispatch does."""+ k = self.rnd(1, n, self.kvh, self.hd) if k is None else k+ v = self.rnd(1, n, self.kvh, self.hd) if v is None else v+ sl = torch.tensor([self.len[b]], dtype = torch.int32, device = DEV)+ bt = self.bt[b:b + 1].contiguous()+ self.cl.update_kv_direct(sl, bt, k, v, n)+ if ring:+ ov_write(self.ctx([b]), k, v, sl, n)+ self.K[b] = torch.cat([self.K[b][: self.len[b]], k[0]])+ self.V[b] = torch.cat([self.V[b][: self.len[b]], v[0]])+ self.len[b] += n+ return k, v++ def dequant(self, b):+ """fp32 dequantized K/V of sequence b, positions 0..len-1."""+ sl = torch.tensor([self.len[b]], dtype = torch.int32, device = DEV)+ k, v = self.cl.get_kv(sl, self.bt[b:b + 1].contiguous())+ pos = torch.arange(self.len[b], device = DEV)+ page = self.bt[b].long()[pos // PAGE]+ return k[page, pos % PAGE].float(), v[page, pos % PAGE].float()+++def ref_attn(rig, b, q, L, mix = True):+ """q [q_len, qh, hd] at positions L..L+q_len-1 of sequence b (all of whose K/V are in the rig).+ mix: sinks + per-row window exact, the rest dequantized; else everything dequantized."""+ cfg = rig.cfg+ kd, vd = rig.dequant(b)+ ke, ve = rig.K[b].float(), rig.V[b].float()+ out = torch.empty(q.shape, dtype = torch.float32, device = DEV)+ group = rig.qh // rig.kvh+ for i in range(q.shape[0]):+ qa = L + i+ pos = torch.arange(qa + 1, device = DEV)+ exact = ((pos < cfg.S) | (pos > qa - cfg.W)) if mix else torch.zeros_like(pos, dtype = torch.bool)+ kk = torch.where(exact[:, None, None], ke[: qa + 1], kd[: qa + 1])+ vv = torch.where(exact[:, None, None], ve[: qa + 1], vd[: qa + 1])+ kk = kk.repeat_interleave(group, dim = 1) # [T, qh, hd]+ vv = vv.repeat_interleave(group, dim = 1)+ s = torch.einsum("hd,thd->ht", q[i].float(), kk) / math.sqrt(rig.hd)+ out[i] = torch.einsum("ht,thd->hd", s.softmax(-1), vv)+ return out+++def decode(rig, b, q, L, ring = True, **kw):+ q_len = q.shape[0]+ sl = torch.tensor([L], dtype = torch.int32, device = DEV)+ return paged_attn_triton_decode(+ q[None].contiguous(), None, None, rig.cl.qk, rig.cl.qv, rig.bt[b:b + 1].contiguous(), sl, causal = True,+ qc = (rig.cl.sk, rig.cl.sv, rig.kb, rig.vb), pre_appended_len = q_len, n_kv_heads_override = rig.kvh,+ ring = rig.ctx([b]) if ring else None, **kw)[0]+++def close(a, b, rel = 6e-3):+ err = (a.float() - b.float()).abs().max().item()+ mx = b.float().abs().max().item()+ return err <= rel * max(mx, 1e-3), err, mx+++CFGS = [KVWinCfg(4, 32, 32 + 16, 4 + 32 + 16), KVWinCfg(0, 64, 64 + 16, 64 + 16), KVWinCfg(4, 128, 128 + 16, 4 + 128 + 16)]+++# -- ring row mapping / reference writer -------------------------------------------------------------------------------++def test_parse():+ assert parse_spec(None) is None and parse_spec("") is None and parse_spec("0") is None+ c = parse_spec("4:128")+ assert (c.S, c.W, c.Rc, c.R) == (4, 128, 144, 148)+ with pytest.raises(ValueError):+ parse_spec("12")++[email protected]("cfg", CFGS)+def test_ring_write_matches_reference(cfg):+ """Chunks crossing a page boundary and several ring wraps, then decode and verify rows: ring == reference writer."""+ rig = Rig(cfg, pages = 8, slots = (3, 1))+ ref_k = torch.zeros(4, cfg.R, rig.kvh, rig.hd, dtype = torch.half, device = DEV)+ ref_v = torch.zeros_like(ref_k)+ for n in (200, 100, 257, 1, 1, 7, 16, 300, 1, 5): # 889 rows: page edge at 256/512/768, wraps of 48..148+ for b in (0, 1):+ L = rig.len[b]+ if L + n > 8 // 2 * PAGE:+ continue+ k, v = rig.append(b, n)+ ov_write_ref(ref_k, ref_v, int(rig.slots[b]), k[0], v[0], L, cfg)+ for b in (0, 1):+ s = int(rig.slots[b])+ assert torch.equal(rig.st.ov_k[s], ref_k[s]) and torch.equal(rig.st.ov_v[s], ref_v[s]), f"slot {s}"+ # untouched slots stay zero+ assert not rig.st.ov_k[0].any() and not rig.st.ov_k[2].any()+ # positions held by the ring after the last write+ for b in (0, 1):+ p = ring_positions(rig.len[b], cfg)+ s = int(rig.slots[b])+ for r in range(cfg.R):+ if p[r] >= 0:+ assert torch.equal(rig.st.ov_k[s, r], rig.K[b][int(p[r])]), (b, r, int(p[r]))+++# -- attention: LSE merge == attention over the dequantized + exact mix ----------------------------------------------------+[email protected]("cfg", CFGS)[email protected]("bits", [(4, 4), (6, 6), (8, 8)])[email protected]("q_len", [1, 5, 16])+def test_merge_equals_mix(cfg, bits, q_len):+ for L0 in (3, 30, 150, 600): # shorter than S+W, around the window, page crossing+ rig = Rig(cfg, hd = 128, kb = bits[0], vb = bits[1], pages = 8, slots = (2, 0), seed = L0)+ b = 0+ rig.append(b, L0)+ k, v = rig.append(b, q_len) # the verify rows+ q = rig.rnd(q_len, rig.qh, rig.hd)+ o = decode(rig, b, q, L0)+ ok, err, mx = close(o, ref_attn(rig, b, q, L0, mix = True))+ assert ok, f"{cfg} {bits} q_len {q_len} L0 {L0}: err {err:.3e} vs max {mx:.3e}"+++def test_tolerance_discriminates():+ """Negative control: the pool-only result (no ring) must NOT pass the mix check at 4 bit, or the check proves nothing."""+ cfg = CFGS[0]+ rig = Rig(cfg, kb = 4, vb = 4, seed = 21)+ rig.append(0, 300); rig.append(0, 1)+ q = rig.rnd(1, rig.qh, rig.hd)+ ok_on, e_on, mx = close(decode(rig, 0, q, 300), ref_attn(rig, 0, q, 300))+ ok_off, e_off, _ = close(decode(rig, 0, q, 300, ring = False), ref_attn(rig, 0, q, 300))+ assert ok_on and not ok_off, (e_on, e_off, mx)+++def test_ring_beats_pool_only():+ """Sanity of the premise: against the exact attention the ring result is closer than the pool-only result."""+ cfg = CFGS[0]+ rig = Rig(cfg, kb = 4, vb = 4, seed = 11)+ rig.append(0, 400)+ rig.append(0, 1)+ # a query aligned with the newest keys, so the window carries real attention mass+ q = (rig.K[0][-3:].float().mean(0).repeat_interleave(rig.qh // rig.kvh, 0) * 1.5)[None].half()+ ke, ve = rig.K[0].float().repeat_interleave(rig.qh // rig.kvh, 1), rig.V[0].float().repeat_interleave(rig.qh // rig.kvh, 1)+ s = torch.einsum("hd,thd->ht", q[0].float(), ke) / math.sqrt(rig.hd)+ exact = torch.einsum("ht,thd->hd", s.softmax(-1), ve)+ e_ring = (decode(rig, 0, q, 400)[0].float() - exact).abs().mean().item()+ e_pool = (decode(rig, 0, q, 400, ring = False)[0].float() - exact).abs().mean().item()+ assert e_ring < e_pool, (e_ring, e_pool)+++def test_batch_two_slots_and_lengths():+ """Two sequences with different lengths and permuted slots in one launch."""+ cfg = CFGS[0]+ rig = Rig(cfg, pages = 8, slots = (3, 1), seed = 5)+ rig.append(0, 500); rig.append(1, 90)+ for b in (0, 1):+ rig.append(b, 3)+ q = rig.rnd(2, 3, rig.qh, rig.hd)+ sl = torch.tensor([500, 90], dtype = torch.int32, device = DEV)+ o = paged_attn_triton_decode(+ q.contiguous(), None, None, rig.cl.qk, rig.cl.qv, rig.bt.contiguous(), sl, causal = True,+ qc = (rig.cl.sk, rig.cl.sv, rig.kb, rig.vb), pre_appended_len = 3, n_kv_heads_override = rig.kvh, ring = rig.ctx())+ for b, L in ((0, 500), (1, 90)):+ ok, err, mx = close(o[b], ref_attn(rig, b, q[b], L))+ assert ok, (b, err, mx)++[email protected]("splits", [None, 1, 3])+def test_split_counts(splits):+ cfg = CFGS[0]+ rig = Rig(cfg, seed = 7)+ rig.append(0, 700); rig.append(0, 2)+ q = rig.rnd(2, rig.qh, rig.hd)+ o = decode(rig, 0, q, 700, num_splits = splits)+ ok, err, mx = close(o, ref_attn(rig, 0, q, 700))+ assert ok, (err, mx)+++# -- speculative rollback ---------------------------------------------------------------------------------------------------++def test_rollback_of_draft_rows():+ """D draft rows are verified (written), only some accepted: the next block attends the right window."""+ cfg = CFGS[0]+ rig = Rig(cfg, seed = 3)+ rig.append(0, 300)+ L = 300+ D = 16+ rig.append(0, D) # verify block of 16 draft rows (positions 300..315)+ q = rig.rnd(D, rig.qh, rig.hd)+ ok, err, mx = close(decode(rig, 0, q, L), ref_attn(rig, 0, q, L))+ assert ok+ # reject all but 3: sequence continues at 303 with fresh rows (the stale rows 303..315 are overwritten as they land)+ rig.len[0] = L + 3+ rig.K[0] = rig.K[0][: L + 3]; rig.V[0] = rig.V[0][: L + 3]+ for step in (1, 4, 16):+ L2 = rig.len[0]+ rig.append(0, step)+ q = rig.rnd(step, rig.qh, rig.hd)+ ok, err, mx = close(decode(rig, 0, q, L2), ref_attn(rig, 0, q, L2))+ assert ok, (step, err, mx)+++def test_rollback_across_ring_wrap():+ """Verify blocks of 16 at every offset around a ring wrap; reject everything each time (len stays)."""+ cfg = CFGS[0]+ rig = Rig(cfg, seed = 4)+ rig.append(0, 100)+ for rep in range(6):+ L = rig.len[0]+ rig.append(0, 16)+ rig.len[0] = L; rig.K[0] = rig.K[0][:L]; rig.V[0] = rig.V[0][:L] # all rejected+ rig.append(0, 1 + rep) # real tokens land on the stale rows+ L2 = rig.len[0] - (1 + rep)+ q = rig.rnd(1 + rep, rig.qh, rig.hd)+ ok, err, mx = close(decode(rig, 0, q, L2), ref_attn(rig, 0, q, L2))+ assert ok, (rep, err, mx)+++# -- stash / restore ----------------------------------------------------------------------------------------------------------++def test_stash_restore_bitwise():+ cfg = CFGS[0]+ rig = Rig(cfg, slots = (1, 2), seed = 9)+ rig.append(0, 450)+ stashed = rig.st.stash(1)+ pinned = rig.st.stash(1, pinned = True)+ torch.cuda.synchronize()+ assert torch.equal(stashed[0], pinned[0]) and torch.equal(stashed[1], pinned[1])+ rig.st.clear(3)+ rig.st.unstash(3, stashed)+ assert torch.equal(rig.st.ov_k[3], rig.st.ov_k[1]) and torch.equal(rig.st.ov_v[3], rig.st.ov_v[1])+ # disk round trip (prefix_disk uses torch.save of the stash dict)+ import io+ buf = io.BytesIO(); torch.save({"x": stashed}, buf); buf.seek(0)+ back = torch.load(buf)["x"]+ rig.st.clear(0)+ rig.st.unstash(0, back)+ assert torch.equal(rig.st.ov_k[0], rig.st.ov_k[1])+ # the restored slot attends identically to the original+ rig.slots[1] = 0+ q = rig.rnd(1, rig.qh, rig.hd)+ rig.append(0, 1)+ o_new = decode(rig, 0, q, 450)+ ok, err, mx = close(o_new, ref_attn(rig, 0, q, 450))+ assert ok, (err, mx)+++def test_cold_fill_from_pool():+ """A checkpoint without ring blob: fill rebuilds sinks + window from the dequantized pool (quant-level window)."""+ cfg = CFGS[0]+ rig = Rig(cfg, slots = (1, 2), seed = 10)+ rig.append(0, 420)+ rig.st.unstash_missing(2)+ assert rig.st.cold[2] and not rig.st.cold[1]+ rig.st.fill(2, rig.bt[0], 420)+ assert not rig.st.cold[2]+ kd, vd = rig.dequant(0)+ for p in list(range(cfg.S)) + list(range(420 - cfg.W, 420)):+ r = p if p < cfg.S else cfg.S + (p - cfg.S) % cfg.Rc+ assert torch.equal(rig.st.ov_k[2, r].float(), kd[p]) and torch.equal(rig.st.ov_v[2, r].float(), vd[p]), p+ # after the fill, new rows land normally and the window slides over filled + new rows+ rig.slots[0] = 2+ rig.append(0, 1)+ q = rig.rnd(1, rig.qh, rig.hd)+ o = decode(rig, 0, q, 420)+ # reference: window rows 420-W+1..419 are dequantized (filled), row 420 and the sinks exact+ kk, vv = rig.K[0].clone(), rig.V[0].clone()+ keep = torch.zeros(421, dtype = torch.bool, device = DEV); keep[:cfg.S] = True; keep[420] = True+ kk = torch.where(keep[:, None, None], kk.float(), torch.cat([kd, kd[-1:]])); vv = torch.where(keep[:, None, None], vv.float(), torch.cat([vd, vd[-1:]]))+ g = rig.qh // rig.kvh+ s = torch.einsum("hd,thd->ht", q[0].float(), kk.repeat_interleave(g, 1)) / math.sqrt(rig.hd)+ ref = torch.einsum("ht,thd->hd", s.softmax(-1), vv.repeat_interleave(g, 1))+ ok, err, mx = close(o[0], ref)+ assert ok, (err, mx)+++# -- prefill staging patch ------------------------------------------------------------------------------------------------------+[email protected]("past,q_len", [(0, 300), (700, 300), (90, 40)])+def test_prefill_patch(past, q_len):+ cfg = CFGS[0]+ rig = Rig(cfg, hd = 128, pages = 8, slots = (2, 0), seed = 12)+ if past:+ rig.append(0, past)+ k = rig.rnd(1, q_len, rig.kvh, rig.hd); v = rig.rnd(1, q_len, rig.kvh, rig.hd)+ sl = torch.tensor([past], dtype = torch.int32, device = DEV)+ rig.cl.update_kv_direct(sl, rig.bt[0:1].contiguous(), k, v, q_len)+ ctx = rig.ctx([0])._replace(chunk_k = k, chunk_v = v)+ q = rig.rnd(q_len, rig.qh, rig.hd)+ o = paged_attn_triton_prefill(+ q[None].contiguous(), None, None, rig.cl.qk, rig.cl.qv, rig.bt[0:1].contiguous(), sl, causal = True,+ qc = (rig.cl.sk, rig.cl.sv, rig.kb, rig.vb), pre_appended_len = q_len, n_kv_heads_override = rig.kvh,+ max_kv_len = past, ring = ctx)[0]+ ov_write(rig.ctx([0]), k, v, sl, q_len)+ rig.K[0] = torch.cat([rig.K[0][:past], k[0]]); rig.V[0] = torch.cat([rig.V[0][:past], v[0]]); rig.len[0] = past + q_len+ # reference: chunk rows exact, past window / sinks exact, rest dequantized (a superset of the decode window)+ kd, vd = rig.dequant(0)+ ke, ve = rig.K[0].float(), rig.V[0].float()+ pos = torch.arange(past + q_len, device = DEV)+ exact = (pos < cfg.S) | (pos >= past - cfg.W)+ kk = torch.where(exact[:, None, None], ke, kd); vv = torch.where(exact[:, None, None], ve, vd)+ g = rig.qh // rig.kvh+ kk, vv = kk.repeat_interleave(g, 1), vv.repeat_interleave(g, 1)+ s = torch.einsum("qhd,thd->hqt", q.float(), kk) / math.sqrt(rig.hd)+ mask = pos[None, :] <= (past + torch.arange(q_len, device = DEV))[:, None]+ s = s.masked_fill(~mask[None], -float("inf"))+ ref = torch.einsum("hqt,thd->qhd", s.softmax(-1), vv)+ ok, err, mx = close(o, ref)+ assert ok, (err, mx)+ # and the ring now holds the end of the chunk+ pp = ring_positions(past + q_len, cfg)+ for r in range(cfg.R):+ if pp[r] >= 0:+ assert torch.equal(rig.st.ov_k[2, r], rig.K[0][int(pp[r])])+++def test_off_is_bitwise_today():+ """EXL3_KVWIN unset: attn_dispatch outputs (prefill / decode / verify rows, 4/6/8 bit) equal the tree before KVWIN bit for bit.+ KVWIN_BASE_TREE = checkout of the parent commit (default: the sibling worktree wt_empty27)."""+ import subprocess, tempfile+ here = os.path.dirname(os.path.abspath(__file__))+ new_tree = os.path.dirname(here)+ base = os.environ.get("KVWIN_BASE_TREE", os.path.join(new_tree, "..", "wt_empty27"))+ if not os.path.isdir(os.path.join(base, "exllamav3")):+ pytest.skip("no baseline tree (set KVWIN_BASE_TREE)")+ ext_dir = os.environ.get("KVWIN_EXT_DIR", "")+ outs = []+ with tempfile.TemporaryDirectory() as d:+ for name, tree in (("base", base), ("new", new_tree)):+ o = os.path.join(d, name + ".pt")+ env = {k: v for k, v in os.environ.items() if k != "EXL3_KVWIN"}+ subprocess.run([sys.executable, "-I", os.path.join(here, "kvwin_off_scenario.py"), tree, o] + ([ext_dir] if ext_dir else []),+ check = True, env = env, stdout = subprocess.DEVNULL)+ outs.append(torch.load(o))+ for bits in outs[0]:+ for a, b in zip(outs[0][bits], outs[1][bits]):+ assert torch.equal(a, b), bits+++if __name__ == "__main__":+ sys.exit(pytest.main([__file__, "-x", "-q"] + sys.argv[1:]))