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
ROCm prefill: Composable Kernel fmha_fwd for the staged quantized-cache window (hd128/hd256, opt-out via EXL3_PF_CK=0)
YanissAmz7e8360f2fcd9
diff --git a/exllamav3/modules/attention_fn/triton_paged.py b/exllamav3/modules/attention_fn/triton_paged.pyindex 6520a02..8cc0f9e 100644--- a/exllamav3/modules/attention_fn/triton_paged.py+++ b/exllamav3/modules/attention_fn/triton_paged.py@@ -742,6 +742,53 @@ def _prefill_fa2_contig(q, kd, vd, past, n_kvh, head_dim, scale, out):out[:, s:e].copy_(o.transpose(1, 2))return out+# ROCm gfx1151, staged quantized-cache prefill, head_dim 128 / 256, one sequence: after the staging pass the window is contiguous fp16,+# so the chunk runs as one Composable Kernel fmha_fwd call (stock gfx115 128x64 tiles, causal bottom-right, GQA) over past + chunk keys.+# Qwen3.8 geometry (hd 256, 24q/4kv), 4096-row chunk at 4K/32K/120K past: 27.3/158.9/571.7 -> 21.6/122.8/461.7 ms (x1.26/1.29/1.24, 22 ->+# 28 TFLOPS); hd 128 32q/4kv x1.4-1.6; error vs an fp32 reference equal to the Triton kernel's. Served Qwen27 k4v4, 108K-token prompt (74K new):+# TTFT 270.6/271.4 -> 252.2/251.7 s (-7 %), 35K prompt -1.4 %. Needs the library built by tools/strix_halo/ck_fmha/build.sh (EXL3_PF_CK_SO+# overrides the path). EXL3_PF_CK=auto (default): used when the library exists, silently Triton otherwise; 1 = required (warns if missing); 0 = off.+# Any miss falls back to the Triton kernel+_pf_ck_mode = os.environ.get("EXL3_PF_CK", "auto")+_pf_ck = _pf_ck_mode != "0" and bool(torch.version.hip)+_pf_ck_fn = None+++def _pf_ck_load():+ global _pf_ck_fn, _pf_ck+ if _pf_ck_fn is None:+ import ctypes+ from pathlib import Path+ so = Path(os.environ.get("EXL3_PF_CK_SO") or Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")) / "kyojin" / "ck-fmha" / "libckpf.so")+ try:+ fn = ctypes.CDLL(str(so)).ckpf_fwd+ except OSError as e:+ if _pf_ck_mode == "1":+ print(f" !! EXL3_PF_CK=1 but {so} cannot be loaded ({e}); using the Triton prefill kernel")+ _pf_ck = False+ return None+ fn.restype = ctypes.c_float+ fn.argtypes = [ctypes.c_void_p] * 4 + [ctypes.c_int] * 7 + [ctypes.c_float, ctypes.c_int, ctypes.c_void_p, ctypes.c_int]+ _pf_ck_fn = fn+ return _pf_ck_fn+++def _prefill_ck_contig(q, kd, vd, past, n_kvh, head_dim, scale, out):+ """CK fmha_fwd over the contiguous fp16 staged window; None if the kernel declines (caller keeps the Triton path)."""+ fn = _pf_ck_load()+ if fn is None:+ return None+ q_len = q.shape[1]+ k1 = kd.view(1, -1, n_kvh, head_dim)[:, :past + q_len]+ v1 = vd.view(1, -1, n_kvh, head_dim)[:, :past + q_len]+ r = fn(q.data_ptr(), k1.data_ptr(), v1.data_ptr(), out.data_ptr(), 1, q_len, past + q_len, q.shape[2], n_kvh,+ head_dim, head_dim, float(scale), 1, torch.cuda.current_stream(q.device).cuda_stream, 0)+ if r >= 0 and not getattr(_prefill_ck_contig, "_logged", False):+ _prefill_ck_contig._logged = True+ print(f" -- EXL3_PF_CK: CK fmha_fwd prefill attention active (head_dim {head_dim}, {q.shape[2]}q/{n_kvh}kv)")+ return out if r >= 0 else None++def _get_h32(device):if device not in _h32_cache:h = torch.ones(1, 1, dtype = torch.float32)@@ -2076,6 +2123,16 @@ def paged_attn_triton_prefill(if out is None:out = torch.empty_like(q)return _prefill_fa2_contig(q, kd, vd, max_kv_len, n_kvh, head_dim, softmax_scale, out)+ if (_pf_ck and bsz == 1 and kv_append_len == q_len+ and head_dim in (128, 256) and v_dim == head_dim+ and window_left < 0 and window_right < 0 and not softcap and not has_sinks+ and num_splits is None and block_m is None and q.is_contiguous() and tq is None):+ if out is None:+ out = torch.empty_like(q)+ # ROCm callers leave max_kv_len unset outside QSA: read the past from the device copy (one tiny sync per call)+ past = max_kv_len if max_kv_len is not None else int(cache_seqlens[0].item())+ if _prefill_ck_contig(q, kd, vd, past, n_kvh, head_dim, softmax_scale, out) is not None:+ return outelse:k_scales, v_scales, qck, qcv = q, q, 0, 0h32 = qdiff --git a/tests/test_prefill_ck.py b/tests/test_prefill_ck.pynew file mode 100644index 0000000..86939c9--- /dev/null+++ b/tests/test_prefill_ck.py@@ -0,0 +1,54 @@+import os+import pytest+import torch++pytestmark = pytest.mark.skipif(not torch.cuda.is_available() or torch.version.hip is None, reason = "ROCm only")++from exllamav3.modules.attention_fn import triton_paged as tp++_SO = os.environ.get("EXL3_PF_CK_SO") or os.path.expanduser("~/.cache/kyojin/ck-fmha/libckpf.so")+++def _reference(q, k, v, past, scale, rows):+ # fp32 attention for the selected query rows, queries aligned to the end of the keys, GQA by repeat+ q_len, n_heads, hd = q.shape+ n_kv = k.shape[1]+ out = []+ for r in rows:+ n = past + r + 1+ kf = k[:n].float().repeat_interleave(n_heads // n_kv, dim = 1)+ vf = v[:n].float().repeat_interleave(n_heads // n_kv, dim = 1)+ s = torch.einsum("hd,khd->hk", q[r].float(), kf) * scale+ out.append(torch.einsum("hk,khd->hd", s.softmax(-1), vf))+ return torch.stack(out)++[email protected](not os.path.isfile(_SO), reason = "libckpf.so not built (tools/strix_halo/ck_fmha/build.sh)")[email protected]("hd, n_heads", [(256, 24), (128, 32)])[email protected]("q_len, past", [(300, 0), (1024, 0), (2500, 3000), (4096, 5000), (777, 2001), (4096, 0)])+def test_ck_matches_fp32_reference_and_triton(monkeypatch, hd, n_heads, q_len, past):+ monkeypatch.setenv("EXL3_PF_CK_SO", _SO)+ torch.manual_seed(0)+ n_kv = 4+ q = torch.randn(1, q_len, n_heads, hd, device = "cuda", dtype = torch.half)+ kd = (torch.randn(1, past + q_len + 100, n_kv, hd, device = "cuda") * .5).half()+ vd = torch.randn(1, past + q_len + 100, n_kv, hd, device = "cuda", dtype = torch.half)+ scale = hd ** -0.5+ out = torch.zeros_like(q)+ assert tp._prefill_ck_contig(q, kd, vd, past, n_kv, hd, scale, out) is out+ rows = sorted({0, 1, q_len // 2, q_len - 1})+ ref = _reference(q[0], kd[0], vd[0], past, scale, rows)+ assert (out[0, rows].float() - ref).abs().max().item() / ref.abs().max().item() < 2e-3+ # same K/V through the Triton kernel (paged, identity table): both are fp16-noise away from the reference+ page = 256+ pages = (past + q_len + page - 1) // page+ kc = torch.zeros(pages, page, n_kv, hd, device = "cuda", dtype = torch.half)+ vc = torch.zeros_like(kc)+ kc.view(-1, n_kv, hd)[:past + q_len] = kd[0, :past + q_len]+ vc.view(-1, n_kv, hd)[:past + q_len] = vd[0, :past + q_len]+ bt = torch.arange(pages, dtype = torch.int32, device = "cuda")[None]+ sl = torch.tensor([past], dtype = torch.int32, device = "cuda")+ tri = tp.paged_attn_triton_prefill(q, None, None, kc, vc, bt, sl, causal = True, softmax_scale = scale,+ k_new = kd[:, past:past + q_len].contiguous(), v_new = vd[:, past:past + q_len].contiguous(),+ max_kv_len = past)+ assert (out.float() - tri.float()).abs().max().item() < 5e-3diff --git a/tools/strix_halo/ck_fmha/build.sh b/tools/strix_halo/ck_fmha/build.shnew file mode 100755index 0000000..7801917--- /dev/null+++ b/tools/strix_halo/ck_fmha/build.sh@@ -0,0 +1,22 @@+#!/usr/bin/env bash+# Build libckpf.so: Composable Kernel fmha_fwd (stock gfx115 fp16 tiles, hd128 + hd256, batch mode, causal/none) behind+# a C ABI (ckpf_fwd) used by EXL3_PF_CK=1. Nothing is fetched here: CK_SRC is a local ROCm/composable_kernel checkout+# (tested at 6f44fdf90f69adee742ec3660b95d32963b9bd2d). Output: $EXL3_CK_OUT (default ~/.cache/kyojin/ck-fmha/libckpf.so).+# Needs the ROCm clang (ROCM_CLANG, default /opt/rocm/bin/amdclang++) and a libstdc++ GCC install dir (GCC_DIR, default 13).+set -euo pipefail+: "${CK_SRC:?set CK_SRC to a composable_kernel checkout}"+HERE=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)+OUT=${EXL3_CK_OUT:-${XDG_CACHE_HOME:-$HOME/.cache}/kyojin/ck-fmha/libckpf.so}+CXX=${ROCM_CLANG:-/opt/rocm/bin/amdclang++}+GCC_DIR=${GCC_DIR:-/usr/lib/gcc/x86_64-linux-gnu/13}+F=$CK_SRC/example/ck_tile/01_fmha+B=$(mktemp -d); trap 'rm -rf "$B"' EXIT+mkdir -p "$B/gen" "$B/obj" "$(dirname "$OUT")"+python3 "$F/generate.py" --targets gfx1151 --api fwd --optdim 128,256 -r 0 \+ -f "*fp16*batch*_nlogits_nbias_*_nlse_ndropout_nskip_nqscale*_nsink*" -o "$B/gen" >/dev/null+FLAGS="--gcc-install-dir=$GCC_DIR -std=c++20 -O3 -fPIC -x hip --offload-arch=gfx1151 -I$CK_SRC/include -I$F -I$B/gen \+ -DCK_TILE_FMHA_FWD_FAST_EXP2=1 -fgpu-flush-denormals-to-zero -DCK_TILE_FMHA_FWD_SPLITKV_API=0 -DCK_TILE_FMHA_FWD_APPENDKV_API=0 \+ -DCK_TILE_FMHA_FWD_PAGEDKV_API=0 -DCK_TILE_FMHA_FWD_BATCH_PREFILL_API=0 -w"+ls "$B"/gen/*.cpp "$HERE/ckpf_shim.cpp" | nice -n 19 taskset -c 16-31 xargs -P 8 -I{} sh -c "$CXX $FLAGS -c {} -o $B/obj/\$(basename {} .cpp).o"+"$CXX" --gcc-install-dir="$GCC_DIR" -shared -fPIC --offload-arch=gfx1151 "$B"/obj/*.o -o "$OUT"+echo "built $OUT"diff --git a/tools/strix_halo/ck_fmha/ckpf_shim.cpp b/tools/strix_halo/ck_fmha/ckpf_shim.cppnew file mode 100644index 0000000..193fd30--- /dev/null+++ b/tools/strix_halo/ck_fmha/ckpf_shim.cpp@@ -0,0 +1,36 @@+// ckpf: C ABI over CK fmha_fwd (batch mode, bshd, fp16, GQA, causal bottom-right)+#include <cmath>+#include <cstdint>+#include <hip/hip_runtime.h>+#include "bias.hpp"+#include "fmha_fwd.hpp"+#include "mask.hpp"++extern "C" float ckpf_fwd(const void* q, const void* k, const void* v, void* o,+ int batch, int sq, int sk, int hq, int hk, int dq, int dv,+ float scale, int causal, hipStream_t stream, int time_it)+{+ fmha_fwd_traits t{};+ t.hdim_q = dq; t.hdim_v = dv; t.data_type = "fp16"; t.is_group_mode = false;+ t.is_v_rowmajor = true; t.has_logits_soft_cap = false;+ t.mask_type = causal ? mask_enum::mask_bottom_right : mask_enum::no_mask;+ t.bias_type = bias_enum::no_bias; t.has_lse = false; t.has_dropout = false;+ t.qscale_type = quant_scale_enum::no_scale;+ fmha_fwd_args a{};+ a.q_ptr = q; a.k_ptr = k; a.v_ptr = v; a.o_ptr = o;+ a.seqlen_q = sq; a.seqlen_k = sk; a.batch = batch; a.max_seqlen_q = sq;+ a.hdim_q = dq; a.hdim_v = dv; a.nhead_q = hq; a.nhead_k = hk;+ a.scale_s = scale; a.logits_soft_cap = 0.f;+ a.stride_q = hq * dq; a.stride_k = hk * dq; a.stride_v = hk * dv; a.stride_o = hq * dv;+ a.nhead_stride_q = dq; a.nhead_stride_k = dq; a.nhead_stride_v = dv; a.nhead_stride_o = dv;+ a.batch_stride_q = (ck_tile::index_t)sq * hq * dq;+ a.batch_stride_k = (ck_tile::index_t)sk * hk * dq;+ a.batch_stride_v = (ck_tile::index_t)sk * hk * dv;+ a.batch_stride_o = (ck_tile::index_t)sq * hq * dv;+ a.window_size_left = -1; a.window_size_right = causal ? 0 : -1;+ a.mask_type = static_cast<ck_tile::index_t>(t.mask_type);+ a.p_drop = 0.f; a.s_randval = false;+ a.drop_seed_offset = std::pair<uint64_t, uint64_t>{0, 0};+ ck_tile::stream_config cfg{stream, time_it != 0, 0, 0, 1, false};+ return fmha_fwd(t, a, cfg);+}