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 ROCm: qdec_hip serves the pool pass (KEY_LO compile-time bound, shifted seqlens) and the ring partial is merged by qdec_combine; tests cover the hip, legacy and 1.6 decode wrappers at hd 128/256

YanissAmz5a51780e65d0
diff --git a/exllamav3/modules/attention_fn/kvwin_triton.py b/exllamav3/modules/attention_fn/kvwin_triton.py
index 6f1aecf..5404500 100644
--- a/exllamav3/modules/attention_fn/kvwin_triton.py
+++ b/exllamav3/modules/attention_fn/kvwin_triton.py
@@ -65,18 +65,25 @@ def _ring_split_kernel(
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)
+ LAYOUT: tl.constexpr, # partial layout of the pool kernel: 0 = dense (query, head) rows (1.6 Triton), 1 = padded rows
+ # (legacy Triton), 2 = qdec_hip (rows q-major, log2-domain max, unpadded columns)
BLOCK_M: tl.constexpr,
BLOCK_H: tl.constexpr,
BLOCK_ROWS: tl.constexpr,
BLOCK_N: tl.constexpr,
+ RPP: tl.constexpr = 0, # LAYOUT 2: rows per program in the partial buffers (RP of qdec_hip)
):
"""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:
+ if LAYOUT == 2:
+ bh = pid
+ row_q = rows // group_size
+ row_h_local = rows % group_size
+ valid_row = rows < q_len * group_size
+ elif LAYOUT == 0:
h_blocks = tl.cdiv(q_len * group_size, BLOCK_ROWS)
h_block = pid % h_blocks
bh = pid // h_blocks
@@ -142,15 +149,23 @@ def _ring_split_kernel(
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)
+ if LAYOUT == 2:
+ # qdec_hip partials: RPP rows of head_dim columns, running max in the log2 domain (the sum l is domain-free)
+ pb = (pid * ns_total + s_idx) * RPP
+ st_rows = rows < RPP
+ tl.store(partial_o + (pb + rows[:, None]) * head_dim + offs_d[None, :], acc, mask = st_rows[:, None] & d_mask[None, :])
+ tl.store(partial_ml + (pb + rows) * 2, m * 1.4426950408889634, mask = st_rows)
+ tl.store(partial_ml + (pb + rows) * 2 + 1, l, mask = st_rows)
+ else:
+ 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):
+ q_len, n_q_heads, n_kv_heads, head_dim, hd_pad, scale, rot_v, layout, block_m, block_h, block_rows, rpp = 0):
cfg = ctx.cfg
st = ctx.state
with torch.cuda.device(q.device):
@@ -158,8 +173,8 @@ def ring_split(ctx: KVWinCtx, q, cache_seqlens, h32, partial_o, partial_ml, ns_t
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,
+ q_len, n_q_heads, n_kv_heads, head_dim, hd_pad, float(scale), bool(rot_v), int(layout),
+ block_m, block_h, block_rows, 64, int(rpp),
num_warps = 4, num_stages = 1,
)
diff --git a/exllamav3/modules/attention_fn/qdec.hip b/exllamav3/modules/attention_fn/qdec.hip
index 47e14c1..bdd4753 100644
--- a/exllamav3/modules/attention_fn/qdec.hip
+++ b/exllamav3/modules/attention_fn/qdec.hip
@@ -49,6 +49,9 @@ typedef u32 v8u __attribute__((ext_vector_type(8)));
#ifndef HAS_SINKS
#define HAS_SINKS 0
#endif
+#ifndef KEY_LO
+#define KEY_LO 0 // KVWIN: tokens below KEY_LO are not attended (the fp16 ring serves the sinks)
+#endif
__device__ __forceinline__ u32 hsub2(u32 a, u32 b) { return __builtin_bit_cast(u32, __builtin_bit_cast(v2h, a) - __builtin_bit_cast(v2h, b)); }
__device__ __forceinline__ u32 hmul2(u32 a, u32 b) { return __builtin_bit_cast(u32, __builtin_bit_cast(v2h, a) * __builtin_bit_cast(v2h, b)); }
@@ -284,7 +287,7 @@ qdec_split(
if (!active) continue;
// ---- online softmax (log2 domain); lane owns q row n of every tile and tokens 2r + half, r = 0..7
- const bool full = (n0 + 15 < n_end) && (!CAUSAL || (float)(n0 + 15) <= qmin);
+ const bool full = (n0 + 15 < n_end) && (n0 >= KEY_LO) && (!CAUSAL || (float)(n0 + 15) <= qmin);
u32 pa[NT][8];
#pragma unroll
for (int j = 0; j < NT; j++) {
@@ -296,7 +299,7 @@ qdec_split(
#pragma unroll
for (int r = 0; r < 8; r++) {
int tk = n0 + 2 * r + half;
- bool ok = rvalid[j] && tk < n_end && (!CAUSAL || (float) tk <= qabs[j]);
+ bool ok = rvalid[j] && tk < n_end && tk >= KEY_LO && (!CAUSAL || (float) tk <= qabs[j]);
if (!ok) s[r] = NEG_INF;
}
}
diff --git a/exllamav3/modules/attention_fn/qdec_hip.py b/exllamav3/modules/attention_fn/qdec_hip.py
index c5f3d1c..53d1c46 100644
--- a/exllamav3/modules/attention_fn/qdec_hip.py
+++ b/exllamav3/modules/attention_fn/qdec_hip.py
@@ -56,8 +56,8 @@ def geometry(hd, nqh, nkv, qlen, nw, dw):
def make_cfg(q_len, n_q_heads, n_kv_heads, head_dim, k_bits, v_bits, page_size, causal, sm_scale,
- window_left, window_right, softcap, kv_append_len, has_sinks):
- """Kernel config for a call, or None when the Triton kernels must run it"""
+ window_left, window_right, softcap, kv_append_len, has_sinks, 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 not (2 <= k_bits <= 8) or not (2 <= v_bits <= 8)):
return None
@@ -72,13 +72,13 @@ def make_cfg(q_len, n_q_heads, n_kv_heads, head_dim, k_bits, v_bits, page_size,
if shared > 64 * 1024:
return None
return dict(hd=head_dim, kb=k_bits, vb=v_bits, nkv=n_kv_heads, nqh=n_q_heads, qlen=q_len, page=page_size, nw=nw, dw=dw,
- causal=bool(causal), scale=float(sm_scale), sinks=bool(has_sinks))
+ causal=bool(causal), scale=float(sm_scale), sinks=bool(has_sinks), key_lo=int(key_lo))
def _compile(cfg, arch):
from exllamav3.util import hip_compiler
defs = dict(HD=cfg["hd"], KB=cfg["kb"], VB=cfg["vb"], NKV=cfg["nkv"], NQH=cfg["nqh"], QLEN=cfg["qlen"], PAGE=cfg["page"],
- NW=cfg["nw"], DW=cfg["dw"], CAUSAL=int(cfg["causal"]), HAS_SINKS=int(cfg["sinks"]), SCALE=repr(float(cfg["scale"])) + "f")
+ NW=cfg["nw"], DW=cfg["dw"], CAUSAL=int(cfg["causal"]), HAS_SINKS=int(cfg["sinks"]), KEY_LO=cfg["key_lo"], SCALE=repr(float(cfg["scale"])) + "f")
extra = [f"-D{k}={v}" for k, v in defs.items()] + os.environ.get("EXL3_QDEC_HIP_FLAGS", "").split()
flags = ["--genco", f"--offload-arch={arch}", "-O3", "-ffp-contract=off", "--no-gpu-bundle-output"] + extra
gcc = os.environ.get("EXL3_GCC_INSTALL_DIR", "/usr/lib/gcc/x86_64-linux-gnu/13")
@@ -152,22 +152,31 @@ def num_splits(cfg, device, programs, max_k_len):
return max(1, min(-(-waves // (programs * cfg["nw"])), -(-max_k_len // 16 // cfg["nw"]), 128))
-def decode(cfg, q, k_cache, v_cache, block_table, cache_seqlens, k_scales, v_scales, h32, sinks, out, max_k_len):
- """q [bsz, q_len, n_q_heads, hd] fp16 -> out (same shape, fp16); caches are the packed int32 words"""
+def decode(cfg, q, k_cache, v_cache, block_table, cache_seqlens, k_scales, v_scales, h32, sinks, out, max_k_len, ring = None):
+ """q [bsz, q_len, n_q_heads, hd] fp16 -> out (same shape, fp16); caches are the packed int32 words.
+ ring (KVWIN, cfg built with key_lo = S): the split kernel attends [S, q - W] (cache_seqlens shifted by W) and one more
+ partial, written by the fp16 ring kernel after the last split, carries the sinks and the window."""
bsz = q.shape[0]
kern = get_kernel(cfg, q.device)
programs = bsz * cfg["nkv"]
splits = num_splits(cfg, q.device, programs, max_k_len)
split_len = -(-(-(-max_k_len // splits)) // 16) * 16
rows = cfg["qlen"] * (cfg["nqh"] // cfg["nkv"])
- po = _buf(q.device, "po", programs * splits * kern.rp * cfg["hd"])
- pml = _buf(q.device, "pml", programs * splits * kern.rp * 2)
+ ns_total = splits + (1 if ring is not None else 0)
+ po = _buf(q.device, "po", programs * ns_total * kern.rp * cfg["hd"])
+ pml = _buf(q.device, "pml", programs * ns_total * kern.rp * 2)
+ pool_seqlens = cache_seqlens if ring is None else cache_seqlens - ring.cfg.W
P, I = ctypes.c_void_p, ctypes.c_int
kern._launch(kern.split, (programs, splits), 32 * cfg["nw"], kern.shared,
- [P(q.data_ptr()), P(k_cache.data_ptr()), P(v_cache.data_ptr()), P(block_table.data_ptr()), P(cache_seqlens.data_ptr()),
+ [P(q.data_ptr()), P(k_cache.data_ptr()), P(v_cache.data_ptr()), P(block_table.data_ptr()), P(pool_seqlens.data_ptr()),
P(po.data_ptr()), P(pml.data_ptr()), P(k_scales.data_ptr()), P(v_scales.data_ptr()), P(h32.data_ptr()),
- I(split_len), I(block_table.shape[1]), I(splits)])
+ I(split_len), I(block_table.shape[1]), I(ns_total)])
+ if ring is not None:
+ import triton
+ from .kvwin_triton import ring_split
+ ring_split(ring, q, cache_seqlens, h32, po, pml, ns_total, programs, cfg["qlen"], cfg["nqh"], cfg["nkv"], cfg["hd"],
+ cfg["hd"], cfg["scale"], True, 2, 1, 1, max(16, triton.next_power_of_2(kern.rp)), rpp = kern.rp)
kern._launch(kern.combine, (programs, rows), cfg["hd"], 0,
[P(po.data_ptr()), P(pml.data_ptr()), P(out.data_ptr()), P(h32.data_ptr()),
- P(sinks.data_ptr() if cfg["sinks"] else None), I(splits)])
+ P(sinks.data_ptr() if cfg["sinks"] else None), I(ns_total)])
return out
diff --git a/exllamav3/modules/attention_fn/triton_paged.py b/exllamav3/modules/attention_fn/triton_paged.py
index 5205193..792ac0f 100644
--- a/exllamav3/modules/attention_fn/triton_paged.py
+++ b/exllamav3/modules/attention_fn/triton_paged.py
@@ -1111,8 +1111,9 @@ if _QDEC_HIP_DEBUG:
def _qdec_hip_decode(q, k_cache, v_cache, block_table, cache_seqlens, causal, softmax_scale, window_size, softcap, sinks, out,
- num_splits, max_kv_len, qc, kv_append_len, n_kv_heads):
- """The qdec.hip path of paged_attn_triton_decode, or None when the call is outside its shapes (the Triton kernels then run it)"""
+ num_splits, max_kv_len, qc, kv_append_len, n_kv_heads, ring = None):
+ """The qdec.hip path of paged_attn_triton_decode, or None when the call is outside its shapes (the Triton kernels then run it).
+ ring (KVWIN): the pool pass of qdec_hip over [S, q-W] plus the fp16 ring partial"""
k_scales, v_scales, qck, qcv = qc
why = None
if q.dtype != torch.float16 or q.ndim != 4: why = "q dtype/rank"
@@ -1130,7 +1131,7 @@ def _qdec_hip_decode(q, k_cache, v_cache, block_table, cache_seqlens, causal, so
window_left, window_right = _normalize_window(window_size)
sinks, has_sinks = _prep_sinks(sinks, n_q_heads, q)
cfg = _qh.make_cfg(q_len, n_q_heads, n_kv_heads, head_dim, qck, qcv, k_cache.shape[1], causal, softmax_scale,
- window_left, window_right, softcap, kv_append_len, has_sinks)
+ window_left, window_right, softcap, kv_append_len, has_sinks, ring.cfg.S if ring is not None else 0)
if cfg is None:
if _QDEC_HIP_DEBUG: _qdec_hip_note(("no", f"cfg q_len {q_len} hd {head_dim} {n_q_heads}/{n_kv_heads} bits {qck},{qcv} window {window_left},{window_right} softcap {softcap} append {kv_append_len}"))
return None
@@ -1148,7 +1149,7 @@ def _qdec_hip_decode(q, k_cache, v_cache, block_table, cache_seqlens, causal, so
if out is None:
out = torch.empty_like(q)
with torch.cuda.device(q.device):
- return _qh.decode(cfg, q, k_cache, v_cache, block_table, cache_seqlens, k_scales, v_scales, _get_h32(q.device), sinks, out, max_k_len)
+ return _qh.decode(cfg, q, k_cache, v_cache, block_table, cache_seqlens, k_scales, v_scales, _get_h32(q.device), sinks, out, max_k_len, ring)
# A/B switch, read once at import: CUDA decode runs the upstream exllamav3 1.6.0 (MIT) kernels in triton_paged_cu.py;
# EXL3_ATTN16=0 keeps the kernels in this file. ROCm always keeps them
@@ -1201,9 +1202,9 @@ def paged_attn_triton_decode(
_k = (tuple(q.shape), tuple(k_cache.shape), str(window_size), qc is not None, split_batch)
if _k not in _ATTN16_SEEN:
_ATTN16_SEEN.add(_k); print(" -- attn16 eager decode", _k, "new" if ATTN16 and (qc is not None or _normalize_window(window_size)[0] >= 0) else "old", flush = True)
- if qc is not None and _QDEC_HIP and k is None and ring is None:
+ if qc is not None and _QDEC_HIP and k is None:
out_hip = _qdec_hip_decode(q, k_cache, v_cache, block_table, cache_seqlens, causal, softmax_scale, window_size, softcap,
- sinks, out, num_splits, max_kv_len, qc, pre_appended_len, n_kv_heads_override)
+ 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):
@@ -1335,7 +1336,7 @@ def paged_attn_triton_decode(
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,
+ q_len, n_q_heads, n_kv_heads, head_dim, hd_pad, softmax_scale, qcv > 0, 1,
block_m, block_h, block_rows)
if ns_total > 1:
diff --git a/exllamav3/modules/attention_fn/triton_paged_cu.py b/exllamav3/modules/attention_fn/triton_paged_cu.py
index 87c1681..20b7f62 100644
--- a/exllamav3/modules/attention_fn/triton_paged_cu.py
+++ b/exllamav3/modules/attention_fn/triton_paged_cu.py
@@ -887,7 +887,7 @@ def paged_attn_triton_decode_cu(
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,
+ q_len, n_q_heads, n_kv_heads, head_dim, hd_pad, softmax_scale, qcv > 0, 0,
1, 1, block_rows)
if ns_total > 1:
diff --git a/tests/test_kvwin.py b/tests/test_kvwin.py
index 931e116..e650da6 100644
--- a/tests/test_kvwin.py
+++ b/tests/test_kvwin.py
@@ -42,11 +42,15 @@ def cpu_env(monkeypatch):
monkeypatch.setattr(triton_paged_cu, "pick_config", lambda device, name, key, candidates, probe: candidates[0])
[email protected](autouse = True, params = ["legacy", "cu"])
[email protected](autouse = True, params = ["legacy", "cu", "hip"])
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)."""
+ """Decode wrappers: the pre-1.6 Triton kernels (ROCm default without qdec_hip), the 1.6 ones (CUDA default; run here on
+ whatever GPU) and qdec_hip (ROCm default; skipped without a ROCm GPU)."""
from exllamav3.modules.attention_fn import triton_paged
+ if request.param == "hip" and (CPU or not triton_paged._QDEC_HIP):
+ pytest.skip("qdec_hip needs a ROCm GPU")
monkeypatch.setattr(triton_paged, "ATTN16", request.param == "cu")
+ monkeypatch.setattr(triton_paged, "_QDEC_HIP", request.param == "hip")
return request.param
@@ -186,9 +190,12 @@ def test_ring_write_matches_reference(cfg):
@pytest.mark.parametrize("cfg", CFGS)
@pytest.mark.parametrize("bits", [(4, 4), (6, 6), (8, 8)])
@pytest.mark.parametrize("q_len", [1, 5, 16])
-def test_merge_equals_mix(cfg, bits, q_len):
[email protected]("hd", [128, 256])
+def test_merge_equals_mix(cfg, bits, q_len, hd):
+ if hd == 256 and CPU and (cfg is not CFGS[0] or bits != (4, 4)):
+ pytest.skip("interpreter is slow: one hd 256 cell on CPU")
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)
+ rig = Rig(cfg, hd = hd, 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