Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

KVWIN on CUDA: qdec.cu / qdec_rows.cu take a compile-time KEY_LO so the pool pass of the ring runs on the tensor-core kernels; env var documented

YanissAmzbf299666cacf
diff --git a/doc/env_vars.md b/doc/env_vars.md
index b0f9d59..ba4820d 100644
--- a/doc/env_vars.md
+++ b/doc/env_vars.md
@@ -157,6 +157,20 @@ Pipeline stage count for the direct quantized-cache prefill kernel. Unset/`0`, t
skipping the measurement. Only relevant where the direct path still runs (`EXL3_QC_STAGING=0`,
or short chunks below the threshold above).
+### `EXL3_KVWIN` (default: unset = off)
+
+`sink:window`, e.g. `4:128`. Keeps the first `sink` positions and the last `window` positions of every job in fp16
+next to a quantized K/V cache (`--k-bits/--v-bits`): attention reads the quantized pool for everything in between
+and a small fp16 ring (`sink + window + 16` rows per layer and job) for the rest, merged exactly by the flash-decoding
+combine. Costs about 10 MiB of VRAM per job slot at `4:128` on a 16-layer, 4-kv-head, head-dim-256 model. Applies to
+quantized-cache attention layers of models with recurrent state slots (Qwen3.5/3.8 hybrids); the ring is part of the
+job's recurrent state, so prefix/tail checkpoints, the CPU stash and the prefix disk carry it and restores stay
+bit-exact (a checkpoint written without the switch rebuilds the ring from the pool, with quantized precision for the
+first `window` tokens). While it is on, the graph-captured decode attention (`EXL3_BC_ATTN`) and the whole-forward
+graph (`EXL3_CUDA_GRAPH`) decline, and tensor-parallel loading is not supported. Prefill chunks attend the exact
+sinks, the exact window before the chunk and all of the chunk's own rows (a superset of the per-row decode window).
+Unset or `0` leaves every code path bit-identical.
+
### `EXL3_MLA_PREFILL` (default: `mha`)
Prefill strategy for MLA layers: `mha` up-projects past latent tiles from the compressed cache
diff --git a/exllamav3/modules/attention_fn/cu/qdec.cu b/exllamav3/modules/attention_fn/cu/qdec.cu
index 0cc8eb6..d45f16a 100644
--- a/exllamav3/modules/attention_fn/cu/qdec.cu
+++ b/exllamav3/modules/attention_fn/cu/qdec.cu
@@ -295,7 +295,7 @@ qdec_split(
for (int e = 0; e < 4; e++) {
int tk = n0 + g + ((e >> 1) << 3);
int ri = e & 1;
- ok[e] = rvalid[j][ri] && tk < n_end && (!CAUSAL || (float)tk <= qabs[j][ri]);
+ ok[e] = rvalid[j][ri] && tk < n_end && tk >= KEY_LO && (!CAUSAL || (float)tk <= qabs[j][ri]);
s[e] = ok[e] ? S[j][e] * sl : -INFINITY;
}
float alpha[2];
diff --git a/exllamav3/modules/attention_fn/cu/qdec_common.cuh b/exllamav3/modules/attention_fn/cu/qdec_common.cuh
index 92362f6..adedd6f 100644
--- a/exllamav3/modules/attention_fn/cu/qdec_common.cuh
+++ b/exllamav3/modules/attention_fn/cu/qdec_common.cuh
@@ -68,6 +68,9 @@ __device__ __forceinline__ void cp4(void* dst, const void* src, bool pred)
// L2 cache hints: the K/V stream is read once per decode step (evict_first) while the per-token scale sectors are shared
// by the kv-head CTAs of a split, which run unsynchronized (evict_last keeps them resident for the siblings). Without
// the hints the 8-byte scale pieces were refetched from HBM by every head: 794 -> 860 GB/s on a load-only kernel.
+#ifndef KEY_LO
+#define KEY_LO 0 // KVWIN: tokens below KEY_LO are not attended (the fp16 ring serves the sinks)
+#endif
#ifndef L2HINT
#define L2HINT 1
#endif
diff --git a/exllamav3/modules/attention_fn/cu/qdec_rows.cu b/exllamav3/modules/attention_fn/cu/qdec_rows.cu
index 0752e20..f1d3eb1 100644
--- a/exllamav3/modules/attention_fn/cu/qdec_rows.cu
+++ b/exllamav3/modules/attention_fn/cu/qdec_rows.cu
@@ -229,7 +229,7 @@ qdec_split_rows(
for (int e = 0; e < 4; e++) {
int tk = n0 + g + ((e >> 1) << 3);
int ri = e & 1;
- ok[e] = rvalid[o][ri] && tk < n_end && (!CAUSAL || (float)tk <= qabs[o][ri]);
+ ok[e] = rvalid[o][ri] && tk < n_end && tk >= KEY_LO && (!CAUSAL || (float)tk <= qabs[o][ri]);
s[e] = ok[e] ? sv[e] * sl : -INFINITY;
}
float alpha[2];
diff --git a/exllamav3/modules/attention_fn/qdec_cuda.py b/exllamav3/modules/attention_fn/qdec_cuda.py
index f0e0599..81f5734 100644
--- a/exllamav3/modules/attention_fn/qdec_cuda.py
+++ b/exllamav3/modules/attention_fn/qdec_cuda.py
@@ -74,7 +74,7 @@ def _compile(cfg):
from cuda.bindings import nvrtc
defs = dict(HD=cfg["hd"], KB=cfg["kb"], VB=cfg["vb"], NKV=cfg["nkv"], NQH=cfg["nqh"], QLEN=cfg["qlen"],
PAGE=cfg["page"], NW=cfg["nw"], ST=cfg["st"], CAUSAL=int(cfg["causal"]), BLOCK_ROWS=cfg["block_rows"],
- HD_PAD=triton.next_power_of_2(cfg["hd"]), SCALE=repr(float(cfg["scale"])) + "f")
+ HD_PAD=triton.next_power_of_2(cfg["hd"]), SCALE=repr(float(cfg["scale"])) + "f", KEY_LO=cfg.get("key_lo", 0))
defs["L2HINT"] = int(os.environ.get("EXL3_QDEC_L2HINT", "1")) # L2 evict_first on K/V, evict_last on the scales
defs["FASTDQ"] = int(os.environ.get("EXL3_QDEC_FASTDQ", "1")) # permuted-order PRMT/LOP3 bit-plane unpack (qdec.cu)
if os.environ.get("EXL3_QDEC_ABL"):
@@ -184,13 +184,15 @@ _sm = {}
def make_cfg(q_len, n_q_heads, n_kv_heads, head_dim, k_bits, v_bits, page_size, causal, sm_scale, block_rows,
- window_left, window_right, softcap, kv_append_len):
- """Kernel config for a call, or None when the Triton kernels must run it"""
+ window_left, window_right, softcap, kv_append_len, key_lo = 0):
+ """Kernel config for a call, or None when the Triton kernels must run it. key_lo: KVWIN, positions below it are not attended"""
if (not ENABLED or window_left >= 0 or window_right >= 0 or softcap or kv_append_len != q_len
or k_bits == 0 or v_bits == 0):
return None
cfg = dict(hd=head_dim, kb=k_bits, vb=v_bits, nkv=n_kv_heads, nqh=n_q_heads, qlen=q_len, page=page_size,
nw=4, st=2, causal=bool(causal), scale=float(sm_scale), block_rows=block_rows)
+ if key_lo:
+ cfg["key_lo"] = int(key_lo)
old_ok = supported(cfg) and geometry(cfg)["nt"] * 8 <= block_rows
# the many-row kernel also serves 2-row hd256 steps (qdec.cu needs 74 KB there: one CTA per SM)
if ROWS_MODE == "2" or (ROWS_MODE == "1" and (not old_ok or (cfg["hd"] >= 256 and cfg["qlen"] == 2))):
diff --git a/exllamav3/modules/attention_fn/triton_paged_cu.py b/exllamav3/modules/attention_fn/triton_paged_cu.py
index 20b7f62..eeb9e1a 100644
--- a/exllamav3/modules/attention_fn/triton_paged_cu.py
+++ b/exllamav3/modules/attention_fn/triton_paged_cu.py
@@ -787,10 +787,18 @@ def paged_attn_triton_decode_cu(
programs_split = programs if split_batch is None else programs // bsz * split_batch
req_splits = num_splits
- if qc is not None and qck > 0 and qcv > 0 and ring is None:
+ # KVWIN: the pool pass attends [S, q-W] (causal bound shifted by W, KEY_LO cuts the sinks) and the fp16 ring pass is one
+ # more partial after the pool splits, so the combine needs no change but its split count
+ 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
+
+ if qc is not None and qck > 0 and qcv > 0:
from . import qdec_cuda
qcfg = qdec_cuda.make_cfg(q_len, n_q_heads, n_kv_heads, head_dim, qck, qcv, page_size, causal, softmax_scale,
- block_rows, window_left, window_right, softcap, kv_append_len)
+ block_rows, window_left, window_right, softcap, kv_append_len, key_lo)
if qcfg is not None and (h_blocks == 1 or qcfg.get("rows_kernel")):
if qcfg.get("rows_kernel"):
# many-row kernel (cu/qdec_rows.cu): all of a kv head's (query, head) rows in one program
@@ -801,19 +809,24 @@ def paged_attn_triton_decode_cu(
qsplits = req_splits if req_splits is not None else \
max(1, min(qdec_cuda.split_cap(qcfg, q.device, programs_split), triton.cdiv(max_k_len, 16), 128))
qsplit_len = triton.cdiv(triton.cdiv(max_k_len, qsplits), 16) * 16
- partial_o = torch.empty(programs * qsplits * block_rows * hd_pad, dtype = torch.float32, device = q.device)
- partial_ml = torch.empty(programs * qsplits * block_rows * 2, dtype = torch.float32, device = q.device)
+ ns_total = qsplits + (1 if ring is not None else 0)
+ 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)
with torch.cuda.device(q.device):
qdec_cuda.get_kernel(qcfg).launch(
(programs, qsplits),
- [q.data_ptr(), k_cache.data_ptr(), v_cache.data_ptr(), block_table.data_ptr(), cache_seqlens.data_ptr(),
+ [q.data_ptr(), k_cache.data_ptr(), v_cache.data_ptr(), block_table.data_ptr(), pool_seqlens.data_ptr(),
out.data_ptr(), partial_o.data_ptr(), partial_ml.data_ptr(), k_scales.data_ptr(), v_scales.data_ptr(),
h32.data_ptr()],
- [qsplit_len, num_pages_per_seq, qsplits])
+ [qsplit_len, num_pages_per_seq, ns_total])
+ if ring is not None:
+ from .kvwin_triton import ring_split
+ ring_split(ring, q, cache_seqlens, h32, partial_o, partial_ml, ns_total, programs,
+ q_len, n_q_heads, n_kv_heads, head_dim, hd_pad, softmax_scale, True, 0, 1, 1, block_rows)
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,
- qsplits, 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,
)
@@ -825,12 +838,6 @@ 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_splits
diff --git a/tests/test_kvwin.py b/tests/test_kvwin.py
index e650da6..eb2cf43 100644
--- a/tests/test_kvwin.py
+++ b/tests/test_kvwin.py
@@ -14,12 +14,11 @@ 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
+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