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.

Kyojin 1.2: Qwen prefill tail merge, split MoE stage launches, 8-bit context cache by default, logprobs, request timing line

YanissAmza3ac00d4a321
diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_fused9.cu b/exllamav3/exllamav3_ext/quant/exl3_moe_fused9.cu
index 0b5534f..d034ce2 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_moe_fused9.cu
+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_fused9.cu
@@ -22,7 +22,7 @@ template <class S7, bool TM, int OCC, int INL, int ABL = 0> int grid7()
int nb = 0, dev = 0; hipGetDevice(&dev);
hipDeviceProp_t prop; hipGetDeviceProperties(&prop, dev);
cuda_check(hipOccupancyMaxActiveBlocksPerMultiprocessor(&nb, (OCC ? (const void*) mf9::moe_fused9o_kernel<S7, TM, (bool) INL, ABL> : (const void*) mf9::moe_fused9_kernel<S7, TM, (bool) INL, ABL>), mf::THREADS, 0));
- return (OCC == 3 ? 1 : OCC == 2 ? 2 : std::max(1, nb)) * prop.multiProcessorCount; // OCC 2: forced two blocks per WGP (the occupancy API reports one); OCC 3: one block per WGP, half the VGPR / LDS free for other GPU clients
+ return (OCC == 3 ? 1 : (OCC == 2 || OCC == 4) ? 2 : std::max(1, nb)) * prop.multiProcessorCount; // OCC 2: forced two blocks per WGP (the occupancy API reports one); OCC 4: two blocks per WGP as six stage launches without any grid barrier; OCC 3: one block per WGP, half the VGPR / LDS free for other GPU clients
}();
return G;
}
@@ -60,8 +60,21 @@ template <class S7, bool TM, int OCC, int INL, int ABL = 0> void launch7(const a
p.dots = (float*) (wb + off[1]); p.post = (float*) (wb + off[2]); p.mixed = (half*) (wb + off[3]); p.scores = (half*) (wb + off[4]);
p.sgl = (float*) (wb + off[5]); p.gu = (half*) (wb + off[6]); p.dn = (float*) (wb + off[7]); p.ydbg = (float*) (wb + off[8]); p.seldbg = (int*) (wb + off[9]);
p.rms_eps = (float) rms_eps;
- if (OCC) { mf9::moe_fused9o_kernel<S7, TM, (bool) INL, ABL><<<p.G, mf::THREADS, 0, stream>>>(p, vmask); }
- else { mf9::moe_fused9_kernel<S7, TM, (bool) INL, ABL><<<p.G, mf::THREADS, 0, stream>>>(p, vmask); }
+ if constexpr (OCC == 4)
+ {
+ static_assert(!TM && INL == 1, "split launches: no timing build, inline phases");
+ mf9::moe_fused9s_kernel<S7, (bool) INL, ABL, 0><<<p.G, mf::THREADS, 0, stream>>>(p, vmask);
+ mf9::moe_fused9s_kernel<S7, (bool) INL, ABL, 1><<<p.G, mf::THREADS, 0, stream>>>(p, vmask);
+ mf9::moe_fused9s_kernel<S7, (bool) INL, ABL, 2><<<p.G, mf::THREADS, 0, stream>>>(p, vmask);
+ mf9::moe_fused9s_kernel<S7, (bool) INL, ABL, 3><<<p.G, mf::THREADS, 0, stream>>>(p, vmask);
+ mf9::moe_fused9s_kernel<S7, (bool) INL, ABL, 4><<<p.G, mf::THREADS, 0, stream>>>(p, vmask);
+ mf9::moe_fused9s_kernel<S7, (bool) INL, ABL, 5><<<p.G, mf::THREADS, 0, stream>>>(p, vmask);
+ }
+ else
+ {
+ if (OCC) { mf9::moe_fused9o_kernel<S7, TM, (bool) INL, ABL><<<p.G, mf::THREADS, 0, stream>>>(p, vmask); }
+ else { mf9::moe_fused9_kernel<S7, TM, (bool) INL, ABL><<<p.G, mf::THREADS, 0, stream>>>(p, vmask); }
+ }
cuda_check(hipPeekAtLastError());
}
} // namespace
@@ -81,6 +94,7 @@ void mf9_half(at::Tensor& x, const at::Tensor& fn, const at::Tensor& fn_scale, c
#define L7A(SH, TMV, OCCV, INLV, ABLV) launch7<SH, TMV, OCCV, INLV, ABLV>(x, fn, fn_scale, upt, up_scale, w_h, router, sgate, wt, svt, ws, rms_eps, (int) native, R, (int) (variant & 0xffff), stream)
#define L7(SH, TMV, OCCV, INLV) launch7<SH, TMV, OCCV, INLV>(x, fn, fn_scale, upt, up_scale, w_h, router, sgate, wt, svt, ws, rms_eps, (int) native, R, (int) (variant & 0xffff), stream)
#define X7(SH) if (Match7<SH>::eq(D, H, LR, NEXP, TOPK, INTER, RB, SB)) { \
+ if (variant & 0x100000) { TORCH_CHECK((variant & 0x1f0000) == 0x160000 && !timing, "mf9: split launches (0x100000) need variant 0x160000 and no timing"); L7(SH, false, 4, 1); return; } /* six stage launches, no grid barrier */ \
if ((variant & 0x80000) && (variant & 0x70000) == 0x60000) { if (timing) L7(SH, true, 3, 1); else L7(SH, false, 3, 1); return; } /* one block per WGP */ \
const int occ = (variant & 0x40000) ? 2 : ((variant & 0x10000) != 0), inl = (variant & 0x20000) != 0; \
if (timing) { if (occ == 2) { if (inl) L7(SH, true, 2, 1); else L7(SH, true, 2, 0); } else if (occ) { if (inl) L7(SH, true, 1, 1); else L7(SH, true, 1, 0); } else { if (inl) L7(SH, true, 0, 1); else L7(SH, true, 0, 0); } return; } \
@@ -90,6 +104,7 @@ void mf9_half(at::Tensor& x, const at::Tensor& fn, const at::Tensor& fn_scale, c
// the shapes of K3 / K4 routed packs and K4 / K5 shared experts carry the served variant only (two blocks per WGP, forced inline, no timing build)
#define X9D(SH) if (Match7<SH>::eq(D, H, LR, NEXP, TOPK, INTER, RB, SB)) { \
TORCH_CHECK((variant & 0x70000) == 0x60000, "mf9: this shape is instantiated for the default variant 0x60000 only"); \
+ if (variant & 0x100000) { TORCH_CHECK((variant & 0x1f0000) == 0x160000 && !timing, "mf9: split launches (0x100000) need variant 0x160000 and no timing"); L7(SH, false, 4, 1); return; } /* split launches */ \
const bool one = (variant & 0x80000) != 0; /* one block per WGP, same kernel and arithmetic */ \
if (timing) { if (one) L7(SH, true, 3, 1); else L7(SH, true, 2, 1); return; } \
if (one) L7(SH, false, 3, 1); else L7(SH, false, 2, 1); return; }
diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_fused9.cuh b/exllamav3/exllamav3_ext/quant/exl3_moe_fused9.cuh
index 74c2945..8f99047 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_moe_fused9.cuh
+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_fused9.cuh
@@ -251,5 +251,32 @@ __global__ __launch_bounds__(THREADS) void moe_fused9_kernel(Params p, int vm) {
template <class S, bool TM, bool INL, int ABL = 0>
__global__ __launch_bounds__(THREADS) __attribute__((amdgpu_num_vgpr(192))) void moe_fused9o_kernel(Params p, int vm) { body9<S, TM, INL, ABL>(p, vm); }
+// Split launches. The same phases and the same block partition as body9 (G = two blocks per WGP), but every grid barrier is a kernel boundary,
+// so no block ever waits for another one and residency does not matter (a desktop client sharing the iGPU cannot stall or corrupt the step).
+// Stage 0 dots | 1 finalize | 2 router | 3 top-k + gate/up | 4 down | 5 combine. The top-k result crosses the boundaries through seldbg (selected experts and weights, written by block 0 of stage 3).
+template <class S, bool INL, int ABL, int STAGE>
+__device__ __forceinline__ void body9s(const Params& p, int vm)
+{
+ static_assert(INL, "split launches exist for the forced-inline phases only");
+ __shared__ Smem<S> s;
+ uint32_t sink = 0;
+ if constexpr (STAGE == 0) { if (vm & V_T0) touch_static<S>(p, vm, sink); ph_dots9<S>(p, s, vm, sink); }
+ if constexpr (STAGE == 1) ph_finalize9<S, false>(p, s);
+ if constexpr (STAGE == 2) ph_router9<S>(p, s);
+ if constexpr (STAGE == 3)
+ {
+ ph_topk9<S>(p, s, vm);
+ if (blockIdx.x == 0 && threadIdx.x < p.R * S::TOPK) p.seldbg[threadIdx.x] = s.sel[threadIdx.x];
+ if (blockIdx.x == 0 && threadIdx.x < p.R * S::TOPK) p.seldbg[64 + threadIdx.x] = (int) __half_as_ushort(s.wt[threadIdx.x]);
+ if (vm & V_TDOWN) touch_down<S>(p, s, sink);
+ ph_gateup9<S, ABL>(p, s);
+ }
+ if constexpr (STAGE == 4) { topk_restore9<S>(p, s); ph_down9<S, ABL>(p, s); }
+ if constexpr (STAGE == 5) { topk_restore9<S>(p, s); ph_combine9<S>(p, s); }
+ asm volatile("" :: "v"(sink));
+}
+template <class S, bool INL, int ABL, int STAGE>
+__global__ __launch_bounds__(THREADS) __attribute__((amdgpu_num_vgpr(192))) void moe_fused9s_kernel(Params p, int vm) { body9s<S, INL, ABL, STAGE>(p, vm); }
+
} // namespace mf9
#endif
diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_fused9_inl.cuh b/exllamav3/exllamav3_ext/quant/exl3_moe_fused9_inl.cuh
index 769a3e2..cbacbd8 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_moe_fused9_inl.cuh
+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_fused9_inl.cuh
@@ -327,6 +327,33 @@ __device__ __forceinline__ float tk2_value(const uint32_t ukey)
return __half2float(__ushort_as_half((unsigned short) u));
}
+template <class S>
+__device__ __forceinline__ void ph_topk_tail9(const Params& p, Smem<S>& s)
+{
+ MF_DIMS
+ const int R = p.R;
+ const int NA = R * TOPK;
+ if (threadIdx.x < NA)
+ {
+ const int a = threadIdx.x, e = s.sel[a];
+ int pp = 0;
+ for (int b = 0; b < NA; ++b) { const int eb = s.sel[b]; pp += (eb < e) || (eb == e && b < a); }
+ s.sorted_e[pp] = e; s.sorted_a[pp] = a; s.tok[pp] = a / TOPK;
+ }
+ __syncthreads();
+ if (threadIdx.x < NA) s.head[threadIdx.x] = (threadIdx.x == 0 || s.sorted_e[threadIdx.x - 1] != s.sorted_e[threadIdx.x]) ? 1 : 0;
+ __syncthreads();
+ if (threadIdx.x == 0)
+ {
+ int g = 0;
+ for (int q = 0; q < NA; ++q) if (s.head[q]) s.gstart[g++] = q;
+ s.gstart[g] = NA; s.ngroups = g;
+ for (int u = 0; u < g; ++u) s.urows[u] = min(s.gstart[u + 1] - s.gstart[u], MAXR);
+ s.urows[g] = R; // the shared expert: R rows
+ }
+ __syncthreads();
+}
+
template <class S>
__device__ __forceinline__ void ph_topk9(const Params& p, Smem<S>& s, int vm = 0)
{
@@ -425,26 +452,20 @@ __device__ __forceinline__ void ph_topk9(const Params& p, Smem<S>& s, int vm = 0
}
}
__syncthreads();
- const int NA = R * TOPK;
- if (threadIdx.x < NA)
- {
- const int a = threadIdx.x, e = s.sel[a];
- int pp = 0;
- for (int b = 0; b < NA; ++b) { const int eb = s.sel[b]; pp += (eb < e) || (eb == e && b < a); }
- s.sorted_e[pp] = e; s.sorted_a[pp] = a; s.tok[pp] = a / TOPK;
- }
- __syncthreads();
- if (threadIdx.x < NA) s.head[threadIdx.x] = (threadIdx.x == 0 || s.sorted_e[threadIdx.x - 1] != s.sorted_e[threadIdx.x]) ? 1 : 0;
- __syncthreads();
- if (threadIdx.x == 0)
+ ph_topk_tail9<S>(p, s);
+}
+
+// Split launches: the stages after the router re-enter here with s.sel / s.wt reloaded from seldbg (block 0 of the top-k stage wrote them)
+template <class S>
+__device__ __forceinline__ void topk_restore9(const Params& p, Smem<S>& s)
+{
+ if (threadIdx.x < p.R * S::TOPK)
{
- int g = 0;
- for (int q = 0; q < NA; ++q) if (s.head[q]) s.gstart[g++] = q;
- s.gstart[g] = NA; s.ngroups = g;
- for (int u = 0; u < g; ++u) s.urows[u] = min(s.gstart[u + 1] - s.gstart[u], MAXR);
- s.urows[g] = R; // the shared expert: R rows
+ s.sel[threadIdx.x] = p.seldbg[threadIdx.x];
+ s.wt[threadIdx.x] = __ushort_as_half((unsigned short) p.seldbg[64 + threadIdx.x]);
}
__syncthreads();
+ ph_topk_tail9<S>(p, s);
}
template <class S, int ABL>
diff --git a/exllamav3/ext_fallbacks.py b/exllamav3/ext_fallbacks.py
index 7e6f5f2..d8a2b75 100644
--- a/exllamav3/ext_fallbacks.py
+++ b/exllamav3/ext_fallbacks.py
@@ -601,7 +601,7 @@ def _quant_cache_paged_one(source: torch.Tensor, packed: torch.Tensor, scales: t
scales.reshape(-1, groups).index_copy_(0, destination_positions, q_scales)
-def quant_cache_paged(
+def _quant_cache_paged_torch(
k_in: torch.Tensor, k_out: torch.Tensor, k_out_scales: torch.Tensor,
v_in: torch.Tensor, v_out: torch.Tensor, v_out_scales: torch.Tensor,
cache_seqlens: torch.Tensor, block_table: torch.Tensor, page_size: int,
@@ -828,3 +828,32 @@ class _BCNone:
__slots__ = ()
def __call__(self, *args: Any, **kwargs: Any) -> None:
return None
+
+
+_QW_OFF = os.environ.get("EXL3_QWRITE_TRITON", "1") == "0"
+
+
+def quant_cache_paged(
+ k_in, k_out, k_out_scales, v_in, v_out, v_out_scales,
+ cache_seqlens, block_table, page_size, seq_len, compand_a = 0.0, in_contiguous = False,
+):
+ """Paged cache append: native Triton writer for the 8-bit layout, torch fallback otherwise."""
+ if (
+ not _QW_OFF and compand_a == 0.0 and seq_len > 0 and k_in.is_cuda and
+ k_out.ndim == 3 and v_out.ndim == 3 and k_out_scales.shape[-1] in (8, 16, 32, 64) and
+ k_out.shape[-1] == k_out_scales.shape[-1] * 8 and v_out.shape[-1] == k_out.shape[-1] and
+ v_out_scales.shape == k_out_scales.shape and
+ k_in.dtype == torch.float16 and v_in.dtype == torch.float16 and
+ k_in.is_contiguous() and v_in.is_contiguous() and page_size == 256 and
+ k_out.dtype == torch.int32 and v_out.dtype == torch.int32 and
+ k_out_scales.dtype == torch.float16 and v_out_scales.dtype == torch.float16 and
+ cache_seqlens.dtype == torch.int32 and block_table.dtype == torch.int32 and
+ k_in.shape == v_in.shape and k_in.numel() >= block_table.shape[0] * seq_len * (k_out_scales.shape[-1] * 32) and
+ (in_contiguous or k_in.numel() == k_out.shape[0] * page_size * k_out_scales.shape[-1] * 32)
+ ):
+ from .modules.attention_fn.qwrite_triton import quant_cache_paged8
+ quant_cache_paged8(k_in, k_out, k_out_scales, v_in, v_out, v_out_scales,
+ cache_seqlens, block_table, seq_len, in_contiguous)
+ return
+ _quant_cache_paged_torch(k_in, k_out, k_out_scales, v_in, v_out, v_out_scales,
+ cache_seqlens, block_table, page_size, seq_len, compand_a, in_contiguous)
diff --git a/exllamav3/generator/job.py b/exllamav3/generator/job.py
index 32d0fe4..405eda7 100644
--- a/exllamav3/generator/job.py
+++ b/exllamav3/generator/job.py
@@ -727,7 +727,13 @@ class Job:
"eos_triggering_token_id": stop_token,
"eos_triggering_token_str": id_to_piece[stop_token]
})
- pass
+ # The stop token itself is not streamed as a token, but its probability and top candidates are reported
+ # (the entry of the position where the stop token was sampled), so a client can score every position.
+ if self.held_probs:
+ r.update({ "stop_token_prob": self.held_probs.torch()[:, -1:].clone() })
+ if self.held_k_tokens:
+ r.update({ "stop_token_top_k_tokens": self.held_k_tokens.torch()[:, -1:].clone() })
+ r.update({ "stop_token_top_k_probs": self.held_k_probs.torch()[:, -1:].clone() })
if eos_reason == "stop_string":
r.update({ "eos_triggering_string": stop_string })
@@ -1272,6 +1278,14 @@ class Job:
if not (big_tail and prefill_end >= len(seq.sequence_ids) - 1):
prefill_end = (prefill_end // PAGE_SIZE) * PAGE_SIZE
prefill_end = min(prefill_end, len(seq.sequence_ids) - 1)
+ # EXL3_PF_NO_TAIL=1 (GDN models): the last chunk runs to the end of the prompt even when that is not a page
+ # boundary (it would otherwise be a second forward pass re-reading every expert); the last-page recurrent
+ # checkpoint is written from inside the chunk (see no_tail_row below). EXL3_PF_TAIL_MERGE: extra rows beyond the
+ # chunk size a merged last chunk may take (default 0: only what fits in one chunk)
+ gdn_nt = self.gdn_no_tail_enabled()
+ if gdn_nt and seq.kv_position % PAGE_SIZE == 0 and \
+ remaining <= chunk + int(os.environ.get("EXL3_PF_TAIL_MERGE", "0")):
+ prefill_end = len(seq.sequence_ids) - 1
atomic_mm_prefill = bool(self.embeddings) and self.generator.model.caps.get("atomic_mm_prefill")
mm_exact_chunks = bool(self.embeddings) and self.generator.model.caps.get("mm_exact_chunks")
@@ -1362,7 +1376,10 @@ class Job:
# (a 4K prompt ran 3840 + 255, the 255-row tail cost ~1 s); the chunk runs whole and the KDA
# kernel side-writes the last-page state as a second mid-chunk checkpoint (stash_midchunk)
# Chunks under 512 rows keep the cut: chunk_kda runs the fla chain there (no HIP side-write)
- if big_tail and prefill_start < last_page_b < prefill_end and prefill_start % PAGE_SIZE == 0 and \
+ if gdn_nt and prefill_end == seqlen and prefill_start < last_page_b < prefill_end and \
+ prefill_start % PAGE_SIZE == 0:
+ no_tail_row = last_page_b - prefill_start
+ elif big_tail and prefill_start < last_page_b < prefill_end and prefill_start % PAGE_SIZE == 0 and \
prefill_end - prefill_start >= 512 and os.environ.get("EXL3_PF_NO_TAIL", "0") == "1":
no_tail_row = last_page_b - prefill_start
elif prefill_start < last_page_b <= prefill_end:
@@ -1451,19 +1468,22 @@ class Job:
# EXL3_MIDCHUNK_CKPT=1 (default off): a chunk that crosses a recurrent checkpoint boundary also
# saves the recurrent state at that boundary (KDA layers split conv + core there), stashed below
if self.recurrent_state is not None and not self.embeddings and \
- os.environ.get("EXL3_MIDCHUNK_CKPT", "0") in ("1", "2") and \
+ (os.environ.get("EXL3_MIDCHUNK_CKPT", "0") in ("1", "2") or (gdn_nt and no_tail_row is not None)) and \
not self.generator.model.loaded_tp and prefill_start % PAGE_SIZE == 0:
- rows = [
- p - prefill_start
- for p in range(prefill_start + PAGE_SIZE, prefill_end, PAGE_SIZE)
- if self.is_checkpoint_boundary(pos = p)
- ]
- if no_tail_row is not None:
- rows = sorted(set(rows + [no_tail_row]))
+ if gdn_nt:
+ rows = [] if no_tail_row is None else [no_tail_row]
+ else:
+ rows = [
+ p - prefill_start
+ for p in range(prefill_start + PAGE_SIZE, prefill_end, PAGE_SIZE)
+ if self.is_checkpoint_boundary(pos = p)
+ ]
+ if no_tail_row is not None:
+ rows = sorted(set(rows + [no_tail_row]))
if rows:
params["checkpoint_rows"] = rows
- # 1: split conv + KDA core (reference), 2: in-kernel S side-write + async D2H
- params["midchunk_mode"] = int(os.environ["EXL3_MIDCHUNK_CKPT"])
+ # 1: split conv + KDA core (reference), 2: in-kernel S side-write + async D2H (the only GDN mode)
+ params["midchunk_mode"] = 2 if gdn_nt else int(os.environ["EXL3_MIDCHUNK_CKPT"])
if self.generator.mtp_draft:
# MTP needs the target's post-final-norm state for every prompt token.
# Normal prefill stops at the last cache-writing layer, before final norm.
@@ -1672,6 +1692,29 @@ class Job:
f.is_active = f.trigger_token is None and not self.filters_suspended
+ def gdn_no_tail_enabled(self):
+ """
+ EXL3_PF_NO_TAIL=1 for GDN (non-KDA) recurrent models: text-only job, no TP, every recurrent layer a GatedDeltaNet (or the
+ Qwen PLE layer) with the fused HIP chain (EXL3_GDN_FUSE=1, EXL3_GDN_PF on), the only path that side-writes the mid-chunk state.
+ """
+ if os.environ.get("EXL3_PF_NO_TAIL", "0") != "1" or os.environ.get("EXL3_GDN_FUSE", "0") != "1" or \
+ os.environ.get("EXL3_GDN_PF", "1") != "1":
+ return False
+ if self.recurrent_state is None or self.embeddings:
+ return False
+ g = self.generator
+ ok = getattr(g, "_gdn_no_tail_ok", None)
+ if ok is None:
+ from ..modules.gated_delta_net import GatedDeltaNet
+ from ..modules.ple import PLELayer # Qwen 3.8: one PLE layer also holds a recurrent state (it saves its own mid-chunk state)
+ rl = g.model.get_recurrent_layers()
+ ok = bool(rl) and not g.model.loaded_tp and \
+ all(isinstance(m, PLELayer) or (isinstance(m, GatedDeltaNet) and not m.kda) for m in rl) and \
+ any(isinstance(m, GatedDeltaNet) for m in rl)
+ g._gdn_no_tail_ok = ok
+ return ok
+
+
def big_tail_enabled(self):
"""
EXL3_PREFILL_BIG_TAIL=1, honored only with EXL3_MIDCHUNK_CKPT=2 and where the mid-chunk path can stash every
diff --git a/exllamav3/model/dense_gemm_tune_seed.txt b/exllamav3/model/dense_gemm_tune_seed.txt
new file mode 100644
index 0000000..a17dafd
--- /dev/null
+++ b/exllamav3/model/dense_gemm_tune_seed.txt
@@ -0,0 +1,138 @@
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 512 2560 4352 3 0 -1162086340
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 640 2560 4352 1 0 -1162086337
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 640 4352 1 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 6144 4352 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 6144 2560 4352 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 4352 1 0 -1162086365
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 4352 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 12288 2560 4352 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 512 2560 4608 3 0 -1162086355
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 640 2560 4608 1 0 -1162086365
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 640 4608 1 0 -1162086364
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 6144 4608 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 6144 2560 4608 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 4608 1 0 -1162086365
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 4608 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 12288 2560 4608 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 512 2560 4864 3 0 -1162086340
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 640 2560 4864 1 0 -1162086365
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 640 4864 1 0 -1162086302
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 6144 4864 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 6144 2560 4864 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 4864 1 0 -1162086367
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 4864 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 12288 2560 4864 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 512 2560 5120 3 0 -1162086356
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 640 2560 5120 1 0 -1162086365
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 640 5120 1 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 6144 5120 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 6144 2560 5120 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 5120 1 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 5120 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 12288 2560 5120 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 512 2560 5376 3 0 -1162086308
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 640 2560 5376 1 0 -1162086368
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 640 5376 1 0 -1162086370
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 6144 5376 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 6144 2560 5376 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 5376 1 0 -1162086365
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 5376 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 12288 2560 5376 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 512 2560 5632 3 0 -1162086327
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 640 2560 5632 1 0 -1162086367
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 640 5632 1 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 6144 5632 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 6144 2560 5632 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 5632 1 0 -1162086365
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 5632 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 12288 2560 5632 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 512 2560 5888 3 0 -1162086313
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 640 2560 5888 1 0 -1162086362
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 640 5888 1 0 -1162086366
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 6144 5888 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 6144 2560 5888 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 5888 1 0 -1162086365
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 5888 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 12288 2560 5888 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 512 2560 6144 3 0 -1162086316
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 640 2560 6144 1 0 -1162086367
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 640 6144 1 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 6144 6144 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 6144 2560 6144 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 6144 1 0 -1162086365
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 6144 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 12288 2560 6144 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 512 2560 6400 3 0 -1162086313
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 640 2560 6400 1 0 -1162086367
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 640 6400 1 0 -1162086366
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 6144 6400 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 6144 2560 6400 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 6400 1 0 -1162086365
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 6400 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 12288 2560 6400 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 512 2560 6656 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 640 2560 6656 1 0 -1162086367
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 640 6656 1 0 -1162086370
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 6144 6656 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 6144 2560 6656 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 6656 1 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 6656 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 12288 2560 6656 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 512 2560 6912 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 640 2560 6912 1 0 -1162086367
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 640 6912 1 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 6144 6912 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 6144 2560 6912 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 6912 1 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 6912 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 12288 2560 6912 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 512 2560 7168 3 0 -1162086305
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 640 2560 7168 1 0 -1162086368
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 640 7168 1 0 -1162086370
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 6144 7168 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 6144 2560 7168 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 7168 1 0 -1162086365
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 7168 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 12288 2560 7168 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 512 2560 7424 3 0 -1162086355
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 640 2560 7424 1 0 -1162086367
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 640 7424 1 0 -1162086364
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 6144 7424 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 6144 2560 7424 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 7424 1 0 -1162086365
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 7424 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 12288 2560 7424 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 512 2560 7680 3 0 -1162086356
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 640 2560 7680 1 0 -1162086368
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 640 7680 1 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 6144 7680 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 6144 2560 7680 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 7680 1 0 -1162086365
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 7680 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 12288 2560 7680 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 512 2560 7936 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 640 2560 7936 1 0 -1162086365
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 640 7936 1 0 -1162086370
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 6144 7936 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 6144 2560 7936 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 7936 1 0 -1162086365
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 7936 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 12288 2560 7936 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 512 2560 8192 3 0 -1162086316
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 6144 8192 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 6144 2560 8192 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 10240 2560 8192 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 12288 2560 8192 3 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 2560 16640 1 0 -1162086362
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 2560 16896 1 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 2560 17408 1 0 -1162086307
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 2560 20992 1 0 -1162086279
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 2560 22528 1 0 -1162086308
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 2560 24064 1 0 -1162086305
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 2560 24320 1 0 -1162086307
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 2560 24832 1 0 -1162086279
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 2560 25856 1 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 2560 26880 1 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 2560 30208 1 0 -1162086307
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 2560 30976 1 0 0
+5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 2560 32000 1 0 0
diff --git a/exllamav3/model/dense_warmup.py b/exllamav3/model/dense_warmup.py
index 7265303..a87cf72 100644
--- a/exllamav3/model/dense_warmup.py
+++ b/exllamav3/model/dense_warmup.py
@@ -24,6 +24,29 @@ def _dense_linears(model):
return list(seen.values())
+def seed_dense_tune(seed=None, path=None) -> int:
+ """Append the shipped tuned solutions (dense_gemm_tune_seed.txt: Qwen shapes at row classes 4352..8192, the classes
+ a merged last prefill chunk reaches) to the dense-GEMM tune file for the keys it does not hold yet. Call before the first
+ dense GEMM of the process (the C++ tuner reads the file once). Returns the number of lines added."""
+ from pathlib import Path
+ seed = Path(seed) if seed else Path(__file__).with_name("dense_gemm_tune_seed.txt")
+ if not seed.exists():
+ return 0
+ if path is None:
+ path = os.environ.get("EXL3_DENSE_GEMM_TUNE_FILE") or os.path.join(os.environ.get("HOME", "/tmp"), ".cache/exllamav3/dense_gemm_tune.txt")
+ path = Path(path)
+ key = lambda ln: tuple(ln.split()[:6])
+ have = set()
+ if path.exists():
+ have = {key(l) for l in path.read_text().splitlines() if len(l.split()) == 7}
+ new = [l for l in seed.read_text().splitlines() if len(l.split()) == 7 and key(l) not in have]
+ if new:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with open(path, "a") as f:
+ f.write("\n".join(new) + "\n")
+ return len(new)
+
+
@torch.inference_mode()
def warm_dense_gemm(models, max_rows: int = 4096, log=print) -> dict:
"""models: iterable of Model (target, draft). max_rows: largest prefill chunk in tokens. Returns stats."""
diff --git a/exllamav3/modules/attention_fn/bc_attn.py b/exllamav3/modules/attention_fn/bc_attn.py
index e1a1578..a9a1f76 100644
--- a/exllamav3/modules/attention_fn/bc_attn.py
+++ b/exllamav3/modules/attention_fn/bc_attn.py
@@ -716,6 +716,18 @@ def build_bc_attn(module, layer):
layer.raw_k.device == torch.device(m.device)
))
):
+ if _bc_trace:
+ print(" -- BC-attn why2:", dict(en=bc_attn_enable, qsa=bool(_qsa_module_eligible(m)),
+ q=getattr(m.q_proj, "quant_type", None), qbc=getattr(getattr(m.q_proj, "inner", None), "bc", None) is not None,
+ o=getattr(m.o_proj, "quant_type", None), obc=getattr(getattr(m.o_proj, "inner", None), "bc", None) is not None,
+ k=getattr(m.k_proj, "quant_type", None), kbc=getattr(getattr(m.k_proj, "inner", None), "bc", None) is not None,
+ mkv=m.multi_kv is not None, vd=getattr(m, "v_head_dim", None), hd=m.head_dim,
+ gate=(m.headwise_gate, m.full_gate, getattr(m, "interleaved_gate", False)),
+ qn=type(m.q_norm).__name__, kn=type(getattr(m, "k_norm", None)).__name__, vn=type(m.v_norm).__name__))
+ print(f" -- BC-attn why: module_eligible={bool(_module_eligible(m))} layer={type(layer).__name__}"
+ f" compand={getattr(layer, 'compand_a', None)} qk_dev={getattr(getattr(layer, 'qk', None), 'device', None)}"
+ f" k_dev={getattr(getattr(layer, 'k', None), 'device', None)} m_dev={m.device}"
+ f" raw_k_dev={getattr(getattr(layer, 'raw_k', None), 'device', None)}")
_trace_build(m, None, "attn")
return None
if isinstance(layer, CacheLayer_quant):
diff --git a/exllamav3/modules/attention_fn/qdeq_triton.py b/exllamav3/modules/attention_fn/qdeq_triton.py
new file mode 100644
index 0000000..49d7532
--- /dev/null
+++ b/exllamav3/modules/attention_fn/qdeq_triton.py
@@ -0,0 +1,144 @@
+"""8-bit paged cache -> rotated-domain fp16 staging for the HIP sparse prefill kernel.
+Packed 8-bit cache: per 32-value group 32 offset-binary codes (four per int32 word, low byte first) + one fp16 scale; the stored
+values are in the H32-rotated domain. Staged values d' = (code - 127.5) * (scale / 128), so the true K/V of a group is H_n d' with
+H_n = H32 / sqrt(32) (symmetric, orthonormal): q . k = (H_n q) . d' and sum p v = H_n (sum p d'). The caller rotates q before and
+un-rotates the output after the unchanged fp16 HIP kernel. Pages are staged into a compact buffer in block-table order."""
+import os
+import torch
+import triton
+import triton.language as tl
+from .qwrite_triton import _h32_stage
+
+TB = 8 # tokens per program (256 % TB == 0)
+
+
+def _deq8_kernel(qk, sk, qv, sv, ok, ov, btable, P, TBc: tl.constexpr):
+ j = tl.program_id(0)
+ tb = tl.program_id(1)
+ page = tl.minimum(tl.maximum(tl.load(btable + j), 0), P - 1).to(tl.int64)
+ tok = (tb * TBc + tl.arange(0, TBc))[:, None].to(tl.int64)
+ offs = tl.arange(0, 512)[None, :]
+ src = (page * 256 + tok) * 512 + offs
+ sidx = (page * 256 + tok) * 16 + offs // 32
+ dst = (j.to(tl.int64) * 256 + tok) * 512 + offs
+ ck = tl.load(qk + src).to(tl.float32)
+ ak = (ck - 127.5) * (tl.load(sk + sidx).to(tl.float32) / 128.0)
+ tl.store(ok + dst, ak.to(tl.float16))
+ cv = tl.load(qv + src).to(tl.float32)
+ av = (cv - 127.5) * (tl.load(sv + sidx).to(tl.float32) / 128.0)
+ tl.store(ov + dst, av.to(tl.float16))
+
+
+def dequant8_pages(qk, sk, qv, sv, pages, out_k, out_v):
+ """qk/qv: (P, 256, 128) int32, sk/sv: (P, 256, 16) fp16 (2 kv heads x 256 dims), pages: (n,) int32 block-table slice,
+ out_k/out_v: (>= n*256, 2, 256) fp16 contiguous."""
+ P = qk.shape[0]
+ n = pages.shape[0]
+ assert qk.shape[1:] == (256, 128) and sk.shape[1:] == (256, 16) and qv.shape == qk.shape and sv.shape == sk.shape
+ assert out_k.shape[0] >= n * 256 and out_k.shape[1:] == (2, 256) and out_v.shape == out_k.shape
+ assert pages.dtype == torch.int32 and pages.is_contiguous() and out_k.is_contiguous() and out_v.is_contiguous()
+ _deq8_kernel[(n, 256 // TB)](qk.view(torch.uint8), sk, qv.view(torch.uint8), sv, out_k, out_v, pages, P, TBc=TB, num_warps=4)
+
+
+def _deqfull8_kernel(qk, sk, qv, sv, ok, ov, btable, P, TBc: tl.constexpr, G: tl.constexpr):
+ """True fp16 dequantisation (H32 un-rotation included), same float32 operation order as ext_fallbacks.dequant_cache_cont:
+ (code - 127.5) * ((scale * r32) / 128), unnormalised butterfly, one rounding to fp16."""
+ j = tl.program_id(0)
+ tb = tl.program_id(1)
+ page = tl.minimum(tl.maximum(tl.load(btable + j), 0), P - 1).to(tl.int64)
+ tok = (tb * TBc + tl.arange(0, TBc))[:, None, None].to(tl.int64)
+ grp = tl.arange(0, G)[None, :, None]
+ lane = tl.arange(0, 32)[None, None, :]
+ src = ((page * 256 + tok) * G + grp) * 32 + lane
+ sidx = (page * 256 + tok) * G + grp
+ dst = ((j.to(tl.int64) * 256 + tok) * G + grp) * 32 + lane
+ for which in tl.static_range(2):
+ if which == 0:
+ c = tl.load(qk + src).to(tl.float32)
+ sc = tl.load(sk + sidx).to(tl.float32)
+ else:
+ c = tl.load(qv + src).to(tl.float32)
+ sc = tl.load(sv + sidx).to(tl.float32)
+ x = (c - 127.5) * ((sc * 0.17677669529663688) / 128.0)
+ x = tl.reshape(x, (TBc * G, 32))
+ x = _h32_stage(x, TBc * G, 1)
+ x = _h32_stage(x, TBc * G, 2)
+ x = _h32_stage(x, TBc * G, 4)
+ x = _h32_stage(x, TBc * G, 8)
+ x = _h32_stage(x, TBc * G, 16)
+ x = tl.reshape(x, (TBc, G, 32)).to(tl.float16)
+ if which == 0:
+ tl.store(ok + dst, x)
+ else:
+ tl.store(ov + dst, x)
+
+
+def dequant8_full(qk, sk, qv, sv, pages, out_k, out_v):
+ """qk/qv (P, 256, G*8) int32, sk/sv (P, 256, G) fp16, pages (n,) int32 -> out_k/out_v (>= n*256 tokens, G*32) fp16 holding true K/V
+ (any trailing shape with G*32 values per token), compact in `pages` order."""
+ P, G = qk.shape[0], sk.shape[-1]
+ n = pages.shape[0]
+ assert qk.shape[1:] == (256, G * 8) and sk.shape[1:] == (256, G) and qv.shape == qk.shape and sv.shape == sk.shape and G & (G - 1) == 0
+ assert pages.dtype == torch.int32 and pages.is_contiguous() and out_k.is_contiguous() and out_v.is_contiguous()
+ assert out_k.numel() >= n * 256 * G * 32 and out_v.numel() >= n * 256 * G * 32 and out_k.dtype == out_v.dtype == torch.half
+ _deqfull8_kernel[(n, 256 // 4)](qk.view(torch.uint8), sk, qv.view(torch.uint8), sv, out_k, out_v, pages, P, TBc=4, G=G, num_warps=4)
+
+
+def _rot32_kernel(x, y, n, BG: tl.constexpr):
+ row = (tl.program_id(0).to(tl.int64) * BG + tl.arange(0, BG))[:, None]
+ offs = row * 32 + tl.arange(0, 32)[None, :]
+ m = row < n
+ v = tl.load(x + offs, mask=m, other=0.0).to(tl.float32)
+ v = _h32_stage(v, BG, 1)
+ v = _h32_stage(v, BG, 2)
+ v = _h32_stage(v, BG, 4)
+ v = _h32_stage(v, BG, 8)
+ v = _h32_stage(v, BG, 16)
+ tl.store(y + offs, (v * 0.17677669529663688).to(tl.float16), mask=m)
+
+
+def rot32(x, out = None):
+ """x (..., 32k) fp16 contiguous -> H32/sqrt(32) applied to every group of 32 (fp32 butterfly, one rounding to fp16). Self-inverse."""
+ assert x.dtype == torch.half and x.is_contiguous() and x.numel() % 32 == 0
+ out = torch.empty_like(x) if out is None else out
+ n = x.numel() // 32
+ BG = 64
+ _rot32_kernel[((n + BG - 1) // BG,)](x, out, n, BG=BG, num_warps=4)
+ return out
+
+
+_STAGE = {}
+
+
+def _h32_f32(dev):
+ h = torch.ones(1, 1, dtype = torch.float32)
+ while h.shape[0] < 32:
+ h = torch.cat([torch.cat([h, h], 1), torch.cat([h, -h], 1)], 0)
+ return (h / 32 ** 0.5).to(dev).contiguous()
+
+
+def qsa_prefill_q8(q_rows, qk, sk, qv, sv, indices, sm_scale, block_table, n_used, page_size = 256):
+ """Sparse prefill attention over an 8-bit paged cache through the fp16 HIP kernel (same call shape as qsa_prefill_hip).
+ q_rows (R, 24, 256) fp16, block_table (>= n_used,) int32 logical page -> cache page. Returns (R, 24, 256) fp16."""
+ from .qsa_prefill_hip import qsa_prefill_hip
+ dev = q_rows.device
+ st = _STAGE.get(dev)
+ if st is None or st["k"].shape[0] < n_used * page_size:
+ cap = max(n_used * page_size, 2 * (st["k"].shape[0] if st else 0))
+ st = _STAGE[dev] = dict(
+ k = torch.empty((cap, 2, 256), dtype = torch.half, device = dev),
+ v = torch.empty((cap, 2, 256), dtype = torch.half, device = dev),
+ ids = torch.arange(cap // page_size, dtype = torch.int32, device = dev),
+ h = _h32_f32(dev))
+ if os.environ.get("EXL3_QSA_Q8_STAGE", "full") == "full":
+ # true fp16 K/V (un-rotation inside the staging kernel), unrotated q, no output rotation
+ dequant8_full(qk, sk, qv, sv, block_table[:n_used].int().contiguous(), st["k"], st["v"])
+ return qsa_prefill_hip(q_rows, st["k"][: n_used * page_size], st["v"][: n_used * page_size], indices, sm_scale, st["ids"][:n_used], page_size)
+ dequant8_pages(qk, sk, qv, sv, block_table[:n_used].int().contiguous(), st["k"], st["v"])
+ tri = os.environ.get("EXL3_QSA_Q8_ROT", "triton") == "triton"
+ qr = rot32(q_rows.contiguous()) if tri else torch.matmul(q_rows.float().view(-1, 32), st["h"]).half().view(q_rows.shape)
+ o = qsa_prefill_hip(qr, st["k"][: n_used * page_size], st["v"][: n_used * page_size], indices, sm_scale, st["ids"][:n_used], page_size)
+ return rot32(o) if tri else torch.matmul(o.float().view(-1, 32), st["h"]).half().view(o.shape)
diff --git a/exllamav3/modules/attention_fn/qwrite_triton.py b/exllamav3/modules/attention_fn/qwrite_triton.py
new file mode 100644
index 0000000..92cbc41
--- /dev/null
+++ b/exllamav3/modules/attention_fn/qwrite_triton.py
@@ -0,0 +1,70 @@
+"""Native (Triton) 8-bit paged cache writer. Replaces the PyTorch fallback of ext.quant_cache_paged on ROCm
+(cache/q_cache.cu is not part of the ROCm build): same format, same float32 operation order
+(unnormalised H32 butterfly, * 1/sqrt(32), scale = absmax + 1e-10, codes = floor(v/scale*128 + 128),
+four codes per int32 word, low byte first), one launch for K and V instead of ~70 torch launches."""
+import torch
+import triton
+import triton.language as tl
+
+
+def _h32_stage(x, G: tl.constexpr, W: tl.constexpr):
+ N: tl.constexpr = 16 // W
+ y = tl.reshape(x, (G, N, 2, W))
+ y = tl.permute(y, (0, 1, 3, 2))
+ lo, hi = tl.split(y)
+ y = tl.join(lo + hi, lo - hi)
+ y = tl.permute(y, (0, 1, 3, 2))
+ return tl.reshape(y, (G, 32))
+
+
+def _quant_row8(inp, out, sc, src, dst, G: tl.constexpr):
+ og = tl.arange(0, G)[:, None]
+ oi = tl.arange(0, 32)[None, :]
+ x = tl.load(inp + src * (G * 32) + og * 32 + oi).to(tl.float32)
+ x = _h32_stage(x, G, 1)
+ x = _h32_stage(x, G, 2)
+ x = _h32_stage(x, G, 4)
+ x = _h32_stage(x, G, 8)
+ x = _h32_stage(x, G, 16)
+ x = x * 0.17677669529663688
+ s = tl.max(tl.abs(x), axis=1) + 1.0e-10
+ inv = tl.math.div_rn(tl.full((G,), 1.0, tl.float32), s)
+ v = x * inv[:, None]
+ c = tl.floor(v * 128.0 + 128.0)
+ c = tl.minimum(tl.maximum(c, 0.0), 255.0).to(tl.int32)
+ c = tl.reshape(c, (G, 8, 4))
+ sh = (tl.arange(0, 4) * 8)[None, None, :]
+ words = tl.sum(c << sh, axis=2)
+ ow = tl.arange(0, 8)[None, :]
+ tl.store(out + dst * (G * 8) + og * 8 + ow, words)
+ tl.store(sc + dst * G + tl.arange(0, G), s.to(tl.float16))
+
+
+def _quant_cache_paged8_kernel(
+ k_in, v_in, k_out, v_out, k_sc, v_sc, seqlens, btable,
+ seq_len, pages_per_seq, in_contig: tl.constexpr, G: tl.constexpr,
+):
+ row = tl.program_id(0)
+ b = row // seq_len
+ t = row % seq_len
+ tok = tl.load(seqlens + b) + t
+ page = tl.load(btable + b * pages_per_seq + tok // 256)
+ dst = page.to(tl.int64) * 256 + tok % 256
+ if in_contig:
+ src = row.to(tl.int64)
+ else:
+ src = dst
+ _quant_row8(k_in, k_out, k_sc, src, dst, G)
+ _quant_row8(v_in, v_out, v_sc, src, dst, G)
+
+
+def quant_cache_paged8(k_in, k_out, k_sc, v_in, v_out, v_sc, cache_seqlens, block_table, seq_len, in_contiguous):
+ dim = k_sc.shape[-1] * 32
+ G = dim // 32
+ bsz = block_table.shape[0]
+ _quant_cache_paged8_kernel[(bsz * seq_len,)](
+ k_in, v_in, k_out, v_out, k_sc, v_sc, cache_seqlens, block_table,
+ seq_len, block_table.shape[1], in_contig=bool(in_contiguous), G=G, num_warps=1)
diff --git a/exllamav3/modules/block_sparse_mlp.py b/exllamav3/modules/block_sparse_mlp.py
index 1dd31ae..0ca8800 100644
--- a/exllamav3/modules/block_sparse_mlp.py
+++ b/exllamav3/modules/block_sparse_mlp.py
@@ -115,6 +115,43 @@ def _scatter_expert_count(flat_expert_local: torch.Tensor, num_bins: int) -> tor
return expert_count
+# EXL3_MOE_ALIGN_CHUNK (default 4096, 0 = off): a prefill chunk of more than this many rows runs the grouped
+# expert GEMM as ONE launch whose per-expert row lists are laid out exactly like the chunk-by-chunk path:
+# every (expert, sub-chunk) segment starts on an even row (the GEMM result of a row depends on its row parity
+# inside the expert list), so the output is bit-identical to running the sub-chunks one after the other.
+_MOE_ALIGN_CHUNK = int(os.environ.get("EXL3_MOE_ALIGN_CHUNK", "4096"))
+
+
+def _aligned_expert_layout(flat: torch.Tensor, num_tokens: int, top_k: int, num_experts: int, chunk: int):
+ """flat: (num_tokens * top_k) int64 expert ids, slot = token * top_k + k. Returns (order, sel_flat, dummy_tokens):
+ order lists the assignment slots grouped by expert, each (expert, chunk of `chunk` tokens) segment in slot order
+ and padded to an even length with dummy slots; sel_flat is the expert id of every slot including the dummy ones
+ (slots >= num_tokens * top_k belong to dummy tokens num_tokens .. num_tokens + dummy_tokens - 1). No host sync."""
+ dev = flat.device
+ a0 = num_tokens * top_k
+ nc = (num_tokens + chunk - 1) // chunk
+ nseg = num_experts * nc
+ dummy_tokens = (nseg + top_k - 1) // top_k
+ total = a0 + dummy_tokens * top_k
+ key = flat * nc + torch.arange(a0, device = dev) // (top_k * chunk)
+ srt = key.argsort(stable = True)
+ kc = torch.bincount(key, minlength = nseg)
+ odd = kc & 1
+ padbefore = torch.cumsum(odd, 0) - odd
+ pos = torch.arange(a0, device = dev) + padbefore[key[srt]]
+ pad_pos = torch.cumsum(kc, 0) + padbefore
+ pad_pos = torch.where(odd == 1, pad_pos, torch.full_like(pad_pos, total))
+ pad_slot = a0 + padbefore
+ order = torch.arange(total + 1, device = dev)
+ order[pos] = srt
+ order[pad_pos] = pad_slot
+ sel_flat = torch.full((total + 1,), num_experts - 1, dtype = flat.dtype, device = dev)
+ sel_flat[:a0] = flat
+ sel_flat[torch.where(odd == 1, pad_slot, torch.full_like(pad_slot, total))] = \
+ torch.arange(nseg, device = dev) // nc
+ return order[:total], sel_flat[:total], dummy_tokens
+
+
@dataclass
class FusedBuffers:
temp_state_g: torch.Tensor
@@ -1675,22 +1712,30 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
# (fp16 weights rounded here were half the KLD gap vs the per-expert path)
rw = routing_weights.float().contiguous()
flat = sel.view(-1)
- order = flat.argsort(stable = True)
+ dummy = 0
+ y_k, rw_k, sel_k = y, rw, sel
+ if _MOE_ALIGN_CHUNK and num_tokens > _MOE_ALIGN_CHUNK:
+ order, flat, dummy = _aligned_expert_layout(flat, num_tokens, top_k, self.num_experts, _MOE_ALIGN_CHUNK)
+ y_k = torch.cat((y, torch.zeros((dummy, y.shape[1]), dtype = y.dtype, device = y.device)))
+ rw_k = torch.cat((rw, torch.zeros((dummy, top_k), dtype = rw.dtype, device = rw.device)))
+ sel_k = flat.view(num_tokens + dummy, top_k)
+ else:
+ order = flat.argsort(stable = True)
if _moe_sync_free_count():
expert_count = _scatter_expert_count(flat, self.num_experts + 1)
else:
expert_count = torch.bincount(flat, minlength = self.num_experts + 1)
if _HIP_WMMA_STATS is not None:
_HIP_WMMA_STATS.append((self.key, expert_count[:self.num_experts].cpu()))
- ws = _hip_wmma_workspace(self.device, num_tokens * top_k, self.hidden_size,
+ assignments = (num_tokens + dummy) * top_k
+ ws = _hip_wmma_workspace(self.device, assignments, self.hidden_size,
self.intermediate_size_padded, self.num_experts)
- assignments = num_tokens * top_k
- output = torch.empty((num_tokens, self.hidden_size), dtype = torch.float, device = y.device)
+ output = torch.empty((num_tokens + dummy, self.hidden_size), dtype = torch.float, device = y.device)
gu_had = ws["gu_had"][:2 * assignments * self.hidden_size].view(2 * assignments, self.hidden_size)
# down_out aliases gu_had: the gate/up input is dead once the gate/up GEMM has run
down_out = ws["gu_had"][:2 * assignments * self.hidden_size].view(torch.float).view(assignments, self.hidden_size)
ext.exl3_moe_prefill_wmma(
- y, output, sel, rw, order, expert_count,
+ y_k, output, sel_k, rw_k, order, expert_count,
self.multi_gate.ptrs_trellis, self.multi_gate.ptrs_suh, self.multi_gate.ptrs_svh,
self.multi_up.ptrs_trellis, self.multi_up.ptrs_suh, self.multi_up.ptrs_svh,
self.multi_down.ptrs_trellis, self.multi_down.ptrs_suh, self.multi_down.ptrs_svh,
@@ -1701,7 +1746,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
ws["offsets"], ws["inverse"][:assignments], ws["tiles"], ws["tile_count"],
float(self.act_limit), bool(self.wmma_mcg),
)
- final_hidden_states = output.view(eshape)
+ final_hidden_states = output[:num_tokens].view(eshape)
# Torch/C++/fused path
elif (
diff --git a/exllamav3/modules/gated_delta_net.py b/exllamav3/modules/gated_delta_net.py
index 34a0808..4fda754 100644
--- a/exllamav3/modules/gated_delta_net.py
+++ b/exllamav3/modules/gated_delta_net.py
@@ -1268,7 +1268,11 @@ class GatedDeltaNet(Module):
"""EXL3_MIDCHUNK_CKPT=2: one unsplit call; the HIP KDA kernel side-writes S at the checkpoint row, conv state
there = the last cdim pre-conv inputs (bf16). Single row, rows % 64 == 0 only. Returns the ckpt dict or None."""
rows = params.get("checkpoint_rows")
- if not rows or params.get("midchunk_mode") != 2 or not self.kda or bsz != 1 or not save_state or save_history:
+ if not rows or params.get("midchunk_mode") != 2 or bsz != 1 or not save_state or save_history:
+ return None
+ # GDN (not KDA): only the fused HIP chain (EXL3_GDN_FUSE=1 + EXL3_GDN_PF=1, chunk path) side-writes the state
+ if not self.kda and (os.environ.get("EXL3_GDN_FUSE", "0") != "1" or os.environ.get("EXL3_GDN_PF", "1") != "1"
+ or seqlen < self.num_v_heads):
return None
rows = sorted(set(int(r) for r in rows))
cdim = self.conv_kernel_size
diff --git a/exllamav3/modules/gated_delta_net_fn/gated_delta_rule.py b/exllamav3/modules/gated_delta_net_fn/gated_delta_rule.py
index 83476fd..6e594d3 100644
--- a/exllamav3/modules/gated_delta_net_fn/gated_delta_rule.py
+++ b/exllamav3/modules/gated_delta_net_fn/gated_delta_rule.py
@@ -201,7 +201,8 @@ def gated_delta_rule_fn(
if pf:
core_attn, new_state = chunk_gated_delta_rule_pf(
q[i:i + 1], k[i:i + 1], v[i:i + 1], g = g[i:i + 1], beta = beta[i:i + 1],
- initial_state = state, output_final_state = save_state)
+ initial_state = state, output_final_state = save_state,
+ ckpt = params.get("kda_ckpt") if bsz == 1 else None)
else:
core_attn, new_state = chunk_gated_delta_rule(
q[i:i + 1], k[i:i + 1], v[i:i + 1],
diff --git a/exllamav3/modules/moe_fused.py b/exllamav3/modules/moe_fused.py
index 7646cd4..d49a41e 100644
--- a/exllamav3/modules/moe_fused.py
+++ b/exllamav3/modules/moe_fused.py
@@ -19,9 +19,10 @@ from .hyperconnections import HyperConnection
MAX_ROWS = 4
-# EXL3_MOE_FUSED9=<variant>: 0 off, 393216 (0x60000) = forced-inline phases + two blocks per WGP (core9), 917504 = same kernel, ONE block per WGP:
-# the grid barrier needs every block resident, and two 512-thread blocks fill a WGP's VGPR file exactly, so a desktop client on the same GPU can leave half the grid unscheduled. Runtime-mutable for one-load A/B.
-MF9 = {"variant": int(os.environ.get("EXL3_MOE_FUSED9", "917504"), 0), "timing": 0, # timing 1 = phase stamps into seldbg (tests)
+# EXL3_MOE_FUSED9=<variant>: 0 off, 393216 (0x60000) = forced-inline phases + two blocks per WGP (core9), 917504 = same kernel, ONE block per WGP, 1441792 (0x160000, default) = same phases and block partition as 0x60000, but every grid barrier is a kernel boundary (six stage launches):
+# no block waits for another, so a desktop client on the GPU cannot stall it or change the output; 0.58 ms/token faster than 917504. 393216 / 917504 keep the barrier kernels.
+# The barrier kernels need every block resident, and two 512-thread blocks fill a WGP's VGPR file exactly, so a desktop client on the same GPU can leave half the grid unscheduled. Runtime-mutable for one-load A/B.
+MF9 = {"variant": int(os.environ.get("EXL3_MOE_FUSED9", "1441792"), 0), "timing": 0, # timing 1 = phase stamps into seldbg (tests)
# ballot top-k in the expert selection (variant bit 0x1000), bit-identical to the plain loop; EXL3_MOE_TK2=0 turns it off
"tk2": os.environ.get("EXL3_MOE_TK2", "1") not in ("", "0")}
diff --git a/exllamav3/modules/ple.py b/exllamav3/modules/ple.py
index 68fc083..125b46a 100644
--- a/exllamav3/modules/ple.py
+++ b/exllamav3/modules/ple.py
@@ -435,6 +435,21 @@ class PLELayer(Module):
else:
conv_state[s, :, :win].copy_(conv_stream[i, :, -win:])
id_state[s, :ctx].copy_(history[i, -ctx:])
+ # EXL3_PF_NO_TAIL: the state after row r of this chunk (what stash() would hold if the forward had ended there) =
+ # conv columns [r, r + win) of the full conv stream and ids [r, r + ctx) of the history; the job stashes them
+ # (Job.stash_midchunk, 3-tuple form: pinned host copy + event)
+ rows = params.get("checkpoint_rows")
+ if rows and params.get("midchunk_mode") == 2 and not save_history and bsz == 1 and len(slots) == 1:
+ saved = params.setdefault("midchunk_states", {})
+ layer_instance = (self.layer_idx, params.get("layer_instance", 0))
+ for r in rows:
+ if not 0 < r < seq:
+ continue
+ hs = torch.empty((conv_stream.shape[1], win), dtype = conv_stream.dtype, pin_memory = True)
+ hs.copy_(conv_stream[0, :, r:r + win], non_blocking = True)
+ ev = torch.cuda.Event()
+ ev.record()
+ saved.setdefault(r, {})[layer_instance] = (hs, history[0, r:r + ctx].clone(), ev)
else:
delta, _ = self.forward_streams(x, history, params)
if os.environ.get("EXL3_PFE_PLE", "1") != "0":
diff --git a/exllamav3/modules/qsa_indexer.py b/exllamav3/modules/qsa_indexer.py
index 537a1bb..ec7a497 100644
--- a/exllamav3/modules/qsa_indexer.py
+++ b/exllamav3/modules/qsa_indexer.py
@@ -727,6 +727,15 @@ class QSAIndexer(Module):
from .attention_fn.qsa_prefill_hip import qsa_prefill_hip
o = qsa_prefill_hip(q_rows, k_arg, v_arg, indices, attn.sm_scale, block_table[0].int().contiguous(), page_size)
return o.view(bsz, seq, attn.num_q_heads, attn.head_dim)
+ if (os.environ.get("EXL3_QSA_PF_HIP", "1") == "1" and os.environ.get("EXL3_QSA_PF_DEQ", "1") == "1" and qc is not None
+ and qc[2] == 8 and qc[3] == 8 and bsz == 1 and seq >= 64 and seq <= 4096 * 4
+ and (attn.num_q_heads, attn.num_kv_heads, attn.head_dim, page_size, indices.shape[1]) == (24, 2, 256, 256, 2080)
+ and q_rows.dtype == torch.half and _pf_hip_ready()):
+ # stage the used pages as rotated-domain fp16 (one elementwise pass), run the proven fp16 HIP kernel on q rotated by H32/sqrt(32), rotate the output back
+ from .attention_fn.qdeq_triton import qsa_prefill_q8
+ n_used = (int(cache_seqlens_cpu.max().item()) + seq + page_size - 1) // page_size
+ o = qsa_prefill_q8(q_rows, qk, sk, qv, sv, indices, attn.sm_scale, block_table[0], n_used, page_size)
+ return o.view(bsz, seq, attn.num_q_heads, attn.head_dim)
o = qsa_sparse_attend_rows(
q_rows,
k_arg, v_arg, indices, attn.sm_scale,
diff --git a/exllamav3/vendor/fla/__init__.py b/exllamav3/vendor/fla/__init__.py
index 6b68e9e..d71590f 100644
--- a/exllamav3/vendor/fla/__init__.py
+++ b/exllamav3/vendor/fla/__init__.py
@@ -88,7 +88,7 @@ def chunk_gated_delta_rule(
return o.to(q.dtype), final_state
-def chunk_gated_delta_rule_pf(q, k, v, g, beta, scale=None, initial_state=None, output_final_state=False):
+def chunk_gated_delta_rule_pf(q, k, v, g, beta, scale=None, initial_state=None, output_final_state=False, ckpt=None):
"""chunk_gated_delta_rule(use_qk_l2norm_in_kernel=True, chunk_size=64) for q, k, v given as (possibly strided) views of the conv
output; g (fp32) and beta (bf16) contiguous. Bitwise equal to the guarded entry; no copies of q, k, v when the views are plain
token-pitch slices."""
@@ -107,7 +107,7 @@ def chunk_gated_delta_rule_pf(q, k, v, g, beta, scale=None, initial_state=None,
g = chunk_local_cumsum(g, chunk_size = chunk_size, scale = RCP_LN2)
if os.environ.get("EXL3_GDN_FUSE", "0") == "1":
from .gdn_fused import chunk_gdn_fused
- res = chunk_gdn_fused(qn, kn, v, g, beta, scale, initial_state, output_final_state, chunk_size)
+ res = chunk_gdn_fused(qn, kn, v, g, beta, scale, initial_state, output_final_state, chunk_size, ckpt = ckpt)
if res is not None:
return res[0].to(qn.dtype), res[1]
v = v.contiguous()
diff --git a/exllamav3/vendor/fla/gdn_fused.py b/exllamav3/vendor/fla/gdn_fused.py
index d6306c8..3b22b34 100644
--- a/exllamav3/vendor/fla/gdn_fused.py
+++ b/exllamav3/vendor/fla/gdn_fused.py
@@ -37,14 +37,14 @@ def gdn_kkt_solve(k, g, beta, chunk_size=64):
return A
-def chunk_gdn_fused(q, k, v, g, beta, scale, initial_state, output_final_state, chunk_size=64):
+def chunk_gdn_fused(q, k, v, g, beta, scale, initial_state, output_final_state, chunk_size=64, ckpt=None):
"""Returns (o, final_state) or None when the caller must run the Triton chain."""
if not gdn_fuse_ok(q, k, v, g, beta, initial_state, chunk_size):
return None
try:
from .hip.gdn_fused_h_hip import chunk_gdn_fwd_fused_hip
A = gdn_kkt_solve(k, g, beta, chunk_size)
- return chunk_gdn_fwd_fused_hip(q, k, v, g, beta, A, scale, initial_state=initial_state, output_final_state=output_final_state)
+ return chunk_gdn_fwd_fused_hip(q, k, v, g, beta, A, scale, initial_state=initial_state, output_final_state=output_final_state, ckpt=ckpt)
except Exception:
_FAIL.append(1)
return None
diff --git a/exllamav3/vendor/fla/hip/gdn_fused_h.hip b/exllamav3/vendor/fla/hip/gdn_fused_h.hip
index c781f65..fd427aa 100644
--- a/exllamav3/vendor/fla/hip/gdn_fused_h.hip
+++ b/exllamav3/vendor/fla/hip/gdn_fused_h.hip
@@ -47,6 +47,9 @@ typedef uint32_t v8u __attribute__((ext_vector_type(8)));
#ifndef OST
#define OST 0 // 1: o tile staged through LDS (sW) and written as 16 B vectors, full 256 B rows (same bits; replaces 2 B stores of 32 B row pieces)
#endif
+#ifndef CKPT
+#define CKPT 0 // 1: two extra kernel arguments (hc, ckpt_chunk, hc2, ckpt_chunk2): the state after a given chunk is also written to hc / hc2 (same bits as ht would hold there)
+#endif
#ifndef PF1
#define PF1 0 // 1: phase 1 writes its LDS tiles directly after a barrier at the top of the chunk (no register staging across a barrier; same bits)
#endif
@@ -133,7 +136,11 @@ extern "C" __global__ __launch_bounds__(256) void gdn_fused_h_o(
const uint16_t* __restrict__ q, const uint16_t* __restrict__ k, const uint16_t* __restrict__ v,
const float* __restrict__ g, const uint16_t* __restrict__ beta, const uint16_t* __restrict__ A,
uint16_t* __restrict__ o, const float* __restrict__ h0, float* __restrict__ ht, float scale, int T, int H, int HV, int PV,
- uint16_t* __restrict__ dw, uint16_t* __restrict__ du, uint16_t* __restrict__ dvn, uint16_t* __restrict__ dh)
+ uint16_t* __restrict__ dw, uint16_t* __restrict__ du, uint16_t* __restrict__ dvn, uint16_t* __restrict__ dh
+#if CKPT
+ , float* __restrict__ hc, int ckpt_chunk, float* __restrict__ hc2, int ckpt_chunk2
+#endif
+ )
{
__shared__ __attribute__((aligned(16))) uint16_t sW[BT * LDR]; // w [token][kdim]
__shared__ __attribute__((aligned(16))) uint16_t sX[KD * LDT]; // kb^T [kdim][token], then q [token][kdim]
@@ -491,6 +498,21 @@ extern "C" __global__ __launch_bounds__(256) void gdn_fused_h_o(
if (!(ABL & 16)) h[kt] = wmma(ld16(sY, 16 * kt + ll, LDT, 16 * j), vg[j], h[kt]);
SBAR(2);
}
+#if CKPT
+ // mid-chunk checkpoints (EXL3_PF_NO_TAIL): the state after chunk ckpt_chunk - 1 (= row 64 * ckpt_chunk), layout of ht
+ if (hc && i_t + 1 == ckpt_chunk)
+ #pragma unroll
+ for (int kt = 0; kt < 8; ++kt)
+ #pragma unroll
+ for (int r = 0; r < 8; ++r)
+ hc[IX_S(i_nh, 16 * kt + 2 * r + half, col)] = h[kt][r];
+ if (hc2 && i_t + 1 == ckpt_chunk2)
+ #pragma unroll
+ for (int kt = 0; kt < 8; ++kt)
+ #pragma unroll
+ for (int r = 0; r < 8; ++r)
+ hc2[IX_S(i_nh, 16 * kt + 2 * r + half, col)] = h[kt][r];
+#endif
}
if (ABL & 256) { if (sink == 0x9e3779b9u && tid == 0) o[0] = 0; } // keeps the ablated o path alive
diff --git a/exllamav3/vendor/fla/hip/gdn_fused_h_hip.py b/exllamav3/vendor/fla/hip/gdn_fused_h_hip.py
index 672ac72..f8fbad3 100644
--- a/exllamav3/vendor/fla/hip/gdn_fused_h_hip.py
+++ b/exllamav3/vendor/fla/hip/gdn_fused_h_hip.py
@@ -56,10 +56,12 @@ def _load(defs=""):
return fn
-def chunk_gdn_fwd_fused_hip(q, k, v, g, beta, A, scale, initial_state=None, output_final_state=False, defs="", dbg=None, grid=None):
+def chunk_gdn_fwd_fused_hip(q, k, v, g, beta, A, scale, initial_state=None, output_final_state=False, defs="", dbg=None, grid=None, ckpt=None):
"""recompute_w_u + chunk_h + chunk_o in one kernel. q, k [B,T,H,128] bf16; v [B,T,HV,128] bf16; g [B,T,HV] fp32
(chunk-local cumsum, log2 domain); beta [B,T,HV] bf16; A [B,T,HV,64] bf16 (solved kkt). Returns (o, final_state).
- dbg: optional dict of bf16 buffers w, u, vn [T,HV,128] and h [NT,HV,128,128] (build with defs containing DBG=1)."""
+ dbg: optional dict of bf16 buffers w, u, vn [T,HV,128] and h [NT,HV,128,128] (build with defs containing DBG=1).
+ ckpt: optional dict or list of up to 2 dicts {"s": fp32 [B, HV, K, V] contiguous, "chunk": n}: the kernel (CKPT=1 build, a separate
+ code object; the default build is untouched) also writes the state after chunk n - 1 (row 64 n) to ckpt["s"] and sets ckpt["ok"]."""
B, T, H, K = k.shape
HV, V = v.shape[2], v.shape[-1]
assert K == 128 and V == 128 and HV % H == 0
@@ -73,6 +75,13 @@ def chunk_gdn_fwd_fused_hip(q, k, v, g, beta, A, scale, initial_state=None, outp
assert q.shape == k.shape and g.shape == (B, T, HV) and beta.shape == (B, T, HV) and A.shape == (B, T, HV, 64)
if not defs and os.environ.get("EXL3_GDN_OST", "1") == "1":
defs = "OST=1" # EXL3_GDN_OST: o tile staged through LDS, 16 B row stores (same bits, see gdn_fused_h.hip)
+ cks = [] if ckpt is None else (list(ckpt) if isinstance(ckpt, (list, tuple)) else [ckpt])
+ assert len(cks) <= 2
+ cks = [c for c in cks if 0 < c["chunk"] <= (T + 63) // 64]
+ for c in cks:
+ assert c["s"].dtype == torch.float32 and c["s"].is_contiguous() and c["s"].shape == (B, HV, K, V)
+ if cks:
+ defs = (defs + " CKPT=1").strip()
fn = _load(defs)
o = torch.empty(B, T, HV, V, device=v.device, dtype=v.dtype)
final_state = k.new_empty(B, HV, K, V, dtype=torch.float32) if output_final_state else None
@@ -86,6 +95,10 @@ def chunk_gdn_fwd_fused_hip(q, k, v, g, beta, A, scale, initial_state=None, outp
ctypes.c_float(scale), ctypes.c_int(T), ctypes.c_int(H), ctypes.c_int(HV), ctypes.c_int(PV)]
for n in ("w", "u", "vn", "h"):
args.append(P(d[n].data_ptr() if n in d else 0))
+ if cks:
+ for i in range(2):
+ c = cks[i] if i < len(cks) else None
+ args += [P(0 if c is None else c["s"].data_ptr()), ctypes.c_int(-1 if c is None else c["chunk"])]
params = (ctypes.c_void_p * len(args))(*[ctypes.cast(ctypes.byref(a), ctypes.c_void_p) for a in args])
stream = torch.cuda.current_stream().cuda_stream
nwg = B * HV if grid is None else int(grid) # grid < B * HV launches the first nwg heads only (timing experiments)
@@ -93,4 +106,6 @@ def chunk_gdn_fwd_fused_hip(q, k, v, g, beta, A, scale, initial_state=None, outp
r = _state["lib"].hipModuleLaunchKernel(fn, nwg, 1, 1, 256, 1, 1, 0, stream, params, None)
if r != 0:
raise RuntimeError(f"gdn_fused_h_hip: launch failed ({r})")
+ for c in cks:
+ c["ok"] = True
return o, final_state
diff --git a/tests/test_cache8_roundtrip_cpu.py b/tests/test_cache8_roundtrip_cpu.py
new file mode 100644
index 0000000..39c83eb
--- /dev/null
+++ b/tests/test_cache8_roundtrip_cpu.py
@@ -0,0 +1,17 @@
+import os, sys, torch
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "tools", "qwen", "cache8"))
+from ref8 import pack8, dequant8
+
+def _rel(x):
+ w, s = pack8(x)
+ return ((dequant8(w, s) - x.float()).pow(2).mean().sqrt() / x.float().pow(2).mean().sqrt()).item()
+
+def test_roundtrip_8bit_error():
+ g = torch.Generator().manual_seed(0)
+ assert _rel(torch.randn(512, 512, generator=g).half()) < 7e-3
+ x = torch.randn(512, 512, generator=g); x[:, ::37] *= 30
+ assert _rel(x.half()) < 7e-3
+
+def test_zero_group():
+ w, s = pack8(torch.zeros(4, 512).half())
+ assert dequant8(w, s).abs().max() < 1e-6
diff --git a/tests/test_dense_tune_seed.py b/tests/test_dense_tune_seed.py
new file mode 100644
index 0000000..4918a6d
--- /dev/null
+++ b/tests/test_dense_tune_seed.py
@@ -0,0 +1,32 @@
+import os, sys, tempfile, unittest
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
+from exllamav3.model.dense_warmup import seed_dense_tune
+
+
+class SeedDenseTune(unittest.TestCase):
+ def test_adds_missing_keys_once(self):
+ with tempfile.TemporaryDirectory() as d:
+ seed = os.path.join(d, "seed.txt")
+ tune = os.path.join(d, "sub", "tune.txt")
+ open(seed, "w").write("t|g|exact1 512 2560 4352 3 0 -5\nt|g|exact1 640 2560 4352 1 0 7\n")
+ self.assertEqual(seed_dense_tune(seed, tune), 2)
+ self.assertEqual(seed_dense_tune(seed, tune), 0)
+ open(tune, "a").write("t|g|exact1 99 99 256 1 0 0\n")
+ self.assertEqual(len(open(tune).read().splitlines()), 3)
+
+ def test_existing_key_kept(self):
+ with tempfile.TemporaryDirectory() as d:
+ seed = os.path.join(d, "seed.txt")
+ tune = os.path.join(d, "tune.txt")
+ open(seed, "w").write("t|g|exact1 512 2560 4352 3 0 -5\n")
+ open(tune, "w").write("t|g|exact1 512 2560 4352 3 0 11\n")
+ self.assertEqual(seed_dense_tune(seed, tune), 0)
+ self.assertEqual(open(tune).read().strip().split()[-1], "11")
+
+ def test_shipped_seed_parses(self):
+ for ln in open(os.path.join(os.path.dirname(__file__), "..", "exllamav3", "model", "dense_gemm_tune_seed.txt")):
+ self.assertEqual(len(ln.split()), 7)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tools/prefill/check_gdn_bounds.py b/tools/prefill/check_gdn_bounds.py
new file mode 100644
index 0000000..727d895
--- /dev/null
+++ b/tools/prefill/check_gdn_bounds.py
@@ -0,0 +1,309 @@
+"""CPU bounds proof for gdn_fused_h.hip (run BEFORE any GPU run of a kernel revision).
+Parses the kernel source itself: the IX_* / TCL macros, the guard of every global store, and every LDS access expression
+(ld16 calls, uint32 / uint16 stores into sW sX sY sA sG sGE sRS). Replays all of them over the real shapes
+(Qwen H 16, HV 48, K = V = 128, BT 64; T = 1..4097 incl. non-multiples of 64; B 1 and 2) and asserts every element
+index (plus access width and 16 B alignment of vector accesses) stays inside the tensor / LDS buffer.
+Usage: check_gdn_bounds.py <file.hip> [--mutate N] [--defs "ABL=0 ..."] (mutations 1..9 must FAIL, 16..18 with --defs "OST=1 CKPT=1" (checkpoint store index / column / batch item), 10..15 with --defs "OST=1": they model a dropped clamp, a dropped
+store guard, an LDS row-stride overflow, a bad state-store index and a bad LDS q write).
+Exit 0 = proof clean, 1 = violation found."""
+import itertools, re, sys
+import numpy as np
+
+src = open(sys.argv[1]).read()
+mut = int(sys.argv[sys.argv.index("--mutate") + 1]) if "--mutate" in sys.argv else 0
+if mut == 1:
+ src = src.replace("min((t_), (T_) - 1)", "(t_)") # drop the row clamp
+elif mut == 2:
+ src = src.replace("if (t < T) o[IX_V(bos + t, i_hv, col)]", "if (t < T + 64) o[IX_V(bos + t, i_hv, col)]")
+elif mut == 3:
+ src = src.replace("sA + ar * LDT + ac", "sA + ar * (LDT + 8) + ac")
+elif mut == 4:
+ src = src.replace("ht[IX_S(i_nh, 16 * kt + 2 * r + half, col)]", "ht[IX_S(i_nh, 16 * kt + 2 * r + half + 8, col)]")
+elif mut == 5:
+ src = src.replace("sX + (16 * tg + s) * LDR + 2 * cp)", "sX + (16 * tg + s + 4) * LDR + 2 * cp)")
+elif mut == 6:
+ src = src.replace("#define IX_VR(tc, hv, c) ((((int64_t) (tc)) * PV)", "#define IX_VR(tc, hv, c) ((((int64_t) (tc)) * (PV + 8))") # wrong v pitch
+elif mut == 7:
+ src = src.replace("uint32_t vv = *(const uint32_t*) (v + IX_VR(tc, i_hv, 2 * cp));", "uint32_t vv = *(const uint32_t*) (v + IX_VR(t, i_hv, 2 * cp));") # unclamped row
+elif mut == 8:
+ src = src.replace("#define TCL(bos_, t_, T_) ((bos_) + min((t_), (T_) - 1))", "#define TCL(bos_, t_, T_) ((bos_) + min((t_), (T_) - 1) + t)") # macro argument capturing the outer loop variable t
+elif mut == 9:
+ src = src.replace("#define IX_G(tc, hv) (((int64_t) (tc)) * HV + (hv))", "#define IX_G(tc, hv) (((int64_t) (tc)) * HV + (hv) + t0)") # macro body capturing an outer variable
+elif mut == 10:
+ src = src.replace("if (t < T) *(uint4*) (o + IX_V(bos + t, i_hv, cc)) = x;", "if (t < T + 64) *(uint4*) (o + IX_V(bos + t, i_hv, cc)) = x;") # OST: dropped row guard of the vector store
+elif mut == 11:
+ src = src.replace("const uint4 x = *(const uint4*) (sW + rr * LDR + cc);", "const uint4 x = *(const uint4*) (sW + (rr + 8) * LDR + cc);") # OST: LDS read past the tile
+elif mut == 12:
+ src = src.replace("cc = 8 * (tid & 15)", "cc = 8 * (tid & 31)") # OST: columns past the head
+elif mut == 13:
+ src = src.replace(" __syncthreads(); // every wave is done reading sW (w) before the o tile is staged into it\n", "") # OST: staging races with the vn chain reads of sW
+elif mut == 14:
+ src = src.replace(" SYNCA(64); // k^T visible\n", "") # OST: copy-out races with the staging writes
+elif mut == 15:
+ src = src.replace("sW[(16 * a + 2 * r + half) * LDR + col] = (uint16_t) f2bf(res);", "sW[(16 * a + 2 * r + half) * LDR + col + 80] = (uint16_t) f2bf(res);") # OST: staging write past the tile
+elif mut == 16:
+ src = src.replace("hc[IX_S(i_nh, 16 * kt + 2 * r + half, col)]", "hc[IX_S(i_nh, 16 * kt + 2 * r + half + 8, col)]") # CKPT: bad state-row index of the mid-chunk checkpoint store
+elif mut == 17:
+ src = src.replace("hc2[IX_S(i_nh, 16 * kt + 2 * r + half, col)]", "hc2[IX_S(i_nh, 16 * kt + 2 * r + half, col + 64)]") # CKPT: bad column of the second checkpoint store
+elif mut == 18:
+ src = src.replace("hc[IX_S(i_nh, 16 * kt + 2 * r + half, col)]", "hc[IX_S(i_nh + HV, 16 * kt + 2 * r + half, col)]") # CKPT: checkpoint written one batch item too far
+if mut:
+ print(f"[mutation {mut}] expecting a violation")
+
+fails = []
+def fail(msg):
+ if len(fails) < 12: fails.append(msg)
+
+# ---- constants and macros from the source
+consts = {}
+for m in re.finditer(r"^#define (BT|KD|VD|LDR|LDT)\s+(\d+)", src, re.M): consts[m.group(1)] = int(m.group(2))
+for k in ("BT", "KD", "VD", "LDR", "LDT"): assert k in consts, k
+BT, KD, VD, LDR, LDT = (consts[k] for k in ("BT", "KD", "VD", "LDR", "LDT"))
+macros = {}
+for m in re.finditer(r"^#define ((?:IX_\w+|TCL))\(([^)]*)\)\s+(.*)$", src, re.M):
+ name, args, body = m.group(1), [a.strip() for a in m.group(2).split(",")], re.sub(r"//.*$", "", m.group(3)).strip()
+ macros[name] = (args, body)
+def c2py(e):
+ e = e.replace("(int64_t)", "")
+ e = re.sub(r"\bmin\(", "np.minimum(", e)
+ return e
+def mcall(name, *vals, env):
+ args, body = macros[name]
+ e = c2py(body)
+ local = dict(zip(args, vals))
+ return eval(e, {"np": np, "BT": BT, "KD": KD, "VD": VD}, {**env, **local})
+
+# ---- global accesses over the real shapes
+def global_proof(B, T, H, HV, PV):
+ NT = (T + BT - 1) // BT
+ ext = {"qk": B * T * H * KD, "v": B * T * HV * VD, "vr": (B * T - 1) * PV + HV * VD, "g": B * T * HV, "A": B * T * HV * BT, "S": B * HV * KD * VD}
+ # guard of the o store, taken from the source
+ gm = re.search(r"if \(([^)]*)\) o\[IX_V\(bos \+ t, i_hv, col\)\]", src)
+ assert gm, "o store guard not found"
+ ostore_guard = c2py(gm.group(1))
+ tid = np.arange(256); cp = tid & 63; tg = tid >> 6; ar = tid >> 2; ac = 16 * (tid & 3)
+ for i_n in range(B):
+ bos = i_n * T
+ for i_hv in sorted({0, 1, HV // H - 1, HV // H, HV // 2, HV - 2, HV - 1}): # extremes of every index term (all affine in i_hv)
+ i_h = i_hv // (HV // H)
+ env = {"H": H, "HV": HV, "T": T, "bos": bos, "PV": PV}
+ i_nh = i_n * HV + i_hv
+ def chk(name, idx, width, tens, tag):
+ idx = np.asarray(idx, dtype=np.int64)
+ if idx.size and (idx.min() < 0 or (idx + width).max() > ext[tens]):
+ fail(f"{tag}: B{B} T{T} hv{i_hv}: {name} idx [{idx.min()}, {(idx + width).max()}) outside 0..{ext[tens]}")
+ for i_t in range(NT):
+ t0 = i_t * BT
+ last = min(t0 + BT, T) - 1
+ chk("g_last", mcall("IX_G", bos + last, i_hv, env=env), 1, "g", "gl")
+ tcA = mcall("TCL", bos, t0 + ar, T, env=env)
+ chk("A", mcall("IX_A", tcA, i_hv, ac, env=env), 16, "A", "A")
+ if (mcall("IX_A", tcA, i_hv, ac, env=env) % 16).any(): fail("A vector alignment")
+ for s2, e in itertools.product(range(8), range(2)):
+ t = t0 + 16 * tg + 2 * s2 + e
+ tc = mcall("TCL", bos, t, T, env=env)
+ chk("k/q", mcall("IX_QK", tc, i_h, 2 * cp, env=env), 2, "qk", "kq")
+ chk("v", mcall("IX_VR", tc, i_hv, 2 * cp, env=env), 2, "vr", "v")
+ chk("g/beta", mcall("IX_G", tc, i_hv, env=env), 1, "g", "gb")
+ t = t0 + np.arange(64)
+ tcg = mcall("TCL", bos, t, T, env=env)
+ chk("sG load", mcall("IX_G", tcg[t < T], i_hv, env=env), 1, "g", "sG")
+ # o store: rows t0 + 16a + 2r + half, cols 0..127, guarded by the source's guard
+ a, r, half, col = np.meshgrid(np.arange(4), np.arange(8), np.arange(2), np.arange(128), indexing="ij")
+ t = t0 + 16 * a + 2 * r + half
+ ok = eval(ostore_guard, {"np": np}, {"t": t, "T": T})
+ idx = mcall("IX_V", bos + t[ok], i_hv, col[ok], env=env)
+ chk("o store", idx, 1, "v", "o")
+ kt, r, half, col = np.meshgrid(np.arange(8), np.arange(8), np.arange(2), np.arange(128), indexing="ij")
+ idx = mcall("IX_S", i_nh, 16 * kt + 2 * r + half, col, env=env)
+ chk("h0/ht", idx, 1, "S", "state")
+ # the state-store expression text must be the one proven above (mutation 4 changes it)
+ for m in re.finditer(r"(?:ht|h0|hc2?)\[IX_S\(i_nh, ([^,]*), col\)\]", src):
+ kt, r, half = np.meshgrid(np.arange(8), np.arange(8), np.arange(2), indexing="ij")
+ row = eval(c2py(m.group(1)), {"np": np}, {"kt": kt, "r": r, "half": half})
+ if row.min() < 0 or row.max() >= KD: fail(f"state row expr {m.group(1)} range {row.min()}..{row.max()}")
+
+# ---- OST (o tile staged through sW, 16 B vector copy-out): bounds of the vector store and of the LDS read, and the barrier order
+OST_RAW = re.search(r"#if OST\n\s*// o tile.*?\n\s*#pragma unroll\n\s*for \(int i = 0; i < 4; \+\+i\)\n\s*\{\n\s*const int (rr = .*?), (cc = .*?), t = t0 \+ rr;\n\s*const uint4 x = \*\(const uint4\*\) \(sW \+ (.*?)\);\n\s*if \((.*?)\) \*\(uint4\*\) \(o \+ (IX_V\(.*?\))\) = x;", src, re.S)
+assert OST_RAW, "OST copy-out block not found"
+def ost_global_proof(B, T, H, HV, PV):
+ NT = (T + BT - 1) // BT
+ tid, i = np.meshgrid(np.arange(256), np.arange(4), indexing="ij")
+ rr = eval(c2py(OST_RAW.group(1).split("=", 1)[1]), {"np": np}, {"tid": tid, "i": i})
+ cc = eval(c2py(OST_RAW.group(2).split("=", 1)[1]), {"np": np}, {"tid": tid, "i": i})
+ for ldx in (eval(c2py(OST_RAW.group(3)), {"np": np}, {"rr": rr, "cc": cc, "LDR": LDR}),):
+ if ldx.min() < 0 or ldx.max() + 8 > BT * LDR: fail(f"OST LDS sW read range {ldx.min()}..{ldx.max() + 8} > {BT * LDR}")
+ if (ldx % 8).any(): fail("OST LDS sW read alignment")
+ ext = B * T * HV * VD
+ for i_n in range(B):
+ bos = i_n * T
+ for i_hv in sorted({0, 1, HV // H - 1, HV // H, HV // 2, HV - 2, HV - 1}):
+ env = {"H": H, "HV": HV, "T": T, "bos": bos, "PV": PV}
+ for i_t in range(NT):
+ t = i_t * BT + rr
+ ok = eval(c2py(OST_RAW.group(4)), {"np": np}, {"t": t, "T": T})
+ idx = np.asarray(mcall("IX_V", bos + t[ok], i_hv, cc[ok], env=env), dtype=np.int64)
+ if idx.size and (idx.min() < 0 or idx.max() + 8 > ext): fail(f"OST o vector store: B{B} T{T} hv{i_hv}: [{idx.min()}, {idx.max() + 8}) outside 0..{ext}")
+ if (idx % 8).any(): fail("OST o vector store alignment")
+ # every in-range (t, col) element must be written exactly once (coverage)
+ if i_hv == 0:
+ cover = np.zeros((min(BT, T - i_t * BT), VD), dtype=np.int32)
+ for tt_, c_ in zip((rr[ok] - 0).ravel(), cc[ok].ravel()):
+ if tt_ < cover.shape[0]: cover[tt_, c_:c_ + 8] += 1
+ else: fail(f"OST store of row {tt_} past the chunk (T {T})")
+ if not (cover == 1).all(): fail(f"OST coverage of the o tile: B{B} T{T} chunk {i_t}")
+def ost_order_check():
+ i_chain = src.rfind("ld16(sW, 16 * a + ll, LDR, 16 * kt)")
+ i_bar1 = src.find("__syncthreads(); // every wave is done reading sW")
+ i_stage = src.find("sW[(16 * a + 2 * r + half) * LDR + col] = (uint16_t) f2bf(res);")
+ i_bar2 = src.find("SYNCA(64); // k^T visible")
+ i_copy = src.find("const uint4 x = *(const uint4*) (sW + ")
+ if not (0 <= i_chain < i_bar1 < i_stage < i_bar2 < i_copy): fail(f"OST barrier order broken: chain {i_chain} bar1 {i_bar1} stage {i_stage} bar2 {i_bar2} copy {i_copy}")
+
+# ---- LDS accesses from the source text
+sizes = {"sW": BT * LDR, "sX": KD * LDT, "sY": KD * LDT, "sA": BT * LDT, "sG": BT, "sGE": BT, "sRS": BT}
+VARS = {"tid": range(256), "cp": range(64), "tg": range(4), "s2": range(8), "s": range(16), "c": range(2), "ar": range(64),
+ "ac": (0, 16, 32, 48), "a": range(4), "j": range(4), "r": range(8), "half": range(2), "col": range(128),
+ "ll": range(16), "kt": range(8), "tix": range(10), "wv": range(8), "e": range(2), "tt": range(64)}
+DERIVED = {"ri": "16 * a + 2 * r + half", "cj": "16 * j + ll", "wv": None}
+def lds_check(buf, expr, width, align, where):
+ e = expr
+ for d, de in DERIVED.items():
+ if de: e = re.sub(rf"\b{d}\b", f"({de})", e)
+ names = sorted(set(re.findall(r"[A-Za-z_]\w*", e)) & set(VARS) - {"LDR", "LDT"})
+ # Aqk tile decode: a, j come from tix; use the full a, j grid (superset)
+ grids = [range(64) if (n == "tid" and buf in ("sG", "sGE", "sRS")) else VARS[n] for n in names]
+ if "tid" in names and buf in ("sG", "sGE", "sRS"):
+ assert "if (tid < BT)" in src, "sG writes must stay under tid < BT"
+ envc = {"LDR": LDR, "LDT": LDT, "BT": BT, "KD": KD}
+ arrs = np.meshgrid(*[np.array(list(g)) for g in grids], indexing="ij") if grids else []
+ val = eval(c2py(e), {"np": np}, {**envc, **dict(zip(names, arrs))})
+ val = np.asarray(val)
+ if val.min() < 0 or val.max() + width > sizes[buf]:
+ fail(f"LDS {buf} [{where}] {expr}: range {val.min()}..{val.max() + width} > {sizes[buf]}")
+ if align > 1 and (val % align).any():
+ fail(f"LDS {buf} [{where}] {expr}: alignment {align}")
+n_lds = 0
+for m in re.finditer(r"ld16\((s[WXYA]),\s*([^,]+),\s*(LDR|LDT),\s*([^)]+)\)", src):
+ buf, row, ld, colx = m.groups()
+ lds_check(buf, f"({row}) * {ld} + ({colx})", 16, 8, "ld16"); n_lds += 1
+for m in re.finditer(r"\*\(uint32_t\*\) \((s[WXYA]) \+ (.*?)\) = ", src):
+ lds_check(m.group(1), m.group(2), 2, 2, "st32"); n_lds += 1
+for m in re.finditer(r"(?<![\w])(s[WXYA]|sG|sGE|sRS)\[([^\]]+)\]\s*=", src):
+ lds_check(m.group(1), m.group(2), 1, 1, "st16"); n_lds += 1
+for m in re.finditer(r"uint4\* d = \(uint4\*\) \((s[WXYA]) \+ (.*?)\);", src):
+ lds_check(m.group(1), m.group(2), 16, 8, "st128"); n_lds += 1
+for m in re.finditer(r"(?<![\w=])(sG|sGE|sRS)\[([^\]]+)\](?!\s*=)", src):
+ if m.group(2).strip() == "BT": continue # the declaration
+ lds_check(m.group(1), m.group(2), 1, 1, "ld32"); n_lds += 1
+
+# ---- layer 2 (rule 14): the same global accesses evaluated from the PREPROCESSED source (cpp: macros expanded, -D flags applied), so a macro
+# argument / body that captures an outer variable is seen exactly as the compiler sees it. Statement forms are matched in the expanded text.
+import subprocess, tempfile, os
+defs = sys.argv[sys.argv.index("--defs") + 1].split() if "--defs" in sys.argv else []
+def expanded_text():
+ raw = "\n".join(l for l in src.split("\n") if not l.startswith("#include"))
+ with tempfile.NamedTemporaryFile("w", suffix=".cpp", delete=False) as f: f.write(raw); fn = f.name
+ out = subprocess.run(["cpp", "-P", "-undef", "-nostdinc", "-x", "c++"] + [f"-D{d}" for d in defs] + [fn], capture_output=True, text=True, check=True).stdout
+ os.unlink(fn)
+ return out
+EXP = expanded_text()
+def site(pattern, count=None):
+ ms = re.findall(pattern, EXP, re.M)
+ if not ms or (count is not None and len(ms) != count):
+ fail(f"expanded-source site not found / wrong count ({len(ms)}): {pattern}"); return []
+ return ms
+def balanced_arg(text_after):
+ d = 1; i = 0
+ while i < len(text_after) and d:
+ d += text_after[i] == "("; d -= text_after[i] == ")"; i += 1
+ return text_after[:i - 1]
+def pyx(e):
+ e = e.replace("(int64_t)", "").replace("(int)", "")
+ return re.sub(r"\bmin\(", "np.minimum(", e)
+S_GL = site(r"const float gl = g\[(.+)\];", 1)
+S_A = site(r"ld16g\(A \+ (.+), t0 \+ ar < T\)", 1)
+S_TC = site(r"const int64_t tc = (.+);", 1)
+S_K = site(r"uint32_t kk = \*\(const uint32_t\*\) \(k \+ (.+)\);$", 1)
+S_Q = site(r"uint32_t qq = \*\(const uint32_t\*\) \(q \+ (.+)\);$", 1)
+S_V = site(r"uint32_t vv = \*\(const uint32_t\*\) \(v \+ (.+)\);$", 1)
+S_G1 = site(r"float gv = g\[(.+)\];$", 1)
+S_B1 = site(r"uint32_t bb = beta\[(.+)\];$", 1)
+S_SG = site(r"const float gv = \(t < T\) \? g\[(.+)\] : 0\.0f;", 1)
+OSTMODE = "OST=1" in defs
+if OSTMODE:
+ S_O = []
+ S_OV = site(r"if \((.+)\) \*\(uint4\*\) \(o \+ (.+)\) = x;", 1)
+ S_RC = site(r"const int rr = (.+), cc = (.+), t = (.+);", 1)
+ S_LR = site(r"const uint4 x = \*\(const uint4\*\) \(sW \+ (.+)\);", 1)
+else:
+ S_O = site(r"if \((.+)\) o\[(.+)\] = \(uint16_t\) f2bf\(res\);", 1)
+S_H0 = site(r"h0 \? h0\[(.+)\] : 0\.0f", 1)
+S_HT = site(r"ht\[(.+)\] = h\[kt\]\[r\];", 1)
+S_HC = site(r"hc2?\[(.+)\] = h\[kt\]\[r\];", 2) if "CKPT=1" in defs else []
+def expanded_proof(B, T, H, HV, PV):
+ NT = (T + 63) // 64
+ ext = {"qk": B * T * H * KD, "vr": (B * T - 1) * PV + HV * VD, "v": B * T * HV * VD, "g": B * T * HV, "A": B * T * HV * BT, "S": B * HV * KD * VD}
+ tid = np.arange(256); cp = tid & 63; tg = tid >> 6; ar = tid >> 2; ac = 16 * (tid & 3)
+ def chk(name, idx, width, tens, tag, B_, T_, hv):
+ idx = np.asarray(idx, dtype=np.int64)
+ if idx.size and (idx.min() < 0 or (idx + width).max() > ext[tens]):
+ fail(f"[expanded] {tag}: B{B_} T{T_} hv{hv}: {name} idx [{idx.min()}, {(idx + width).max()}) outside 0..{ext[tens]}")
+ for i_n in range(B):
+ bos = i_n * T
+ for i_hv in sorted({0, HV // H - 1, HV // H, HV // 2, HV - 1}):
+ i_h = i_hv // (HV // H); i_nh = i_n * HV + i_hv
+ base = {"np": np, "bos": bos, "T": T, "H": H, "HV": HV, "PV": PV, "i_h": i_h, "i_hv": i_hv, "i_nh": i_nh}
+ for i_t in range(NT):
+ t0 = i_t * 64; last = min(t0 + 64, T) - 1
+ env = {**base, "t0": t0, "last": last, "ar": ar, "ac": ac}
+ chk("g_last", eval(pyx(S_GL[0]), env), 1, "g", "gl", B, T, i_hv)
+ ia = eval(pyx(S_A[0]), env); chk("A", ia, 16, "A", "A", B, T, i_hv)
+ if (np.asarray(ia) % 16).any(): fail("[expanded] A alignment")
+ s2, e = np.meshgrid(np.arange(8), np.arange(2), indexing="ij")
+ tt_ = tg[:, None, None] * 16 + 2 * s2[None] + e[None]
+ env2 = {**base, "t0": t0, "cp": cp[:, None, None], "tg": tg[:, None, None], "t": t0 + tt_, "tt": tt_}
+ tc = eval(pyx(S_TC[0]), env2); env2["tc"] = tc
+ for nm, ex, tens, w in (("k", S_K, "qk", 2), ("q", S_Q, "qk", 2), ("v", S_V, "vr", 2), ("g", S_G1, "g", 1), ("beta", S_B1, "g", 1)):
+ chk(nm, eval(pyx(ex[0]), env2), w, tens, nm, B, T, i_hv)
+ tq = np.arange(64); env3 = {**base, "t0": t0, "tid": tq, "t": t0 + tq}
+ ok = env3["t"] < T
+ chk("sG load", np.asarray(eval(pyx(S_SG[0]), env3))[ok], 1, "g", "sG", B, T, i_hv)
+ a, r, half, col = np.meshgrid(np.arange(4), np.arange(8), np.arange(2), np.arange(128), indexing="ij")
+ env4 = {**base, "t0": t0, "a": a, "r": r, "half": half, "col": col, "t": t0 + 16 * a + 2 * r + half}
+ if OSTMODE:
+ tid_, i_ = np.meshgrid(np.arange(256), np.arange(4), indexing="ij")
+ env6 = {**base, "t0": t0, "tid": tid_, "i": i_}
+ env6["rr"] = eval(pyx(S_RC[0][0]), env6); env6["cc"] = eval(pyx(S_RC[0][1]), env6); env6["t"] = eval(pyx(S_RC[0][2]), env6)
+ okv = np.broadcast_to(eval(pyx(S_OV[0][0]), env6), tid_.shape)
+ idx = np.asarray(eval(pyx(S_OV[0][1]), env6)); lds = np.asarray(eval(pyx(S_LR[0]), {**env6, "LDR": LDR}))
+ chk("o vector store", idx[okv], 8, "v", "o", B, T, i_hv)
+ if (idx[okv] % 8).any(): fail("[expanded] o vector store alignment")
+ if lds.min() < 0 or lds.max() + 8 > BT * LDR or (lds % 8).any(): fail(f"[expanded] OST LDS read {lds.min()}..{lds.max() + 8}")
+ else:
+ okm = eval(pyx(S_O[0][0]), env4)
+ idx = np.asarray(eval(pyx(S_O[0][1]), env4))
+ chk("o store", idx[np.broadcast_to(okm, idx.shape)], 1, "v", "o", B, T, i_hv)
+ kt, r, half, col = np.meshgrid(np.arange(8), np.arange(8), np.arange(2), np.arange(128), indexing="ij")
+ env5 = {**base, "kt": kt, "r": r, "half": half, "col": col}
+ for ex in (S_H0, S_HT): chk("state", eval(pyx(ex[0]), env5), 1, "S", "state", B, T, i_hv)
+ for ex in S_HC: chk("ckpt state", eval(pyx(ex), env5), 1, "S", "ckpt", B, T, i_hv)
+
+ost_order_check()
+shapes = [(1, T, 16, 48) for T in list(range(1, 130)) + [255, 511, 1000, 1999, 2047, 2048, 2049, 4095, 4096, 4097]] + [(2, 100, 16, 48), (2, 2048, 16, 48), (1, 4096, 16, 64)]
+if "--quick" in sys.argv: shapes = [(1, T, 16, 48) for T in (1, 63, 64, 65, 1999, 2048)] + [(2, 100, 16, 48)]
+PVS = lambda HV_: (HV_ * VD, 2 * 16 * KD + HV_ * VD) # contiguous v, and the conv-output slice pitch (q | k | v)
+n_exp = 0
+for (B, T, H, HV) in shapes:
+ for PV in PVS(HV):
+ global_proof(B, T, H, HV, PV)
+ ost_global_proof(B, T, H, HV, PV)
+ if T in (1, 2, 17, 63, 64, 65, 100, 129, 1999, 2048, 4097) or B > 1 or HV != 48:
+ for PV in PVS(HV):
+ try: expanded_proof(B, T, H, HV, PV); n_exp += 1
+ except NameError as ex: fail(f"[expanded] expression uses a name that is not in scope at its site ({ex}): macro capture")
+print(f"expanded-source layer: {n_exp} (shape, pitch) replays, {len(S_GL + S_A + S_TC + S_K + S_Q + S_V + S_G1 + S_B1 + S_SG + S_O + S_H0 + S_HT + S_HC)} sites")
+print(f"checked {len(shapes)} shapes, {len(macros)} macros, {n_lds} LDS access expressions")
+if fails:
+ print("VIOLATIONS:"); [print(" ", f) for f in fails]; sys.exit(1)
+print("bounds proof CLEAN")
diff --git a/tools/prefill/check_gdn_bounds_big.py b/tools/prefill/check_gdn_bounds_big.py
new file mode 100644
index 0000000..5a736a6
--- /dev/null
+++ b/tools/prefill/check_gdn_bounds_big.py
@@ -0,0 +1,312 @@
+"""CPU bounds proof for gdn_fused_h.hip (run BEFORE any GPU run of a kernel revision).
+Parses the kernel source itself: the IX_* / TCL macros, the guard of every global store, and every LDS access expression
+(ld16 calls, uint32 / uint16 stores into sW sX sY sA sG sGE sRS). Replays all of them over the real shapes
+(Qwen H 16, HV 48, K = V = 128, BT 64; T = 1..4097 incl. non-multiples of 64; B 1 and 2) and asserts every element
+index (plus access width and 16 B alignment of vector accesses) stays inside the tensor / LDS buffer.
+Usage: check_gdn_bounds.py <file.hip> [--mutate N] [--defs "ABL=0 ..."] (mutations 1..9 must FAIL, 16..18 with --defs "OST=1 CKPT=1" (checkpoint store index / column / batch item), 10..15 with --defs "OST=1": they model a dropped clamp, a dropped
+store guard, an LDS row-stride overflow, a bad state-store index and a bad LDS q write).
+Exit 0 = proof clean, 1 = violation found."""
+import itertools, re, sys
+import numpy as np
+
+src = open(sys.argv[1]).read()
+mut = int(sys.argv[sys.argv.index("--mutate") + 1]) if "--mutate" in sys.argv else 0
+if mut == 1:
+ src = src.replace("min((t_), (T_) - 1)", "(t_)") # drop the row clamp
+elif mut == 2:
+ src = src.replace("if (t < T) o[IX_V(bos + t, i_hv, col)]", "if (t < T + 64) o[IX_V(bos + t, i_hv, col)]")
+elif mut == 3:
+ src = src.replace("sA + ar * LDT + ac", "sA + ar * (LDT + 8) + ac")
+elif mut == 4:
+ src = src.replace("ht[IX_S(i_nh, 16 * kt + 2 * r + half, col)]", "ht[IX_S(i_nh, 16 * kt + 2 * r + half + 8, col)]")
+elif mut == 5:
+ src = src.replace("sX + (16 * tg + s) * LDR + 2 * cp)", "sX + (16 * tg + s + 4) * LDR + 2 * cp)")
+elif mut == 6:
+ src = src.replace("#define IX_VR(tc, hv, c) ((((int64_t) (tc)) * PV)", "#define IX_VR(tc, hv, c) ((((int64_t) (tc)) * (PV + 8))") # wrong v pitch
+elif mut == 7:
+ src = src.replace("uint32_t vv = *(const uint32_t*) (v + IX_VR(tc, i_hv, 2 * cp));", "uint32_t vv = *(const uint32_t*) (v + IX_VR(t, i_hv, 2 * cp));") # unclamped row
+elif mut == 8:
+ src = src.replace("#define TCL(bos_, t_, T_) ((bos_) + min((t_), (T_) - 1))", "#define TCL(bos_, t_, T_) ((bos_) + min((t_), (T_) - 1) + t)") # macro argument capturing the outer loop variable t
+elif mut == 9:
+ src = src.replace("#define IX_G(tc, hv) (((int64_t) (tc)) * HV + (hv))", "#define IX_G(tc, hv) (((int64_t) (tc)) * HV + (hv) + t0)") # macro body capturing an outer variable
+elif mut == 10:
+ src = src.replace("if (t < T) *(uint4*) (o + IX_V(bos + t, i_hv, cc)) = x;", "if (t < T + 64) *(uint4*) (o + IX_V(bos + t, i_hv, cc)) = x;") # OST: dropped row guard of the vector store
+elif mut == 11:
+ src = src.replace("const uint4 x = *(const uint4*) (sW + rr * LDR + cc);", "const uint4 x = *(const uint4*) (sW + (rr + 8) * LDR + cc);") # OST: LDS read past the tile
+elif mut == 12:
+ src = src.replace("cc = 8 * (tid & 15)", "cc = 8 * (tid & 31)") # OST: columns past the head
+elif mut == 13:
+ src = src.replace(" __syncthreads(); // every wave is done reading sW (w) before the o tile is staged into it\n", "") # OST: staging races with the vn chain reads of sW
+elif mut == 14:
+ src = src.replace(" SYNCA(64); // k^T visible\n", "") # OST: copy-out races with the staging writes
+elif mut == 15:
+ src = src.replace("sW[(16 * a + 2 * r + half) * LDR + col] = (uint16_t) f2bf(res);", "sW[(16 * a + 2 * r + half) * LDR + col + 80] = (uint16_t) f2bf(res);") # OST: staging write past the tile
+elif mut == 16:
+ src = src.replace("hc[IX_S(i_nh, 16 * kt + 2 * r + half, col)]", "hc[IX_S(i_nh, 16 * kt + 2 * r + half + 8, col)]") # CKPT: bad state-row index of the mid-chunk checkpoint store
+elif mut == 17:
+ src = src.replace("hc2[IX_S(i_nh, 16 * kt + 2 * r + half, col)]", "hc2[IX_S(i_nh, 16 * kt + 2 * r + half, col + 64)]") # CKPT: bad column of the second checkpoint store
+elif mut == 18:
+ src = src.replace("hc[IX_S(i_nh, 16 * kt + 2 * r + half, col)]", "hc[IX_S(i_nh + HV, 16 * kt + 2 * r + half, col)]") # CKPT: checkpoint written one batch item too far
+if mut:
+ print(f"[mutation {mut}] expecting a violation")
+
+fails = []
+def fail(msg):
+ if len(fails) < 12: fails.append(msg)
+
+# ---- constants and macros from the source
+consts = {}
+for m in re.finditer(r"^#define (BT|KD|VD|LDR|LDT)\s+(\d+)", src, re.M): consts[m.group(1)] = int(m.group(2))
+for k in ("BT", "KD", "VD", "LDR", "LDT"): assert k in consts, k
+BT, KD, VD, LDR, LDT = (consts[k] for k in ("BT", "KD", "VD", "LDR", "LDT"))
+macros = {}
+for m in re.finditer(r"^#define ((?:IX_\w+|TCL))\(([^)]*)\)\s+(.*)$", src, re.M):
+ name, args, body = m.group(1), [a.strip() for a in m.group(2).split(",")], re.sub(r"//.*$", "", m.group(3)).strip()
+ macros[name] = (args, body)
+def c2py(e):
+ e = e.replace("(int64_t)", "")
+ e = re.sub(r"\bmin\(", "np.minimum(", e)
+ return e
+def mcall(name, *vals, env):
+ args, body = macros[name]
+ e = c2py(body)
+ local = dict(zip(args, vals))
+ return eval(e, {"np": np, "BT": BT, "KD": KD, "VD": VD}, {**env, **local})
+
+# ---- global accesses over the real shapes
+def global_proof(B, T, H, HV, PV):
+ NT = (T + BT - 1) // BT
+ ext = {"qk": B * T * H * KD, "v": B * T * HV * VD, "vr": (B * T - 1) * PV + HV * VD, "g": B * T * HV, "A": B * T * HV * BT, "S": B * HV * KD * VD}
+ # guard of the o store, taken from the source
+ gm = re.search(r"if \(([^)]*)\) o\[IX_V\(bos \+ t, i_hv, col\)\]", src)
+ assert gm, "o store guard not found"
+ ostore_guard = c2py(gm.group(1))
+ tid = np.arange(256); cp = tid & 63; tg = tid >> 6; ar = tid >> 2; ac = 16 * (tid & 3)
+ for i_n in range(B):
+ bos = i_n * T
+ for i_hv in sorted({0, 1, HV // H - 1, HV // H, HV // 2, HV - 2, HV - 1}): # extremes of every index term (all affine in i_hv)
+ i_h = i_hv // (HV // H)
+ env = {"H": H, "HV": HV, "T": T, "bos": bos, "PV": PV}
+ i_nh = i_n * HV + i_hv
+ def chk(name, idx, width, tens, tag):
+ idx = np.asarray(idx, dtype=np.int64)
+ if idx.size and (idx.min() < 0 or (idx + width).max() > ext[tens]):
+ fail(f"{tag}: B{B} T{T} hv{i_hv}: {name} idx [{idx.min()}, {(idx + width).max()}) outside 0..{ext[tens]}")
+ for i_t in range(NT):
+ t0 = i_t * BT
+ last = min(t0 + BT, T) - 1
+ chk("g_last", mcall("IX_G", bos + last, i_hv, env=env), 1, "g", "gl")
+ tcA = mcall("TCL", bos, t0 + ar, T, env=env)
+ chk("A", mcall("IX_A", tcA, i_hv, ac, env=env), 16, "A", "A")
+ if (mcall("IX_A", tcA, i_hv, ac, env=env) % 16).any(): fail("A vector alignment")
+ for s2, e in itertools.product(range(8), range(2)):
+ t = t0 + 16 * tg + 2 * s2 + e
+ tc = mcall("TCL", bos, t, T, env=env)
+ chk("k/q", mcall("IX_QK", tc, i_h, 2 * cp, env=env), 2, "qk", "kq")
+ chk("v", mcall("IX_VR", tc, i_hv, 2 * cp, env=env), 2, "vr", "v")
+ chk("g/beta", mcall("IX_G", tc, i_hv, env=env), 1, "g", "gb")
+ t = t0 + np.arange(64)
+ tcg = mcall("TCL", bos, t, T, env=env)
+ chk("sG load", mcall("IX_G", tcg[t < T], i_hv, env=env), 1, "g", "sG")
+ # o store: rows t0 + 16a + 2r + half, cols 0..127, guarded by the source's guard
+ a, r, half, col = np.meshgrid(np.arange(4), np.arange(8), np.arange(2), np.arange(128), indexing="ij")
+ t = t0 + 16 * a + 2 * r + half
+ ok = eval(ostore_guard, {"np": np}, {"t": t, "T": T})
+ idx = mcall("IX_V", bos + t[ok], i_hv, col[ok], env=env)
+ chk("o store", idx, 1, "v", "o")
+ kt, r, half, col = np.meshgrid(np.arange(8), np.arange(8), np.arange(2), np.arange(128), indexing="ij")
+ idx = mcall("IX_S", i_nh, 16 * kt + 2 * r + half, col, env=env)
+ chk("h0/ht", idx, 1, "S", "state")
+ # the state-store expression text must be the one proven above (mutation 4 changes it)
+ for m in re.finditer(r"(?:ht|h0|hc2?)\[IX_S\(i_nh, ([^,]*), col\)\]", src):
+ kt, r, half = np.meshgrid(np.arange(8), np.arange(8), np.arange(2), indexing="ij")
+ row = eval(c2py(m.group(1)), {"np": np}, {"kt": kt, "r": r, "half": half})
+ if row.min() < 0 or row.max() >= KD: fail(f"state row expr {m.group(1)} range {row.min()}..{row.max()}")
+
+# ---- OST (o tile staged through sW, 16 B vector copy-out): bounds of the vector store and of the LDS read, and the barrier order
+OST_RAW = re.search(r"#if OST\n\s*// o tile.*?\n\s*#pragma unroll\n\s*for \(int i = 0; i < 4; \+\+i\)\n\s*\{\n\s*const int (rr = .*?), (cc = .*?), t = t0 \+ rr;\n\s*const uint4 x = \*\(const uint4\*\) \(sW \+ (.*?)\);\n\s*if \((.*?)\) \*\(uint4\*\) \(o \+ (IX_V\(.*?\))\) = x;", src, re.S)
+assert OST_RAW, "OST copy-out block not found"
+def ost_global_proof(B, T, H, HV, PV):
+ NT = (T + BT - 1) // BT
+ tid, i = np.meshgrid(np.arange(256), np.arange(4), indexing="ij")
+ rr = eval(c2py(OST_RAW.group(1).split("=", 1)[1]), {"np": np}, {"tid": tid, "i": i})
+ cc = eval(c2py(OST_RAW.group(2).split("=", 1)[1]), {"np": np}, {"tid": tid, "i": i})
+ for ldx in (eval(c2py(OST_RAW.group(3)), {"np": np}, {"rr": rr, "cc": cc, "LDR": LDR}),):
+ if ldx.min() < 0 or ldx.max() + 8 > BT * LDR: fail(f"OST LDS sW read range {ldx.min()}..{ldx.max() + 8} > {BT * LDR}")
+ if (ldx % 8).any(): fail("OST LDS sW read alignment")
+ ext = B * T * HV * VD
+ for i_n in range(B):
+ bos = i_n * T
+ for i_hv in sorted({0, 1, HV // H - 1, HV // H, HV // 2, HV - 2, HV - 1}):
+ env = {"H": H, "HV": HV, "T": T, "bos": bos, "PV": PV}
+ for i_t in range(NT):
+ t = i_t * BT + rr
+ ok = eval(c2py(OST_RAW.group(4)), {"np": np}, {"t": t, "T": T})
+ idx = np.asarray(mcall("IX_V", bos + t[ok], i_hv, cc[ok], env=env), dtype=np.int64)
+ if idx.size and (idx.min() < 0 or idx.max() + 8 > ext): fail(f"OST o vector store: B{B} T{T} hv{i_hv}: [{idx.min()}, {idx.max() + 8}) outside 0..{ext}")
+ if (idx % 8).any(): fail("OST o vector store alignment")
+ # every in-range (t, col) element must be written exactly once (coverage)
+ if i_hv == 0:
+ cover = np.zeros((min(BT, T - i_t * BT), VD), dtype=np.int32)
+ for tt_, c_ in zip((rr[ok] - 0).ravel(), cc[ok].ravel()):
+ if tt_ < cover.shape[0]: cover[tt_, c_:c_ + 8] += 1
+ else: fail(f"OST store of row {tt_} past the chunk (T {T})")
+ if not (cover == 1).all(): fail(f"OST coverage of the o tile: B{B} T{T} chunk {i_t}")
+def ost_order_check():
+ i_chain = src.rfind("ld16(sW, 16 * a + ll, LDR, 16 * kt)")
+ i_bar1 = src.find("__syncthreads(); // every wave is done reading sW")
+ i_stage = src.find("sW[(16 * a + 2 * r + half) * LDR + col] = (uint16_t) f2bf(res);")
+ i_bar2 = src.find("SYNCA(64); // k^T visible")
+ i_copy = src.find("const uint4 x = *(const uint4*) (sW + ")
+ if not (0 <= i_chain < i_bar1 < i_stage < i_bar2 < i_copy): fail(f"OST barrier order broken: chain {i_chain} bar1 {i_bar1} stage {i_stage} bar2 {i_bar2} copy {i_copy}")
+
+# ---- LDS accesses from the source text
+sizes = {"sW": BT * LDR, "sX": KD * LDT, "sY": KD * LDT, "sA": BT * LDT, "sG": BT, "sGE": BT, "sRS": BT}
+VARS = {"tid": range(256), "cp": range(64), "tg": range(4), "s2": range(8), "s": range(16), "c": range(2), "ar": range(64),
+ "ac": (0, 16, 32, 48), "a": range(4), "j": range(4), "r": range(8), "half": range(2), "col": range(128),
+ "ll": range(16), "kt": range(8), "tix": range(10), "wv": range(8), "e": range(2), "tt": range(64)}
+DERIVED = {"ri": "16 * a + 2 * r + half", "cj": "16 * j + ll", "wv": None}
+def lds_check(buf, expr, width, align, where):
+ e = expr
+ for d, de in DERIVED.items():
+ if de: e = re.sub(rf"\b{d}\b", f"({de})", e)
+ names = sorted(set(re.findall(r"[A-Za-z_]\w*", e)) & set(VARS) - {"LDR", "LDT"})
+ # Aqk tile decode: a, j come from tix; use the full a, j grid (superset)
+ grids = [range(64) if (n == "tid" and buf in ("sG", "sGE", "sRS")) else VARS[n] for n in names]
+ if "tid" in names and buf in ("sG", "sGE", "sRS"):
+ assert "if (tid < BT)" in src, "sG writes must stay under tid < BT"
+ envc = {"LDR": LDR, "LDT": LDT, "BT": BT, "KD": KD}
+ arrs = np.meshgrid(*[np.array(list(g)) for g in grids], indexing="ij") if grids else []
+ val = eval(c2py(e), {"np": np}, {**envc, **dict(zip(names, arrs))})
+ val = np.asarray(val)
+ if val.min() < 0 or val.max() + width > sizes[buf]:
+ fail(f"LDS {buf} [{where}] {expr}: range {val.min()}..{val.max() + width} > {sizes[buf]}")
+ if align > 1 and (val % align).any():
+ fail(f"LDS {buf} [{where}] {expr}: alignment {align}")
+n_lds = 0
+for m in re.finditer(r"ld16\((s[WXYA]),\s*([^,]+),\s*(LDR|LDT),\s*([^)]+)\)", src):
+ buf, row, ld, colx = m.groups()
+ lds_check(buf, f"({row}) * {ld} + ({colx})", 16, 8, "ld16"); n_lds += 1
+for m in re.finditer(r"\*\(uint32_t\*\) \((s[WXYA]) \+ (.*?)\) = ", src):
+ lds_check(m.group(1), m.group(2), 2, 2, "st32"); n_lds += 1
+for m in re.finditer(r"(?<![\w])(s[WXYA]|sG|sGE|sRS)\[([^\]]+)\]\s*=", src):
+ lds_check(m.group(1), m.group(2), 1, 1, "st16"); n_lds += 1
+for m in re.finditer(r"uint4\* d = \(uint4\*\) \((s[WXYA]) \+ (.*?)\);", src):
+ lds_check(m.group(1), m.group(2), 16, 8, "st128"); n_lds += 1
+for m in re.finditer(r"(?<![\w=])(sG|sGE|sRS)\[([^\]]+)\](?!\s*=)", src):
+ if m.group(2).strip() == "BT": continue # the declaration
+ lds_check(m.group(1), m.group(2), 1, 1, "ld32"); n_lds += 1
+
+# ---- layer 2 (rule 14): the same global accesses evaluated from the PREPROCESSED source (cpp: macros expanded, -D flags applied), so a macro
+# argument / body that captures an outer variable is seen exactly as the compiler sees it. Statement forms are matched in the expanded text.
+import subprocess, tempfile, os
+defs = sys.argv[sys.argv.index("--defs") + 1].split() if "--defs" in sys.argv else []
+def expanded_text():
+ raw = "\n".join(l for l in src.split("\n") if not l.startswith("#include"))
+ with tempfile.NamedTemporaryFile("w", suffix=".cpp", delete=False) as f: f.write(raw); fn = f.name
+ out = subprocess.run(["cpp", "-P", "-undef", "-nostdinc", "-x", "c++"] + [f"-D{d}" for d in defs] + [fn], capture_output=True, text=True, check=True).stdout
+ os.unlink(fn)
+ return out
+EXP = expanded_text()
+def site(pattern, count=None):
+ ms = re.findall(pattern, EXP, re.M)
+ if not ms or (count is not None and len(ms) != count):
+ fail(f"expanded-source site not found / wrong count ({len(ms)}): {pattern}"); return []
+ return ms
+def balanced_arg(text_after):
+ d = 1; i = 0
+ while i < len(text_after) and d:
+ d += text_after[i] == "("; d -= text_after[i] == ")"; i += 1
+ return text_after[:i - 1]
+def pyx(e):
+ e = e.replace("(int64_t)", "").replace("(int)", "")
+ return re.sub(r"\bmin\(", "np.minimum(", e)
+S_GL = site(r"const float gl = g\[(.+)\];", 1)
+S_A = site(r"ld16g\(A \+ (.+), t0 \+ ar < T\)", 1)
+S_TC = site(r"const int64_t tc = (.+);", 1)
+S_K = site(r"uint32_t kk = \*\(const uint32_t\*\) \(k \+ (.+)\);$", 1)
+S_Q = site(r"uint32_t qq = \*\(const uint32_t\*\) \(q \+ (.+)\);$", 1)
+S_V = site(r"uint32_t vv = \*\(const uint32_t\*\) \(v \+ (.+)\);$", 1)
+S_G1 = site(r"float gv = g\[(.+)\];$", 1)
+S_B1 = site(r"uint32_t bb = beta\[(.+)\];$", 1)
+S_SG = site(r"const float gv = \(t < T\) \? g\[(.+)\] : 0\.0f;", 1)
+OSTMODE = "OST=1" in defs
+if OSTMODE:
+ S_O = []
+ S_OV = site(r"if \((.+)\) \*\(uint4\*\) \(o \+ (.+)\) = x;", 1)
+ S_RC = site(r"const int rr = (.+), cc = (.+), t = (.+);", 1)
+ S_LR = site(r"const uint4 x = \*\(const uint4\*\) \(sW \+ (.+)\);", 1)
+else:
+ S_O = site(r"if \((.+)\) o\[(.+)\] = \(uint16_t\) f2bf\(res\);", 1)
+S_H0 = site(r"h0 \? h0\[(.+)\] : 0\.0f", 1)
+S_HT = site(r"ht\[(.+)\] = h\[kt\]\[r\];", 1)
+S_HC = site(r"hc2?\[(.+)\] = h\[kt\]\[r\];", 2) if "CKPT=1" in defs else []
+def expanded_proof(B, T, H, HV, PV):
+ NT = (T + 63) // 64
+ ext = {"qk": B * T * H * KD, "vr": (B * T - 1) * PV + HV * VD, "v": B * T * HV * VD, "g": B * T * HV, "A": B * T * HV * BT, "S": B * HV * KD * VD}
+ tid = np.arange(256); cp = tid & 63; tg = tid >> 6; ar = tid >> 2; ac = 16 * (tid & 3)
+ def chk(name, idx, width, tens, tag, B_, T_, hv):
+ idx = np.asarray(idx, dtype=np.int64)
+ if idx.size and (idx.min() < 0 or (idx + width).max() > ext[tens]):
+ fail(f"[expanded] {tag}: B{B_} T{T_} hv{hv}: {name} idx [{idx.min()}, {(idx + width).max()}) outside 0..{ext[tens]}")
+ for i_n in range(B):
+ bos = i_n * T
+ for i_hv in sorted({0, HV // H - 1, HV // H, HV // 2, HV - 1}):
+ i_h = i_hv // (HV // H); i_nh = i_n * HV + i_hv
+ base = {"np": np, "bos": bos, "T": T, "H": H, "HV": HV, "PV": PV, "i_h": i_h, "i_hv": i_hv, "i_nh": i_nh}
+ for i_t in range(NT):
+ t0 = i_t * 64; last = min(t0 + 64, T) - 1
+ env = {**base, "t0": t0, "last": last, "ar": ar, "ac": ac}
+ chk("g_last", eval(pyx(S_GL[0]), env), 1, "g", "gl", B, T, i_hv)
+ ia = eval(pyx(S_A[0]), env); chk("A", ia, 16, "A", "A", B, T, i_hv)
+ if (np.asarray(ia) % 16).any(): fail("[expanded] A alignment")
+ s2, e = np.meshgrid(np.arange(8), np.arange(2), indexing="ij")
+ tt_ = tg[:, None, None] * 16 + 2 * s2[None] + e[None]
+ env2 = {**base, "t0": t0, "cp": cp[:, None, None], "tg": tg[:, None, None], "t": t0 + tt_, "tt": tt_}
+ tc = eval(pyx(S_TC[0]), env2); env2["tc"] = tc
+ for nm, ex, tens, w in (("k", S_K, "qk", 2), ("q", S_Q, "qk", 2), ("v", S_V, "vr", 2), ("g", S_G1, "g", 1), ("beta", S_B1, "g", 1)):
+ chk(nm, eval(pyx(ex[0]), env2), w, tens, nm, B, T, i_hv)
+ tq = np.arange(64); env3 = {**base, "t0": t0, "tid": tq, "t": t0 + tq}
+ ok = env3["t"] < T
+ chk("sG load", np.asarray(eval(pyx(S_SG[0]), env3))[ok], 1, "g", "sG", B, T, i_hv)
+ a, r, half, col = np.meshgrid(np.arange(4), np.arange(8), np.arange(2), np.arange(128), indexing="ij")
+ env4 = {**base, "t0": t0, "a": a, "r": r, "half": half, "col": col, "t": t0 + 16 * a + 2 * r + half}
+ if OSTMODE:
+ tid_, i_ = np.meshgrid(np.arange(256), np.arange(4), indexing="ij")
+ env6 = {**base, "t0": t0, "tid": tid_, "i": i_}
+ env6["rr"] = eval(pyx(S_RC[0][0]), env6); env6["cc"] = eval(pyx(S_RC[0][1]), env6); env6["t"] = eval(pyx(S_RC[0][2]), env6)
+ okv = np.broadcast_to(eval(pyx(S_OV[0][0]), env6), tid_.shape)
+ idx = np.asarray(eval(pyx(S_OV[0][1]), env6)); lds = np.asarray(eval(pyx(S_LR[0]), {**env6, "LDR": LDR}))
+ chk("o vector store", idx[okv], 8, "v", "o", B, T, i_hv)
+ if (idx[okv] % 8).any(): fail("[expanded] o vector store alignment")
+ if lds.min() < 0 or lds.max() + 8 > BT * LDR or (lds % 8).any(): fail(f"[expanded] OST LDS read {lds.min()}..{lds.max() + 8}")
+ else:
+ okm = eval(pyx(S_O[0][0]), env4)
+ idx = np.asarray(eval(pyx(S_O[0][1]), env4))
+ chk("o store", idx[np.broadcast_to(okm, idx.shape)], 1, "v", "o", B, T, i_hv)
+ kt, r, half, col = np.meshgrid(np.arange(8), np.arange(8), np.arange(2), np.arange(128), indexing="ij")
+ env5 = {**base, "kt": kt, "r": r, "half": half, "col": col}
+ for ex in (S_H0, S_HT): chk("state", eval(pyx(ex[0]), env5), 1, "S", "state", B, T, i_hv)
+ for ex in S_HC: chk("ckpt state", eval(pyx(ex), env5), 1, "S", "ckpt", B, T, i_hv)
+
+ost_order_check()
+shapes = [(1, T, 16, 48) for T in list(range(1, 130)) + [255, 511, 1000, 1999, 2047, 2048, 2049, 4095, 4096, 4097]] + [(2, 100, 16, 48), (2, 2048, 16, 48), (1, 4096, 16, 64)]
+BIG = (4097, 4098, 4127, 4128, 4160, 4352, 4608, 5119, 5120, 5121, 6144, 8191, 8192, 8193)
+if "--bigonly" in sys.argv: shapes = [(1, T, 16, 48) for T in BIG]
+else: shapes = shapes + [(1, T, 16, 48) for T in BIG] + [(1, 5120, 16, 64)]
+if "--quick" in sys.argv: shapes = [(1, T, 16, 48) for T in (1, 63, 64, 65, 1999, 2048)] + [(2, 100, 16, 48)]
+PVS = lambda HV_: (HV_ * VD, 2 * 16 * KD + HV_ * VD) # contiguous v, and the conv-output slice pitch (q | k | v)
+n_exp = 0
+for (B, T, H, HV) in shapes:
+ for PV in PVS(HV):
+ global_proof(B, T, H, HV, PV)
+ ost_global_proof(B, T, H, HV, PV)
+ if T in (1, 2, 17, 63, 64, 65, 100, 129, 1999, 2048, 4097) + BIG or B > 1 or HV != 48:
+ for PV in PVS(HV):
+ try: expanded_proof(B, T, H, HV, PV); n_exp += 1
+ except NameError as ex: fail(f"[expanded] expression uses a name that is not in scope at its site ({ex}): macro capture")
+print(f"expanded-source layer: {n_exp} (shape, pitch) replays, {len(S_GL + S_A + S_TC + S_K + S_Q + S_V + S_G1 + S_B1 + S_SG + S_O + S_H0 + S_HT + S_HC)} sites")
+print(f"checked {len(shapes)} shapes, {len(macros)} macros, {n_lds} LDS access expressions")
+if fails:
+ print("VIOLATIONS:"); [print(" ", f) for f in fails]; sys.exit(1)
+print("bounds proof CLEAN")
diff --git a/tools/qwen/cache8/.gitignore b/tools/qwen/cache8/.gitignore
new file mode 100644
index 0000000..c0bffaf
--- /dev/null
+++ b/tools/qwen/cache8/.gitignore
@@ -0,0 +1,2 @@
+_*_mut.py
+_mut/
diff --git a/tools/qwen/cache8/interp_dec8.py b/tools/qwen/cache8/interp_dec8.py
new file mode 100644
index 0000000..8141c0e
--- /dev/null
+++ b/tools/qwen/cache8/interp_dec8.py
@@ -0,0 +1,99 @@
+"""(decode split + combine kernels, q_len 1 and 4) CPU proof (Triton interpreter = the kernel body executed on CPU) of the 8-bit packed-cache read path of the QSA gather kernel
+(_qsa_sparse_split_kernel + _paged_attn_decode_combine_kernel, loaders _qc_load_kt/_qc_load_v) at the real Qwen geometry
+(24 q heads, 2 kv heads, head_dim 256, page 256, K_pad 2080, pool of 1024 pages = 262144 tokens).
+Checks: every masked-in pointer inside the exact tensor ranges (bounds), output == torch attention on the dequantised K/V.
+usage: TREE=<worktree> [TRITON_PAGED=<mutated triton_paged.py>] [MUT=name] python interp_qsa8.py"""
+import os, sys, importlib.util
+os.environ["TRITON_INTERPRET"] = "1"; os.environ["HIP_VISIBLE_DEVICES"] = "-1"
+TREE = os.environ["TREE"]; sys.path.insert(0, TREE); sys.path.insert(0, os.path.dirname(__file__))
+import numpy as np, torch, triton
+import triton.runtime.interpreter as _I
+_orig_patch = _I._patch_lang_tensor
+def _patch(tensor, scope):
+ _orig_patch(tensor, scope)
+ scope.set_attr(tensor, "__index__", lambda self: int(np.asarray(self.handle.data).reshape(-1)[0]))
+ scope.set_attr(tensor, "__bool__", lambda self: bool(np.asarray(self.handle.data).reshape(-1)[0]))
+_I._patch_lang_tensor = _patch
+torch.set_num_threads(2)
+RANGES, VIOL = [], []
+def _check(ptrs, mask, what):
+ p = np.asarray(ptrs.data).astype(np.uint64); m = np.asarray(mask.data).astype(bool) if mask is not None else np.ones(p.shape, bool)
+ sel = p[m]
+ if sel.size == 0: return
+ ok = np.zeros(sel.shape, bool)
+ for lo, hi in RANGES: ok |= (sel >= lo) & (sel < hi)
+ if not ok.all():
+ VIOL.append(f"{what}: {int((~ok).sum())} masked-in accesses outside every tensor"); raise RuntimeError("bounds violation")
+Bd = _I.InterpreterBuilder
+_ml, _ms, _l, _s = Bd.create_masked_load, Bd.create_masked_store, Bd.create_load, Bd.create_store
+def _ml2(self, ptrs, mask, other, *a): _check(ptrs, mask, "load"); return _ml(self, ptrs, mask, other, *a)
+def _ms2(self, ptrs, value, mask, *a): _check(ptrs, mask, "store"); return _ms(self, ptrs, value, mask, *a)
+def _l2(self, ptr, *a): _check(ptr, None, "load1"); return _l(self, ptr, *a)
+def _s2(self, ptr, val, *a): _check(ptr, None, "store1"); return _s(self, ptr, val, *a)
+Bd.create_masked_load, Bd.create_masked_store, Bd.create_load, Bd.create_store = _ml2, _ms2, _l2, _s2
+MUT = os.environ.get("MUT", "")
+if os.environ.get("TRITON_PAGED"): # mutated copy of triton_paged.py replaces the module before qsa_triton imports its loaders
+ import exllamav3.modules.attention_fn as pkg
+ spec = importlib.util.spec_from_file_location("exllamav3.modules.attention_fn.triton_paged", os.environ["TRITON_PAGED"])
+ mod = importlib.util.module_from_spec(spec); sys.modules[spec.name] = mod; spec.loader.exec_module(mod)
+import exllamav3.modules.attention_fn.triton_paged
+TP = sys.modules["exllamav3.modules.attention_fn.triton_paged"]
+from exllamav3.modules.attention_fn.triton_paged import _get_h32
+from ref8 import pack8, dequant8
+def jit_of(x):
+ while 'Interpreted' not in type(x).__name__ and hasattr(x, 'fn'): x = x.fn
+ return x
+split = jit_of(TP._paged_attn_decode_split_kernel); comb = jit_of(TP._paged_attn_decode_combine_kernel)
+H, KVH, HD, PS, NP = 24, 2, 256, 256, 1024
+GPT = KVH * HD // 32; BITS = 8
+gen = torch.Generator().manual_seed(2)
+filled = [0, 1, 7, 255, 511, 1022, 1023]
+qk = torch.zeros(NP, PS, GPT * BITS, dtype=torch.int32); qv = torch.zeros_like(qk)
+sk = torch.zeros(NP, PS, GPT, dtype=torch.half); sv = torch.zeros_like(sk)
+for p in filled:
+ kx = (torch.randn(PS, KVH * HD, generator=gen) * torch.exp(torch.randn(1, KVH * HD, generator=gen) * 0.5)).half()
+ vx = torch.randn(PS, KVH * HD, generator=gen).half()
+ w, s = pack8(kx); qk[p], sk[p] = w, s; w, s = pack8(vx); qv[p], sv[p] = w, s
+phys = [1023, 0, 255, 7, 511, 1, 1022, 1023]
+bt = torch.tensor([phys], dtype=torch.int32); npg = bt.shape[1]
+if os.environ.get("BADBT"): bt[0, 3] = NP
+h32 = _get_h32(torch.device("cpu"))
+scale = HD ** -0.5; bad = []
+BN = max(16, 8192 // HD)
+for q_len, seqlen in ((1, 1500), (1, 7), (4, 1900), (4, 2044), (1, 255), (1, 256)):
+ kv_append = q_len # new tokens already in the cache (pre_appended_len)
+ total = seqlen + kv_append
+ block_m = triton.next_power_of_2(q_len); block_h = max(16 // block_m, 1); block_rows = block_m * block_h
+ h_blocks = triton.cdiv(H // KVH, block_h); programs = KVH * h_blocks
+ num_splits = 4; max_k = npg * PS + kv_append; split_len = triton.cdiv(triton.cdiv(max_k, num_splits), BN) * BN
+ q = torch.randn(1, q_len, H, HD, generator=gen).half()
+ po = torch.empty(programs * num_splits * block_rows * HD); pml = torch.empty(programs * num_splits * block_rows * 2)
+ o = torch.full((1, q_len, H, HD), float("nan"), dtype=torch.half)
+ cs = torch.tensor([seqlen], dtype=torch.int32); sinks = q
+ RANGES.clear()
+ for t in (q, qk, qv, sk, sv, bt, cs, po, pml, o, h32):
+ RANGES.append((t.data_ptr(), t.data_ptr() + t.numel() * t.element_size()))
+ if os.environ.get("SHORT"): RANGES[1] = (RANGES[1][0], RANGES[1][1] - PS * GPT * BITS * 4)
+ try:
+ split[(programs, num_splits)](q, qk, qv, bt, cs, o, po, pml, sk, sv, h32, split_len, npg, num_splits, sinks,
+ int(os.environ.get("KBITS", BITS)), BITS, q_len, kv_append, H, KVH, PS, HD, HD, scale, True, -1, -1, 0.0, False, False, block_m, block_h, block_rows, BN)
+ comb[(programs,)](po, pml, o, h32, num_splits, sinks, BITS, False, q_len, H, KVH, HD, HD, block_m, block_h, block_rows)
+ except Exception as e:
+ bad.append(f"q_len {q_len} len {seqlen}: kernel aborted: {str(e)[:90]}"); continue
+ if os.environ.get('BADBT'): continue
+ rowsel = torch.arange(total); rows = bt[0][rowsel // PS].long() * PS + rowsel % PS
+ kf = dequant8(qk.view(-1, GPT * BITS)[rows], sk.view(-1, GPT)[rows]).view(-1, KVH, HD)
+ vf = dequant8(qv.view(-1, GPT * BITS)[rows], sv.view(-1, GPT)[rows]).view(-1, KVH, HD)
+ err = 0.0; mag = 1e-9
+ for i in range(q_len):
+ qa = total - q_len + i
+ for h in range(H):
+ kv = h // (H // KVH)
+ sc = (kf[:qa + 1, kv] @ q[0, i, h].float()) * scale
+ ref = torch.softmax(sc, 0) @ vf[:qa + 1, kv]
+ err = max(err, (o[0, i, h].float() - ref).abs().max().item()); mag = max(mag, ref.abs().max().item())
+ print(f"q_len {q_len} len {seqlen}: max err {err:.2e} (rel {err / mag:.2e})", flush=True)
+ if torch.isnan(o.float()).any() or err / mag > 3e-3: bad.append(f"q_len {q_len} len {seqlen}: mismatch rel {err / mag:.2e}")
+bad += sorted(set(VIOL))[:6]
+print(f"[{MUT or 'baseline'}]", "VIOLATIONS" if bad else "CLEAN"); [print(" ", b) for b in bad[:12]]
+sys.exit(1 if bad else 0)
diff --git a/tools/qwen/cache8/interp_dq8.py b/tools/qwen/cache8/interp_dq8.py
new file mode 100644
index 0000000..cb13d4f
--- /dev/null
+++ b/tools/qwen/cache8/interp_dq8.py
@@ -0,0 +1,69 @@
+"""CPU proof (Triton interpreter) of dequant8_pages: every load/store inside its tensor, output bit-identical to the torch reference, with hostile block tables (negative, past the end).
+usage: TREE=<worktree> [MUT=name] python interp_dq8.py"""
+import os, sys
+os.environ["TRITON_INTERPRET"] = "1"; os.environ["HIP_VISIBLE_DEVICES"] = "-1"
+TREE = os.environ["TREE"]; sys.path.insert(0, TREE)
+import numpy as np, torch
+import triton.runtime.interpreter as _I
+torch.set_num_threads(2)
+RANGES, VIOL = [], []
+def _check(ptrs, mask, what):
+ p = np.asarray(ptrs.data).astype(np.uint64); m = np.asarray(mask.data).astype(bool) if mask is not None else np.ones(p.shape, bool)
+ sel = p[m]
+ if sel.size == 0: return
+ ok = np.zeros(sel.shape, bool)
+ for lo, hi in RANGES: ok |= (sel >= lo) & (sel < hi)
+ if not ok.all():
+ VIOL.append(f"{what}: {int((~ok).sum())} accesses outside every tensor"); raise RuntimeError("bounds violation")
+Bd = _I.InterpreterBuilder
+_ml, _ms, _l, _s = Bd.create_masked_load, Bd.create_masked_store, Bd.create_load, Bd.create_store
+Bd.create_masked_load = lambda self, p, m, o, *a: (_check(p, m, "load"), _ml(self, p, m, o, *a))[1]
+Bd.create_masked_store = lambda self, p, v, m, *a: (_check(p, m, "store"), _ms(self, p, v, m, *a))[1]
+Bd.create_load = lambda self, p, *a: (_check(p, None, "load1"), _l(self, p, *a))[1]
+Bd.create_store = lambda self, p, v, *a: (_check(p, None, "store1"), _s(self, p, v, *a))[1]
+import importlib.util
+HERE = os.path.dirname(os.path.abspath(__file__))
+src = open(os.path.join(TREE, "exllamav3/modules/attention_fn/qdeq_triton.py")).read()
+MUT = os.environ.get("MUT", "")
+muts = {
+ "src_stride": ("src = (page * 256 + tok) * 512 + offs", "src = (page * 256 + tok) * 511 + offs"),
+ "scale_idx": ("offs // 32", "offs // 16"),
+ "scale_stride": ("sidx = (page * 256 + tok) * 16 +", "sidx = (page * 256 + tok) * 17 +"),
+ "dst_page": ("dst = (j.to(tl.int64) * 256 + tok)", "dst = ((j.to(tl.int64) + 1) * 256 + tok)"),
+ "no_clamp": ("tl.minimum(tl.maximum(tl.load(btable + j), 0), P - 1)", "tl.load(btable + j)"),
+ "clamp_high": ("tl.minimum(tl.maximum(tl.load(btable + j), 0), P - 1)", "tl.minimum(tl.maximum(tl.load(btable + j), 0), P)"),
+ "midpoint": ("(ck - 127.5)", "(ck - 127.0)"),
+ "v_from_k": ("cv = tl.load(qv + src)", "cv = tl.load(qk + src)"),
+ "tok_overrun": ("tok = (tb * TBc + tl.arange(0, TBc))[:, None].to(tl.int64)", "tok = (tb * TBc + 1 + tl.arange(0, TBc))[:, None].to(tl.int64)"),
+}
+if MUT:
+ a, b = muts[MUT]; assert a in src; src = src.replace(a, b)
+src = src.replace("from .qwrite_triton import _h32_stage", "from qwrite_triton import _h32_stage")
+sys.path.insert(0, os.path.join(TREE, "exllamav3/modules/attention_fn"))
+open(os.path.join(HERE, "_dq_mut.py"), "w").write(src)
+spec = importlib.util.spec_from_file_location("dqm", os.path.join(HERE, "_dq_mut.py"))
+mod = importlib.util.module_from_spec(spec); spec.loader.exec_module(mod)
+def ref(q, s, pages):
+ P = q.shape[0]; out = []
+ for pg in pages.tolist():
+ pg = min(max(pg, 0), P - 1)
+ c = q[pg].view(torch.uint8).float(); sc = s[pg].float().repeat_interleave(32, dim=-1) # (256, 512)
+ out.append(((c.view(256, 512) - 127.5) * (sc / 128.0)).half().view(256, 2, 256))
+ return torch.cat(out, 0)
+gen = torch.Generator().manual_seed(3)
+P = 6
+qk = torch.randint(-2**31, 2**31 - 1, (P, 256, 128), generator=gen, dtype=torch.int32); qv = torch.randint(-2**31, 2**31 - 1, (P, 256, 128), generator=gen, dtype=torch.int32)
+sk = (torch.rand(P, 256, 16, generator=gen) * 4 + 1e-3).half(); sv = (torch.rand(P, 256, 16, generator=gen) * 4 + 1e-3).half()
+res = []
+try:
+ for pages in ([3, 0, 5], [-3, 9, 2, 4], [1]):
+ pg = torch.tensor(pages, dtype=torch.int32); n = len(pages)
+ ok_ = torch.full((n * 256 + 7, 2, 256), 7.0, dtype=torch.half); ov = ok_.clone() # +7 spare rows must stay untouched
+ RANGES.clear()
+ for t in (qk, qv, sk, sv, ok_, ov, pg): RANGES.append((t.data_ptr(), t.data_ptr() + t.numel() * t.element_size()))
+ mod._deq8_kernel[(n, 256 // mod.TB)](qk.view(torch.uint8), sk, qv.view(torch.uint8), sv, ok_, ov, pg, P, TBc=mod.TB, num_warps=4)
+ rk, rv = ref(qk, sk, pg), ref(qv, sv, pg)
+ res.append(torch.equal(ok_[: n * 256], rk) and torch.equal(ov[: n * 256], rv) and bool((ok_[n * 256:] == 7).all()) and bool((ov[n * 256:] == 7).all()))
+ print("RESULT", "OK identical" if all(res) else f"MISMATCH {res}", "VIOL", VIOL)
+except Exception as e:
+ print("RESULT", "VIOLATION" if VIOL else f"ERROR {e!r}", VIOL)
diff --git a/tools/qwen/cache8/interp_dqf8.py b/tools/qwen/cache8/interp_dqf8.py
new file mode 100644
index 0000000..981e2e7
--- /dev/null
+++ b/tools/qwen/cache8/interp_dqf8.py
@@ -0,0 +1,71 @@
+"""CPU proof (Triton interpreter) of dequant8_full: loads/stores inside their tensors (hostile block tables), output bit-identical to ext_fallbacks.dequant_cache_cont.
+usage: TREE=<worktree> [MUT=name] python interp_dqf8.py"""
+import os, sys
+os.environ["TRITON_INTERPRET"] = "1"; os.environ["HIP_VISIBLE_DEVICES"] = "-1"
+TREE = os.environ["TREE"]; sys.path.insert(0, TREE)
+import numpy as np, torch
+import triton.runtime.interpreter as _I
+torch.set_num_threads(2)
+RANGES, VIOL = [], []
+def _check(ptrs, mask, what):
+ p = np.asarray(ptrs.data).astype(np.uint64); m = np.asarray(mask.data).astype(bool) if mask is not None else np.ones(p.shape, bool)
+ sel = p[m]
+ if sel.size == 0: return
+ ok = np.zeros(sel.shape, bool)
+ for lo, hi in RANGES: ok |= (sel >= lo) & (sel < hi)
+ if not ok.all():
+ VIOL.append(f"{what}: {int((~ok).sum())} accesses outside every tensor"); raise RuntimeError("bounds violation")
+Bd = _I.InterpreterBuilder
+_ml, _ms, _l, _s = Bd.create_masked_load, Bd.create_masked_store, Bd.create_load, Bd.create_store
+Bd.create_masked_load = lambda self, p, m, o, *a: (_check(p, m, "load"), _ml(self, p, m, o, *a))[1]
+Bd.create_masked_store = lambda self, p, v, m, *a: (_check(p, m, "store"), _ms(self, p, v, m, *a))[1]
+Bd.create_load = lambda self, p, *a: (_check(p, None, "load1"), _l(self, p, *a))[1]
+Bd.create_store = lambda self, p, v, *a: (_check(p, None, "store1"), _s(self, p, v, *a))[1]
+import importlib.util
+HERE = os.path.dirname(os.path.abspath(__file__))
+d = os.path.join(TREE, "exllamav3/modules/attention_fn")
+src = open(os.path.join(d, "qdeq_triton.py")).read()
+MUT = os.environ.get("MUT", "")
+muts = {
+ "src_stride": ("src = ((page * 256 + tok) * G + grp) * 32 + lane", "src = ((page * 256 + tok) * G + grp) * 33 + lane"),
+ "scale_idx": ("sidx = (page * 256 + tok) * G + grp", "sidx = (page * 256 + tok) * G + grp + 1"),
+ "dst_page": ("dst = ((j.to(tl.int64) * 256 + tok) * G + grp) * 32 + lane", "dst = (((j.to(tl.int64) + 1) * 256 + tok) * G + grp) * 32 + lane"),
+ "no_clamp": ("tl.minimum(tl.maximum(tl.load(btable + j), 0), P - 1).to(tl.int64)\n tok = (tb * TBc + tl.arange(0, TBc))[:, None, None]", "tl.load(btable + j).to(tl.int64)\n tok = (tb * TBc + tl.arange(0, TBc))[:, None, None]"),
+ "midpoint": ("(c - 127.5)", "(c - 127.0)"),
+ "stage_missing": (" x = _h32_stage(x, TBc * G, 16)\n", ""),
+ "v_from_k": ("c = tl.load(qv + src).to(tl.float32)", "c = tl.load(qk + src).to(tl.float32)"),
+ "tok_overrun": ("tok = (tb * TBc + tl.arange(0, TBc))[:, None, None].to(tl.int64)", "tok = (tb * TBc + 1 + tl.arange(0, TBc))[:, None, None].to(tl.int64)"),
+}
+if MUT:
+ a, b = muts[MUT]
+ if a not in src: raise SystemExit(f"mutation {MUT} does not apply")
+ src = src.replace(a, b)
+src = src.replace("from .qwrite_triton import _h32_stage", "from qwrite_triton import _h32_stage")
+sys.path.insert(0, d)
+open(os.path.join(HERE, "_dqf_mut.py"), "w").write(src)
+spec = importlib.util.spec_from_file_location("dqfm", os.path.join(HERE, "_dqf_mut.py"))
+mod = importlib.util.module_from_spec(spec); spec.loader.exec_module(mod)
+from exllamav3.ext_fallbacks import dequant_cache_cont
+G = 16; P = 5
+gen = torch.Generator().manual_seed(7)
+qk = torch.randint(-2**31, 2**31 - 1, (P, 256, G * 8), generator=gen, dtype=torch.int32); qv = torch.randint(-2**31, 2**31 - 1, (P, 256, G * 8), generator=gen, dtype=torch.int32)
+sk = (torch.rand(P, 256, G, generator=gen) * 4 + 1e-3).half(); sv = (torch.rand(P, 256, G, generator=gen) * 4 + 1e-3).half()
+def ref(q, s, pages):
+ out = []
+ for pg in pages.tolist():
+ pg = min(max(pg, 0), P - 1); o = torch.empty(256, G * 32, dtype=torch.half)
+ dequant_cache_cont(q[pg].contiguous(), s[pg].contiguous(), o, 0.0); out.append(o)
+ return torch.cat(out, 0)
+res = []
+try:
+ for pages in ([3, 0], [-2, 7, 1], [4]):
+ pg = torch.tensor(pages, dtype=torch.int32); n = len(pages)
+ ok_ = torch.full((n * 256 + 5, G * 32), 7.0, dtype=torch.half); ov = ok_.clone()
+ RANGES.clear()
+ for t in (qk, qv, sk, sv, ok_, ov, pg): RANGES.append((t.data_ptr(), t.data_ptr() + t.numel() * t.element_size()))
+ mod._deqfull8_kernel[(n, 64)](qk.view(torch.uint8), sk, qv.view(torch.uint8), sv, ok_, ov, pg, P, TBc=4, G=G)
+ rk, rv = ref(qk, sk, pg), ref(qv, sv, pg)
+ res.append(torch.equal(ok_[: n * 256], rk) and torch.equal(ov[: n * 256], rv) and bool((ok_[n * 256:] == 7).all()) and bool((ov[n * 256:] == 7).all()))
+ print("RESULT", "OK identical" if all(res) else f"MISMATCH {res}", "VIOL", VIOL)
+except Exception as e:
+ print("RESULT", "VIOLATION" if VIOL else f"ERROR {e!r}", VIOL)
diff --git a/tools/qwen/cache8/interp_qsa8.py b/tools/qwen/cache8/interp_qsa8.py
new file mode 100644
index 0000000..4f7e945
--- /dev/null
+++ b/tools/qwen/cache8/interp_qsa8.py
@@ -0,0 +1,108 @@
+"""CPU proof (Triton interpreter = the kernel body executed on CPU) of the 8-bit packed-cache read path of the QSA gather kernel
+(_qsa_sparse_split_kernel + _paged_attn_decode_combine_kernel, loaders _qc_load_kt/_qc_load_v) at the real Qwen geometry
+(24 q heads, 2 kv heads, head_dim 256, page 256, K_pad 2080, pool of 1024 pages = 262144 tokens).
+Checks: every masked-in pointer inside the exact tensor ranges (bounds), output == torch attention on the dequantised K/V.
+usage: TREE=<worktree> [TRITON_PAGED=<mutated triton_paged.py>] [MUT=name] python interp_qsa8.py"""
+import os, sys, importlib.util
+os.environ["TRITON_INTERPRET"] = "1"; os.environ["HIP_VISIBLE_DEVICES"] = "-1"
+TREE = os.environ["TREE"]; sys.path.insert(0, TREE); sys.path.insert(0, os.path.dirname(__file__))
+import numpy as np, torch, triton
+import triton.runtime.interpreter as _I
+_orig_patch = _I._patch_lang_tensor
+def _patch(tensor, scope):
+ _orig_patch(tensor, scope)
+ scope.set_attr(tensor, "__index__", lambda self: int(np.asarray(self.handle.data).reshape(-1)[0]))
+ scope.set_attr(tensor, "__bool__", lambda self: bool(np.asarray(self.handle.data).reshape(-1)[0]))
+_I._patch_lang_tensor = _patch
+torch.set_num_threads(2)
+RANGES, VIOL = [], []
+def _check(ptrs, mask, what):
+ p = np.asarray(ptrs.data).astype(np.uint64); m = np.asarray(mask.data).astype(bool) if mask is not None else np.ones(p.shape, bool)
+ sel = p[m]
+ if sel.size == 0: return
+ ok = np.zeros(sel.shape, bool)
+ for lo, hi in RANGES: ok |= (sel >= lo) & (sel < hi)
+ if not ok.all():
+ VIOL.append(f"{what}: {int((~ok).sum())} masked-in accesses outside every tensor"); raise RuntimeError("bounds violation")
+Bd = _I.InterpreterBuilder
+_ml, _ms, _l, _s = Bd.create_masked_load, Bd.create_masked_store, Bd.create_load, Bd.create_store
+def _ml2(self, ptrs, mask, other, *a): _check(ptrs, mask, "load"); return _ml(self, ptrs, mask, other, *a)
+def _ms2(self, ptrs, value, mask, *a): _check(ptrs, mask, "store"); return _ms(self, ptrs, value, mask, *a)
+def _l2(self, ptr, *a): _check(ptr, None, "load1"); return _l(self, ptr, *a)
+def _s2(self, ptr, val, *a): _check(ptr, None, "store1"); return _s(self, ptr, val, *a)
+Bd.create_masked_load, Bd.create_masked_store, Bd.create_load, Bd.create_store = _ml2, _ms2, _l2, _s2
+MUT = os.environ.get("MUT", "")
+if os.environ.get("TRITON_PAGED"): # mutated copy of triton_paged.py replaces the module before qsa_triton imports its loaders
+ import exllamav3.modules.attention_fn as pkg
+ spec = importlib.util.spec_from_file_location("exllamav3.modules.attention_fn.triton_paged", os.environ["TRITON_PAGED"])
+ mod = importlib.util.module_from_spec(spec); sys.modules[spec.name] = mod; spec.loader.exec_module(mod)
+import exllamav3.modules.attention_fn.qsa_triton as Q
+from exllamav3.modules.attention_fn.triton_paged import _paged_attn_decode_combine_kernel, _get_h32
+from ref8 import pack8, dequant8
+def jit_of(x):
+ while 'Interpreted' not in type(x).__name__ and hasattr(x, 'fn'): x = x.fn
+ return x
+split = jit_of(Q._qsa_sparse_split_kernel); comb = jit_of(_paged_attn_decode_combine_kernel)
+H, KVH, HD, PS, KPAD, NP = 24, 2, 256, 256, 2080, 1024
+GPT = KVH * HD // 32; BITS = 8
+bad = []
+gen = torch.Generator().manual_seed(1)
+R = 2
+filled = [0, 1, 7, 255, 511, 1022, 1023] # pages that carry data; the others stay zero words / zero scales
+qk = torch.zeros(NP, PS, GPT * BITS, dtype=torch.int32); qv = torch.zeros_like(qk)
+sk = torch.zeros(NP, PS, GPT, dtype=torch.half); sv = torch.zeros_like(sk)
+Kt = torch.zeros(NP, PS, KVH * HD); Vt = torch.zeros_like(Kt)
+for p in filled:
+ kx = (torch.randn(PS, KVH * HD, generator=gen) * torch.exp(torch.randn(1, KVH * HD, generator=gen) * 0.5)).half()
+ vx = torch.randn(PS, KVH * HD, generator=gen).half()
+ w, s = pack8(kx); qk[p], sk[p] = w, s; w, s = pack8(vx); qv[p], sv[p] = w, s
+# block table: logical page i -> physical page; 8 logical pages cover positions 0..2047
+phys = [1023, 0, 255, 7, 511, 1, 1022, 255 if False else 1023]
+bt = torch.tensor([phys, phys], dtype=torch.int32)
+npg = bt.shape[1]
+# index lists: R rows, each K_pad wide, positions < 8*256, -1 padded tail (like the real selector)
+idx = torch.full((R, KPAD), -1, dtype=torch.int32)
+for r in range(R):
+ n = 1500 + 300 * r
+ idx[r, :n] = torch.randperm(npg * PS, generator=gen)[:n].int()
+q = torch.randn(R, H, HD, generator=gen).half()
+scale = HD ** -0.5
+h32 = _get_h32(torch.device("cpu"))
+BN = Q._QSA_BN; BH = 16
+splits, split_len = Q.qsa_split_plan(R, KVH * 1, KPAD, BN, 16)
+programs = R * KVH * 1
+po = torch.empty(programs * splits * BH * HD); pml = torch.empty(programs * splits * BH * 2)
+o = torch.full((R, H, HD), float("nan"), dtype=torch.half)
+if os.environ.get("BADBT"): bt[0, 0] = NP # block table points one page past the pool
+for t in (q, qk, qv, sk, sv, bt, idx, po, pml, o, h32):
+ RANGES.append((t.data_ptr(), t.data_ptr() + t.numel() * t.element_size()))
+if os.environ.get("SHORT"): # cache allocated one page short of what the table references
+ RANGES[1] = (RANGES[1][0], RANGES[1][1] - PS * GPT * BITS * 4)
+try:
+ kbits = int(os.environ.get("KBITS", BITS))
+ split[(programs, splits)](q, qk, qv, bt, idx, po, pml, KPAD, npg, splits, split_len, sk, sv, h32,
+ n_q_heads=H, n_kv_heads=KVH, page_size=PS, head_dim=HD, K_pad=KPAD, scale=scale, BLOCK_H=BH, BLOCK_N=BN, PAGED=1, QCK=kbits, QCV=BITS)
+ comb[(programs,)](po, pml, o, h32, splits, pml, QCV=BITS, HAS_SINKS=False, q_len=1, n_q_heads=H, n_kv_heads=KVH,
+ head_dim=HD, HD_PAD=HD, BLOCK_M=1, BLOCK_H=BH, BLOCK_ROWS=BH)
+except Exception as e:
+ bad.append(f"kernel aborted: {str(e)[:100]}")
+if os.environ.get('BADBT'):
+ print('[BADBT]', 'VIOLATIONS' if bad or VIOL else 'CLEAN', bad, VIOL[:2]); sys.exit(1 if bad or VIOL else 0)
+# reference: gather dequantised K/V of the selected positions, plain softmax attention
+ref = torch.zeros(R, H, HD)
+for r in range(R):
+ sel = idx[r][idx[r] >= 0].long()
+ rows = bt[r][sel // PS].long() * PS + sel % PS
+ kf = dequant8(qk.view(-1, GPT * BITS)[rows], sk.view(-1, GPT)[rows]).view(-1, KVH, HD)
+ vf = dequant8(qv.view(-1, GPT * BITS)[rows], sv.view(-1, GPT)[rows]).view(-1, KVH, HD)
+ for h in range(H):
+ kv = h // (H // KVH)
+ sc = (kf[:, kv] @ q[r, h].float()) * scale
+ ref[r, h] = torch.softmax(sc, 0) @ vf[:, kv]
+err = (o.float() - ref).abs().max().item(); mag = ref.abs().max().item()
+print(f"max |kernel - reference| = {err:.3e} (reference max {mag:.3f}, rel {err / mag:.2e}) splits={splits} programs={programs}")
+if not (err / mag < 3e-3): bad.append(f"kernel != reference (rel {err / mag:.2e})")
+if torch.isnan(o.float()).any(): bad.append("NaN in output")
+bad += sorted(set(VIOL))[:6]
+print(f"[{MUT or 'baseline'}]", "VIOLATIONS" if bad else "CLEAN"); [print(" ", b) for b in bad[:12]]
+sys.exit(1 if bad else 0)
diff --git a/tools/qwen/cache8/interp_qw8.py b/tools/qwen/cache8/interp_qw8.py
new file mode 100644
index 0000000..fc706a0
--- /dev/null
+++ b/tools/qwen/cache8/interp_qw8.py
@@ -0,0 +1,70 @@
+"""CPU proof (Triton interpreter) of the native 8-bit paged cache writer: every masked-in pointer inside its tensor,
+output words/scales bit-identical to the torch fallback. usage: TREE=<worktree> [MUT=name] python interp_qw8.py"""
+import os, sys, re
+os.environ["TRITON_INTERPRET"] = "1"; os.environ["HIP_VISIBLE_DEVICES"] = "-1"
+TREE = os.environ["TREE"]; sys.path.insert(0, TREE)
+import numpy as np, torch
+import triton.runtime.interpreter as _I
+torch.set_num_threads(2)
+RANGES, VIOL = [], []
+def _check(ptrs, mask, what):
+ p = np.asarray(ptrs.data).astype(np.uint64); m = np.asarray(mask.data).astype(bool) if mask is not None else np.ones(p.shape, bool)
+ sel = p[m]
+ if sel.size == 0: return
+ ok = np.zeros(sel.shape, bool)
+ for lo, hi in RANGES: ok |= (sel >= lo) & (sel < hi)
+ if not ok.all():
+ VIOL.append(f"{what}: {int((~ok).sum())} accesses outside every tensor"); raise RuntimeError("bounds violation")
+Bd = _I.InterpreterBuilder
+_ml, _ms, _l, _s = Bd.create_masked_load, Bd.create_masked_store, Bd.create_load, Bd.create_store
+Bd.create_masked_load = lambda self, p, m, o, *a: (_check(p, m, "load"), _ml(self, p, m, o, *a))[1]
+Bd.create_masked_store = lambda self, p, v, m, *a: (_check(p, m, "store"), _ms(self, p, v, m, *a))[1]
+Bd.create_load = lambda self, p, *a: (_check(p, None, "load1"), _l(self, p, *a))[1]
+Bd.create_store = lambda self, p, v, *a: (_check(p, None, "store1"), _s(self, p, v, *a))[1]
+import importlib.util
+src = open(os.path.join(TREE, "exllamav3/modules/attention_fn/qwrite_triton.py")).read()
+MUT = os.environ.get("MUT", "")
+muts = {
+ "src_stride": ("src * (G * 32)", "src * (G * 32 + 32)"),
+ "dst_stride": ("dst * (G * 8) + og", "dst * (G * 8 + 8) + og"),
+ "scale_stride": ("sc + dst * G +", "sc + dst * (G + 1) +"),
+ "page": ("tok // 256)", "tok // 256 + 1)"),
+ "midpoint": ("v * 128.0 + 128.0", "v * 128.0 + 127.0"),
+ "shift": ("tl.arange(0, 4) * 8", "tl.arange(0, 4) * 4"),
+}
+if MUT:
+ a, b = muts[MUT]; assert a in src; src = src.replace(a, b)
+open(os.path.join(os.path.dirname(__file__), "_qw_mut.py"), "w").write(src)
+spec = importlib.util.spec_from_file_location("qwm", os.path.join(os.path.dirname(__file__), "_qw_mut.py"))
+mod = importlib.util.module_from_spec(spec); spec.loader.exec_module(mod)
+from exllamav3 import ext_fallbacks as fb
+from exllamav3.ext_fallbacks import _quant_cache_paged_torch
+def run(bsz, seq_len, seqlens, contig, npages=8, dim=512):
+ G = dim // 32
+ bt = torch.arange(npages, dtype=torch.int32).flip(0)[:bsz * 3].reshape(bsz, 3).contiguous() if bsz * 3 <= npages else None
+ gen = torch.Generator().manual_seed(5)
+ n = bsz * seq_len if contig else npages * 256
+ k = (torch.randn(n, dim, generator=gen) * torch.exp(torch.randn(1, dim, generator=gen))).half().contiguous()
+ v = torch.randn(n, dim, generator=gen).half().contiguous()
+ shp = (bsz, seq_len, dim) if contig else (npages, 256, dim)
+ k = k.view(shp); v = v.view(shp)
+ cs = torch.tensor(seqlens, dtype=torch.int32)
+ outs = []
+ for impl in (0, 1):
+ ko = torch.zeros(npages, 256, G * 8, dtype=torch.int32); vo = torch.zeros_like(ko)
+ ks = torch.zeros(npages, 256, G, dtype=torch.half); vs = torch.zeros_like(ks)
+ if impl == 0:
+ _quant_cache_paged_torch(k, ko, ks, v, vo, vs, cs, bt, 256, seq_len, 0.0, contig)
+ else:
+ RANGES.clear()
+ for t in (k, v, ko, vo, ks, vs, cs, bt): RANGES.append((t.data_ptr(), t.data_ptr() + t.numel() * t.element_size()))
+ mod._quant_cache_paged8_kernel[(bsz * seq_len,)](k, v, ko, vo, ks, vs, cs, bt, seq_len, bt.shape[1], in_contig=contig, G=G)
+ outs.append((ko, vo, ks, vs))
+ return all(torch.equal(a, b) for a, b in zip(*outs))
+res = []
+try:
+ res.append(run(1, 1, [255], True)); res.append(run(1, 4, [254], True)); res.append(run(2, 3, [10, 700], True))
+ res.append(run(1, 5, [0], False)); res.append(run(2, 1, [255, 256], False))
+ print("RESULT", "OK identical" if all(res) else f"MISMATCH {res}", "VIOL", VIOL)
+except Exception as e:
+ print("RESULT", "VIOLATION" if VIOL else f"ERROR {e!r}", VIOL)
diff --git a/tools/qwen/cache8/interp_rot32.py b/tools/qwen/cache8/interp_rot32.py
new file mode 100644
index 0000000..cd0a008
--- /dev/null
+++ b/tools/qwen/cache8/interp_rot32.py
@@ -0,0 +1,58 @@
+"""CPU proof (Triton interpreter) of rot32: all accesses inside their tensors (tail rows masked), output bit-identical to the fp32 butterfly reference.
+usage: TREE=<worktree> [MUT=name] python interp_rot32.py"""
+import os, sys
+os.environ["TRITON_INTERPRET"] = "1"; os.environ["HIP_VISIBLE_DEVICES"] = "-1"
+TREE = os.environ["TREE"]; sys.path.insert(0, TREE)
+import numpy as np, torch
+import triton.runtime.interpreter as _I
+torch.set_num_threads(2)
+RANGES, VIOL = [], []
+def _check(ptrs, mask, what):
+ p = np.asarray(ptrs.data).astype(np.uint64); m = np.asarray(mask.data).astype(bool) if mask is not None else np.ones(p.shape, bool)
+ sel = p[m]
+ if sel.size == 0: return
+ ok = np.zeros(sel.shape, bool)
+ for lo, hi in RANGES: ok |= (sel >= lo) & (sel < hi)
+ if not ok.all():
+ VIOL.append(f"{what}: {int((~ok).sum())} accesses outside every tensor"); raise RuntimeError("bounds violation")
+Bd = _I.InterpreterBuilder
+_ml, _ms, _l, _s = Bd.create_masked_load, Bd.create_masked_store, Bd.create_load, Bd.create_store
+Bd.create_masked_load = lambda self, p, m, o, *a: (_check(p, m, "load"), _ml(self, p, m, o, *a))[1]
+Bd.create_masked_store = lambda self, p, v, m, *a: (_check(p, m, "store"), _ms(self, p, v, m, *a))[1]
+Bd.create_load = lambda self, p, *a: (_check(p, None, "load1"), _l(self, p, *a))[1]
+Bd.create_store = lambda self, p, v, *a: (_check(p, None, "store1"), _s(self, p, v, *a))[1]
+import importlib.util
+HERE = os.path.dirname(os.path.abspath(__file__))
+d = os.path.join(TREE, "exllamav3/modules/attention_fn")
+src = open(os.path.join(d, "qdeq_triton.py")).read()
+MUT = os.environ.get("MUT", "")
+muts = {
+ "stride": ("offs = row * 32 + tl.arange(0, 32)[None, :]", "offs = row * 33 + tl.arange(0, 32)[None, :]"),
+ "no_mask_load": ("v = tl.load(x + offs, mask=m, other=0.0)", "v = tl.load(x + offs)"),
+ "no_mask_store": ("tl.store(y + offs, (v * 0.17677669529663688).to(tl.float16), mask=m)", "tl.store(y + offs, (v * 0.17677669529663688).to(tl.float16))"),
+ "mask_off_by_one": ("m = row < n", "m = row <= n"),
+ "scale": ("v * 0.17677669529663688", "v * 0.1767767"),
+ "stage_missing": (" v = _h32_stage(v, BG, 16)\n", ""),
+}
+if MUT:
+ a, b = muts[MUT]; assert a in src; src = src.replace(a, b)
+src = src.replace("from .qwrite_triton import _h32_stage", "from qwrite_triton import _h32_stage")
+sys.path.insert(0, d)
+open(os.path.join(HERE, "_rot_mut.py"), "w").write(src)
+spec = importlib.util.spec_from_file_location("rotm", os.path.join(HERE, "_rot_mut.py"))
+mod = importlib.util.module_from_spec(spec); spec.loader.exec_module(mod)
+from exllamav3.ext_fallbacks import _hadamard32
+res = []
+try:
+ for n in (1, 63, 64, 65, 200):
+ gen = torch.Generator().manual_seed(n)
+ x = (torch.randn(n, 32, generator=gen) * torch.exp(torch.randn(n, 1, generator=gen))).half().contiguous()
+ y = torch.full((n + 70, 32), 9.0, dtype=torch.half) # spare rows must stay untouched
+ RANGES.clear()
+ for t in (x, y): RANGES.append((t.data_ptr(), t.data_ptr() + t.numel() * t.element_size()))
+ mod._rot32_kernel[((n + 63) // 64,)](x, y, n, BG=64)
+ ref = (_hadamard32(x.float()) * torch.scalar_tensor(0.17677669529663688109, dtype=torch.float32)).half()
+ res.append(torch.equal(y[:n], ref) and bool((y[n:] == 9).all()))
+ print("RESULT", "OK identical" if all(res) else f"MISMATCH {res}", "VIOL", VIOL)
+except Exception as e:
+ print("RESULT", "VIOLATION" if VIOL else f"ERROR {e!r}", VIOL)
diff --git a/tools/qwen/cache8/interp_wrap8.py b/tools/qwen/cache8/interp_wrap8.py
new file mode 100644
index 0000000..0d570fb
--- /dev/null
+++ b/tools/qwen/cache8/interp_wrap8.py
@@ -0,0 +1,101 @@
+"""(decode split + combine kernels, q_len 1 and 4) CPU proof (Triton interpreter = the kernel body executed on CPU) of the 8-bit packed-cache read path of the QSA gather kernel
+(_qsa_sparse_split_kernel + _paged_attn_decode_combine_kernel, loaders _qc_load_kt/_qc_load_v) at the real Qwen geometry
+(24 q heads, 2 kv heads, head_dim 256, page 256, K_pad 2080, pool of 1024 pages = 262144 tokens).
+Checks: every masked-in pointer inside the exact tensor ranges (bounds), output == torch attention on the dequantised K/V.
+usage: TREE=<worktree> [TRITON_PAGED=<mutated triton_paged.py>] [MUT=name] python interp_qsa8.py"""
+import os, sys, importlib.util
+os.environ["TRITON_INTERPRET"] = "1"; os.environ["HIP_VISIBLE_DEVICES"] = "-1"
+TREE = os.environ["TREE"]; sys.path.insert(0, TREE); sys.path.insert(0, os.path.dirname(__file__))
+import numpy as np, torch, triton
+import triton.runtime.interpreter as _I
+_orig_patch = _I._patch_lang_tensor
+def _patch(tensor, scope):
+ _orig_patch(tensor, scope)
+ scope.set_attr(tensor, "__index__", lambda self: int(np.asarray(self.handle.data).reshape(-1)[0]))
+ scope.set_attr(tensor, "__bool__", lambda self: bool(np.asarray(self.handle.data).reshape(-1)[0]))
+_I._patch_lang_tensor = _patch
+torch.set_num_threads(2)
+RANGES, VIOL = [], []
+def _check(ptrs, mask, what):
+ p = np.asarray(ptrs.data).astype(np.uint64); m = np.asarray(mask.data).astype(bool) if mask is not None else np.ones(p.shape, bool)
+ sel = p[m]
+ if sel.size == 0: return
+ ok = np.zeros(sel.shape, bool)
+ for lo, hi in RANGES: ok |= (sel >= lo) & (sel < hi)
+ if not ok.all():
+ VIOL.append(f"{what}: {int((~ok).sum())} masked-in accesses outside every tensor"); raise RuntimeError("bounds violation")
+Bd = _I.InterpreterBuilder
+_ml, _ms, _l, _s = Bd.create_masked_load, Bd.create_masked_store, Bd.create_load, Bd.create_store
+def _ml2(self, ptrs, mask, other, *a): _check(ptrs, mask, "load"); return _ml(self, ptrs, mask, other, *a)
+def _ms2(self, ptrs, value, mask, *a): _check(ptrs, mask, "store"); return _ms(self, ptrs, value, mask, *a)
+def _l2(self, ptr, *a): _check(ptr, None, "load1"); return _l(self, ptr, *a)
+def _s2(self, ptr, val, *a): _check(ptr, None, "store1"); return _s(self, ptr, val, *a)
+Bd.create_masked_load, Bd.create_masked_store, Bd.create_load, Bd.create_store = _ml2, _ms2, _l2, _s2
+MUT = os.environ.get("MUT", "")
+if os.environ.get("TRITON_PAGED"): # mutated copy of triton_paged.py replaces the module before qsa_triton imports its loaders
+ import exllamav3.modules.attention_fn as pkg
+ spec = importlib.util.spec_from_file_location("exllamav3.modules.attention_fn.triton_paged", os.environ["TRITON_PAGED"])
+ mod = importlib.util.module_from_spec(spec); sys.modules[spec.name] = mod; spec.loader.exec_module(mod)
+import contextlib
+import exllamav3.modules.attention_fn.triton_paged
+TP = sys.modules["exllamav3.modules.attention_fn.triton_paged"]
+from exllamav3.modules.attention_fn.triton_paged import _get_h32
+from ref8 import pack8, dequant8
+TP._check_tensor = lambda *a, **k: None # CPU harness: the wrappers insist on CUDA tensors
+torch.cuda.device = lambda d: contextlib.nullcontext()
+class _P: multi_processor_count = 16; major = 11; minor = 5
+torch.cuda.get_device_properties = lambda d: _P()
+torch.cuda.get_device_capability = lambda d: (11, 5)
+H, KVH, HD, PS, NP = 24, 2, 256, 256, 1024
+GPT = KVH * HD // 32; BITS = 8
+gen = torch.Generator().manual_seed(3)
+filled = [0, 1, 7, 255, 511, 1022, 1023]
+qk = torch.zeros(NP, PS, GPT * BITS, dtype=torch.int32); qv = torch.zeros_like(qk)
+sk = torch.zeros(NP, PS, GPT, dtype=torch.half); sv = torch.zeros_like(sk)
+for p in filled:
+ kx = (torch.randn(PS, KVH * HD, generator=gen) * torch.exp(torch.randn(1, KVH * HD, generator=gen) * 0.5)).half()
+ vx = torch.randn(PS, KVH * HD, generator=gen).half()
+ w, s = pack8(kx); qk[p], sk[p] = w, s; w, s = pack8(vx); qv[p], sv[p] = w, s
+phys = [1023, 0, 255, 7, 511, 1, 1022, 1023]
+bt = torch.tensor([phys], dtype=torch.int32); npg = bt.shape[1]
+if os.environ.get("BADBT"): bt[0, 3] = NP
+h32 = _get_h32(torch.device("cpu"))
+bad = []
+MODE = os.environ.get("MODE", "both")
+for fn, q_len, seqlen in (("prefill", 64, 0), ("prefill", 100, 1500), ("prefill", 64, 1984), ("prefill", 33, 300), ("decode", 1, 1500), ("decode", 4, 1900), ("decode", 1, 2047)):
+ total = seqlen + q_len
+ q = torch.randn(1, q_len, H, HD, generator=gen).half()
+ out = torch.full((1, q_len, H, HD), float("nan"), dtype=torch.half)
+ cs = torch.tensor([seqlen], dtype=torch.int32)
+ RANGES.clear()
+ for t in (q, qk, qv, sk, sv, bt, cs, out, h32):
+ RANGES.append((t.data_ptr(), t.data_ptr() + t.numel() * t.element_size()))
+ # partial buffers allocated inside the wrapper: widen the allowed range to the whole address space of fresh tensors via a hook on torch.empty
+ _empty = torch.empty
+ def _emp(*a, **k):
+ t = _empty(*a, **k); RANGES.append((t.data_ptr(), t.data_ptr() + t.numel() * t.element_size())); return t
+ torch.empty = _emp
+ if os.environ.get("SHORT"): RANGES[1] = (RANGES[1][0], RANGES[1][1] - PS * GPT * BITS * 4)
+ try:
+ f = TP.paged_attn_triton_prefill if fn == "prefill" else TP.paged_attn_triton_decode
+ f(q, None, None, qk, qv, bt, cs, causal=True, softmax_scale=HD ** -0.5, out=out, qc=(sk, sv, BITS, BITS), pre_appended_len=q_len, n_kv_heads_override=KVH)
+ except Exception as e:
+ import traceback; traceback.print_exc(); bad.append(f"{fn} q_len {q_len} len {seqlen}: aborted: {str(e)[:110]}"); torch.empty = _empty; continue
+ torch.empty = _empty
+ if os.environ.get('BADBT'): continue
+ rowsel = torch.arange(total); rows = bt[0][rowsel // PS].long() * PS + rowsel % PS
+ kf = dequant8(qk.view(-1, GPT * BITS)[rows], sk.view(-1, GPT)[rows]).view(-1, KVH, HD)
+ vf = dequant8(qv.view(-1, GPT * BITS)[rows], sv.view(-1, GPT)[rows]).view(-1, KVH, HD)
+ err = 0.0; mag = 1e-9
+ for i in range(q_len):
+ qa = total - q_len + i
+ for h in range(H):
+ kv = h // (H // KVH)
+ sc = (kf[:qa + 1, kv] @ q[0, i, h].float()) * HD ** -0.5
+ ref = torch.softmax(sc, 0) @ vf[:qa + 1, kv]
+ err = max(err, (out[0, i, h].float() - ref).abs().max().item()); mag = max(mag, ref.abs().max().item())
+ print(f"{fn} q_len {q_len} len {seqlen}: max err {err:.2e} (rel {err / mag:.2e})", flush=True)
+ if torch.isnan(out.float()).any() or err / mag > 3e-3: bad.append(f"{fn} q_len {q_len} len {seqlen}: mismatch rel {err / mag:.2e}")
+bad += sorted(set(VIOL))[:6]
+print(f"[{MUT or 'baseline'}]", "VIOLATIONS" if bad else "CLEAN"); [print(" ", b) for b in bad[:12]]
+sys.exit(1 if bad else 0)
diff --git a/tools/qwen/cache8/mutants.sh b/tools/qwen/cache8/mutants.sh
new file mode 100755
index 0000000..358aa64
--- /dev/null
+++ b/tools/qwen/cache8/mutants.sh
@@ -0,0 +1,27 @@
+#!/bin/bash
+# mutants of the 8-bit read path (usage: TREE=<checkout> [PYTHON=<venv python>] mutants.sh [interp_qsa8.py|interp_dec8.py]); every one must report VIOLATIONS
+HERE=$(cd "$(dirname "$0")" && pwd); SCRIPT=${1:-interp_qsa8.py}; T=${TREE:?set TREE to the checkout}; SRC=$T/exllamav3/modules/attention_fn/triton_paged.py; W=${MUT_DIR:-$HERE/_mut}; mkdir -p $W; cd $HERE; export TREE=$T
+run(){ name=$1; shift; M=$W/tp_$name.py; cp $SRC $M; python3 - "$M" "$name" <<'PY'
+import sys; p, n = sys.argv[1:3]; s = open(p).read()
+muts = {
+ "kt_head_off": [(" base = kv_head * (G * BITS)\n row_words = tok_rows * (GPT * BITS)\n qh = qwords + base\n raw = tl.zeros((1, 1), tl.int32) # replaced", " base = kv_head * (G * BITS) + G * BITS\n row_words = tok_rows * (GPT * BITS)\n qh = qwords + base\n raw = tl.zeros((1, 1), tl.int32) # replaced")],
+ "v_head_off": [(" base = kv_head * (G * BITS)\n row_words = tok_rows * (GPT * BITS)\n qh = qwords + base\n raw = tl.zeros((1, 1), tl.int32)\n pbase", " base = kv_head * (G * BITS) + G * BITS\n row_words = tok_rows * (GPT * BITS)\n qh = qwords + base\n raw = tl.zeros((1, 1), tl.int32)\n pbase")],
+ "kt_scale_stride": [("sc = tl.load(scales + tok_rows[None, :] * GPT + (sgb + garr)[:, None], mask = mask_n[None, :], other = 0.0)", "sc = tl.load(scales + tok_rows[None, :] * (GPT + 1) + (sgb + garr)[:, None], mask = mask_n[None, :], other = 0.0)")],
+ "v_scale_stride": [("sc = tl.load(scales + tok_rows[:, None] * GPT + (sgb + garr)[None, :], mask = mask_n[:, None], other = 0.0)", "sc = tl.load(scales + tok_rows[:, None] * (GPT + 1) + (sgb + garr)[None, :], mask = mask_n[:, None], other = 0.0)")],
+ "row_words_stride": [(" row_words = tok_rows * (GPT * BITS)\n qh = qwords + base\n raw = tl.zeros((1, 1), tl.int32) # replaced", " row_words = tok_rows * (GPT * BITS + 1)\n qh = qwords + base\n raw = tl.zeros((1, 1), tl.int32) # replaced")],
+ "dec_tok_k": [(" tok_rows = phys * page_size + page_off\n k_tile = _qc_load_kt(k_cache, k_scales, tok_rows, kv_head, offs_d, offs_n < n_end, QCK, n_kv_heads, head_dim, HD_PAD)\n else:\n k_ptrs = k_cache + (((phys[None, :] * page_size + page_off[None, :]) * n_kv_heads + kv_head) * head_dim + offs_d[:, None])\n if HD_PAD > head_dim:\n k_tile = tl.load(k_ptrs, mask=(offs_n[None, :] < n_end) & d_mask[:, None], other=0.0)\n else:\n k_tile = tl.load(k_ptrs, mask=offs_n[None, :] < n_end, other=0.0)\n scores = tl.dot(q_tile, k_tile) * scale\n if SOFTCAP > 0.0:\n scores_scaled = scores / SOFTCAP\n scores = (2.0 / (1.0 + tl.exp(-2.0 * scores_scaled)) - 1.0) * SOFTCAP\n\n valid = valid_row[:, None] & (offs_n[None, :] < n_end)\n if CAUSAL:\n valid = valid & (offs_n[None, :] <= q_abs[:, None])\n if WINDOW_LEFT >= 0:\n valid = valid & (offs_n[None, :] >= q_abs[:, None] - WINDOW_LEFT)", " tok_rows = phys * page_size + page_off + page_size\n k_tile = _qc_load_kt(k_cache, k_scales, tok_rows, kv_head, offs_d, offs_n < n_end, QCK, n_kv_heads, head_dim, HD_PAD)\n else:\n k_ptrs = k_cache + (((phys[None, :] * page_size + page_off[None, :]) * n_kv_heads + kv_head) * head_dim + offs_d[:, None])\n if HD_PAD > head_dim:\n k_tile = tl.load(k_ptrs, mask=(offs_n[None, :] < n_end) & d_mask[:, None], other=0.0)\n else:\n k_tile = tl.load(k_ptrs, mask=offs_n[None, :] < n_end, other=0.0)\n scores = tl.dot(q_tile, k_tile) * scale\n if SOFTCAP > 0.0:\n scores_scaled = scores / SOFTCAP\n scores = (2.0 / (1.0 + tl.exp(-2.0 * scores_scaled)) - 1.0) * SOFTCAP\n\n valid = valid_row[:, None] & (offs_n[None, :] < n_end)\n if CAUSAL:\n valid = valid & (offs_n[None, :] <= q_abs[:, None])\n if WINDOW_LEFT >= 0:\n valid = valid & (offs_n[None, :] >= q_abs[:, None] - WINDOW_LEFT)")],
+ "dec_tok_v": [(" tok_rows_v = phys * page_size + page_off\n v_tile = _qc_load_v(v_cache, v_scales, tok_rows_v, kv_head, offs_d, offs_n < n_end, QCV, n_kv_heads, head_dim, HD_PAD)\n else:\n v_ptrs = v_cache + (((phys[:, None] * page_size + page_off[:, None]) * n_kv_heads + kv_head) * head_dim + offs_d[None, :])\n if HD_PAD > head_dim:\n v_tile = tl.load(v_ptrs, mask=(offs_n[:, None] < n_end) & d_mask[None, :], other=0.0)\n else:\n v_tile = tl.load(v_ptrs, mask=offs_n[:, None] < n_end, other=0.0)\n acc = acc * alpha[:, None] + tl.dot(p.to(v_tile.dtype), v_tile)\n m = m_new\n l = l_new\n\n if FINAL:", " tok_rows_v = phys * page_size + page_off + page_size\n v_tile = _qc_load_v(v_cache, v_scales, tok_rows_v, kv_head, offs_d, offs_n < n_end, QCV, n_kv_heads, head_dim, HD_PAD)\n else:\n v_ptrs = v_cache + (((phys[:, None] * page_size + page_off[:, None]) * n_kv_heads + kv_head) * head_dim + offs_d[None, :])\n if HD_PAD > head_dim:\n v_tile = tl.load(v_ptrs, mask=(offs_n[:, None] < n_end) & d_mask[None, :], other=0.0)\n else:\n v_tile = tl.load(v_ptrs, mask=offs_n[:, None] < n_end, other=0.0)\n acc = acc * alpha[:, None] + tl.dot(p.to(v_tile.dtype), v_tile)\n m = m_new\n l = l_new\n\n if FINAL:")],
+ "midpoint": [(" mh = (1 << (BITS - 1)) - 0.5\n inv_m = 1.0 / (1 << (BITS - 1))\n return ((raw.to(tl.float32) - mh) * (scx.to(tl.float32) * inv_m)).to(tl.float16)\n\n\[email protected]\ndef _qc_load_v", " mh = (1 << (BITS - 1)) - 0.0\n inv_m = 1.0 / (1 << (BITS - 1))\n return ((raw.to(tl.float32) - mh) * (scx.to(tl.float32) * inv_m)).to(tl.float16)\n\n\[email protected]\ndef _qc_load_v")],
+}
+for a, b in muts[n]:
+ assert s.count(a) == 1, f"mutation {n} did not apply uniquely ({s.count(a)})"; s = s.replace(a, b)
+open(p, "w").write(s)
+PY
+ [ $? = 0 ] || { echo "MUTANT $name: NOT APPLIED"; return; }
+ TRITON_PAGED=$M MUT=$name nice -n 19 taskset -c 0-3 ${PYTHON:-python} $SCRIPT > $W/$SCRIPT.$name.log 2>&1; rc=$?
+ echo "MUTANT $name: rc=$rc ($(grep -c . $W/$SCRIPT.$name.log) lines) $(grep -m1 -E 'VIOL|CLEAN' $W/$SCRIPT.$name.log)"
+}
+for m in $MUTS_FIRST kt_head_off v_head_off kt_scale_stride v_scale_stride row_words_stride midpoint; do run $m; done
+echo "MUTANT bad_block_table: $(BADBT=1 nice -n 19 taskset -c 0-3 ${PYTHON:-python} $SCRIPT 2>&1 | grep -m1 -E 'VIOL|CLEAN')"
+echo "MUTANT pool_one_page_short: $(SHORT=1 nice -n 19 taskset -c 0-3 ${PYTHON:-python} $SCRIPT 2>&1 | grep -m1 -E 'VIOL|CLEAN')"
+echo "MUTANT wrong_bits_K4: $(KBITS=4 nice -n 19 taskset -c 0-3 ${PYTHON:-python} $SCRIPT 2>&1 | grep -m1 -E 'VIOL|CLEAN')"
diff --git a/tools/qwen/cache8/ref8.py b/tools/qwen/cache8/ref8.py
new file mode 100644
index 0000000..b156060
--- /dev/null
+++ b/tools/qwen/cache8/ref8.py
@@ -0,0 +1,25 @@
+"""CPU reference of the 8-bit cache format (writer semantics of q_cache_kernels.cuh quant_block_x4<8>, reader of _qc_load_kt/_qc_load_v)."""
+import torch
+def h32():
+ h = torch.ones(1, 1, dtype=torch.float64)
+ while h.shape[0] < 32: h = torch.cat([torch.cat([h, h], 1), torch.cat([h, -h], 1)], 0)
+ return h / 32 ** 0.5
+H = h32()
+def pack8(x):
+ """x (N, token_dim) fp16 -> words (N, token_dim//32*8) int32, scales (N, token_dim//32) fp16. Rotated-domain midpoint grid."""
+ N, D = x.shape; G = D // 32
+ v = (x.double().view(N, G, 32) @ H) # rotate (H symmetric, 1/sqrt32 folded in)
+ s = v.abs().amax(-1) + 1e-10
+ inv = 1.0 / s
+ q = torch.floor(v * inv[..., None] * 128 + 128).clamp(0, 255).to(torch.int64) # (N,G,32)
+ qb = q.view(N, G, 8, 4)
+ w = qb[..., 0] | (qb[..., 1] << 8) | (qb[..., 2] << 16) | (qb[..., 3] << 24) # (N,G,8) as uint32 in int64
+ w = torch.where(w >= 2 ** 31, w - 2 ** 32, w).to(torch.int32)
+ return w.reshape(N, G * 8).contiguous(), s.to(torch.float16).float().half()
+def dequant8(words, scales, rotated=False):
+ N = words.shape[0]; G = scales.shape[1]
+ w = words.view(N, G, 8).to(torch.int64) & 0xFFFFFFFF
+ q = torch.stack([(w >> (8 * j)) & 255 for j in range(4)], -1).view(N, G, 32).double()
+ v = (q - 127.5) * (scales.double()[..., None] / 128.0)
+ if not rotated: v = v @ H
+ return v.view(N, G * 32).float()
diff --git a/tools/qwen/cache8/roundtrip.py b/tools/qwen/cache8/roundtrip.py
new file mode 100644
index 0000000..2475fa8
--- /dev/null
+++ b/tools/qwen/cache8/roundtrip.py
@@ -0,0 +1,21 @@
+import sys, os; sys.path.insert(0, os.path.dirname(__file__))
+import torch
+from ref8 import pack8, dequant8
+torch.manual_seed(0)
+def stats(name, x):
+ w, s = pack8(x); y = dequant8(w, s)
+ xf = x.float(); err = (y - xf)
+ rel = (err.pow(2).mean().sqrt() / xf.pow(2).mean().sqrt()).item()
+ G = x.shape[1] // 32
+ amax = xf.view(x.shape[0], G, 32).abs().amax(-1, keepdim=True)
+ mx = (err.view(x.shape[0], G, 32).abs() / amax).max().item()
+ f16 = ((xf.half().float() - xf).pow(2).mean().sqrt() / xf.pow(2).mean().sqrt()).item()
+ print(f"{name:28s} rel RMS {rel:.2e} max err/groupmax {mx:.2e} (fp16 rounding itself {f16:.2e})")
+ return rel, mx
+N, D = 4096, 512
+stats("gaussian", torch.randn(N, D).half())
+x = torch.randn(N, D) * torch.exp(torch.randn(1, D) * 1.0); stats("per-channel scale spread", x.half())
+x = torch.randn(N, D); x[:, ::37] *= 30; stats("outlier channels x30", x.half())
+x = torch.randn(N, D) ** 3; stats("heavy tail (cubed)", x.half())
+x = torch.zeros(N, D).half(); w, s = pack8(x); assert (dequant8(w, s).abs().max() < 1e-6), "zero group"; print("zero group ok")
+# theory: step = 2/256 of the rotated group absmax; uniform error rms = step/sqrt(12) = 2.3e-3 of absmax; group absmax ~ 3 sigma-ish => ~ 0.1 % of RMS
diff --git a/tools/qwen/cache8/writer_bounds.py b/tools/qwen/cache8/writer_bounds.py
new file mode 100644
index 0000000..21f959d
--- /dev/null
+++ b/tools/qwen/cache8/writer_bounds.py
@@ -0,0 +1,50 @@
+"""CPU bounds proof of the cache WRITER (quant_cache_paged_kernel<8,8>, q_cache.cu launch + q_cache_kernels.cuh quant_block_x4) at the Qwen shape.
+The address model is derived from the kernel text (read line by line, see notes): launch geometry + per-warp spans + the staging buffer.
+Every store / load of every (z, y, warp, lane) is checked against the declared tensor sizes. --mutate N breaks one rule; must FAIL."""
+import sys, itertools
+mut = int(sys.argv[sys.argv.index("--mutate") + 1]) if "--mutate" in sys.argv else 0
+KVH, HD, BITS, PAGE, NPAGES = 2, 256, 8, 256, 1024
+dim = KVH * HD; gpt = dim // 32 # groups_per_token = 16
+chunks = -(-gpt // 4); tb_per_token = -(-chunks // 8); tb_usage = -(-chunks // tb_per_token)
+assert (gpt, chunks, tb_per_token, tb_usage) == (16, 4, 1, 4)
+n_tok = NPAGES * PAGE
+W = n_tok * gpt * BITS; S = n_tok * gpt # words, scales
+viol = []
+def chk(what, lo, hi, size):
+ if not (0 <= lo and hi <= size): viol.append(f"{what}: [{lo},{hi}) outside {size}")
+import random; rnd = random.Random(1)
+def run(bsz, seq_len, seqlens, bt, in_contig):
+ in_rows = bsz * seq_len if in_contig else n_tok
+ for z in range(bsz):
+ for y in range(seq_len):
+ token_idx = y + seqlens[z]; page_idx = token_idx // PAGE
+ assert page_idx < len(bt[z]), "block table too short"
+ token_pos = (bt[z][page_idx] + (1 if mut == 3 else 0)) * PAGE + token_idx % PAGE
+ in_pos = z * seq_len + y if in_contig else token_pos
+ for x in range(tb_per_token):
+ for warp in range(tb_usage):
+ g0 = (x * tb_usage + warp) * 4
+ if g0 >= gpt: continue
+ active = min(4, gpt - g0) + 0
+ base = token_pos * gpt + g0 + (4 if mut == 2 else 0); in_base = in_pos * gpt + g0
+ # staging: lanes < 4*bits clear sh_pack[lane]; atomicOr index = sg*bits + word_base + (off>>5), sg<active, word_base 0, off = sl*4*8
+ for sg in range(min(active, 4)):
+ for sl in range(8):
+ idx = sg * BITS + ((sl * 32) >> 5); assert 0 <= idx < 32, "sh_pack overflow"
+ # global writes: out[lane] for lane < 4*bits and lane/bits < active -> words base*bits + lane
+ for lane in range(32):
+ if lane < 4 * BITS and (lane // BITS) < active: chk("k/v words", base * BITS + lane, base * BITS + lane + 1, W)
+ for lane in range(4):
+ if lane < active: chk("k/v scales", base + lane, base + lane + 1, S)
+ # loads: half2 reads in[lane*2], in[lane*2+1] for the 4 groups (128 values) when sg < active
+ for lane in range(32):
+ if (lane >> 3) < active:
+ chk("input rows", in_base * 32 + lane * 4, in_base * 32 + lane * 4 + 4, in_rows * gpt * 32)
+cases = [(1, 1, [255], [[1023]], True), (1, 1, [255], [[1023]], False), (1, 1, [0], [[1023, 0, 255, 7] + [1] * 4], True), (1, 4, [1020], [[1023, 0, 255, 7] + [1] * 4], True),
+ (1, 2048, [0], [list(range(1015, 1023)) + [0, 1, 2]], False), (1, 2048, [1500], [[1023 - i for i in range(16)]], False),
+ (2, 3, [255, 700], [[5, 6, 7, 8], [1023, 1022, 1021, 1020]], True)]
+for c in cases: run(*c)
+# int overflow: widest index products
+big = (n_tok * gpt * BITS, (n_tok - 1) * gpt * BITS * 32 // 32)
+assert n_tok * gpt * BITS < 2**31, "int overflow in base * bits"
+print("MUTANT", mut, "VIOLATIONS" if viol else "CLEAN", viol[:3]); sys.exit(1 if viol else 0)
diff --git a/tools/qwen/check_moe_split.py b/tools/qwen/check_moe_split.py
new file mode 100644
index 0000000..b064af2
--- /dev/null
+++ b/tools/qwen/check_moe_split.py
@@ -0,0 +1,136 @@
+#!/usr/bin/env python3
+"""CPU proof for the split-launch fused MoE, on the PREPROCESSED device source (hipcc -E -P of exl3_moe_fused9.hip, same flags as the build).
+usage: check_moe_split.py fused9.ii
+Claims proved from the expanded text:
+ C1 no stage kernel can wait on another block: the transitive callee closure of body9s contains no barrier / atomic / spin token
+ (gbar*, gfinish, p.bar, p.done, p.err, atomic, s_sleep, __syncthreads is block-local and allowed).
+ C2 the stages are body9 cut at its grid barriers: body9 has exactly 5 gbar7 calls; the 6 groups between them (INL branch, bookkeeping removed)
+ equal stages 0..5 of body9s (the top-k restore of stages 4 / 5 aside).
+ C3 the top-k hand-over cannot leave its buffer: every seldbg index of the restore and of the writer is < 64 + MAXR * TOPK <= STAMP_BASE <= SELDBG_INTS for every instantiated shape;
+ the writer lines in stage 3 are identical to body9's; the restore reads exactly the indices the writer wrote.
+ C4 launch geometry: stage kernels are launched with the same grid p.G (<= CTL_MAXB) and THREADS as the fused kernel.
+Mutants must fail: M1 gbar7 in a stage, M2 gfinish in a stage, M3 stage order swapped, M4 phase dropped, M5 restore index +1, M6 atomic in a callee,
+ M7 writer index shifted, M8 split grid launch with a different grid."""
+import re, sys
+
+def grab(text, name):
+ m = re.search(r'void\s+' + name + r'\s*\([^)]*\)\s*\{', text)
+ assert m, "function not found: " + name
+ i = text.index('{', m.end() - 1); d = 0
+ for j in range(i, len(text)):
+ if text[j] == '{': d += 1
+ elif text[j] == '}':
+ d -= 1
+ if d == 0: return text[m.start():j + 1]
+ raise AssertionError("unbalanced " + name)
+
+def all_funcs(text):
+ out = {}
+ for m in re.finditer(r'(?:^|\n)(?:template <[^\n]*>\n)?(?:__attribute__\(\([a-z_]+\)\) )*(?:inline )?(?:__attribute__\(\(always_inline\)\) )?(?:static )?(?:void|float|int|half|half4|uint32_t|unsigned|long|bool|long long|half2)\s+([A-Za-z_0-9]+)\s*\(', text):
+ out.setdefault(m.group(1), m.start())
+ return out
+
+FORBID = ("gbar", "gfinish", "p.bar", "p.done", "p.err", "atomic", "s_sleep", "s_barrier_signal", "__builtin_amdgcn_s_sleep")
+
+def closure_bad(text, root_body):
+ seen, todo, bad = set(), [root_body], []
+ names = None
+ while todo:
+ b = todo.pop()
+ for t in FORBID:
+ if t in b: bad.append(t)
+ for c in set(re.findall(r'\b([A-Za-z_][A-Za-z_0-9]*)\s*(?:<[^;(){}]*>)?\s*\(', b)):
+ if c in seen or c in ("if", "for", "while", "switch", "sizeof", "asm", "min", "max", "static_assert", "body9s"): continue
+ seen.add(c)
+ try: todo.append(grab(text, c))
+ except AssertionError: pass
+ return sorted(set(bad))
+
+def calls(seg):
+ return [m for m in re.findall(r'\b(touch_static|ph_dots9|ph_finalize9|ph_router9|ph_topk9|touch_down|ph_gateup9|ph_down9|ph_combine9|topk_restore9)\b', seg)]
+
+def stage_lists(b9s):
+ st = {}
+ for m in re.finditer(r'if constexpr \(STAGE == (\d)\)', b9s):
+ k = int(m.group(1)); i = m.end()
+ rest = b9s[i:]
+ if rest.lstrip().startswith('{'):
+ s0 = rest.index('{'); d = 0
+ for j in range(s0, len(rest)):
+ if rest[j] == '{': d += 1
+ elif rest[j] == '}':
+ d -= 1
+ if d == 0: seg = rest[s0:j + 1]; break
+ else:
+ seg = rest[:rest.index(';') + 1]
+ st[k] = seg
+ return st
+
+def groups_of_body9(b9):
+ inl = re.sub(r'if constexpr \(INL\) ([^;]*);\s*else [^;]*;', r'\1;', b9)
+ parts = re.split(r'mf7::gbar7<TM>\(p, phase\);', inl)
+ return parts
+
+def run(text):
+ errs = []
+ b9, b9s = grab(text, 'body9'), grab(text, 'body9s')
+ # C1
+ bad = closure_bad(text, b9s)
+ if bad: errs.append("C1 forbidden tokens reachable from the stage kernel: %s" % bad)
+ # C2
+ if b9.count("gbar7<TM>(p, phase)") != 5: errs.append("C2 body9 has %d grid barriers, expected 5" % b9.count("gbar7<TM>(p, phase)"))
+ gr = groups_of_body9(b9)
+ sl = stage_lists(b9s)
+ if len(gr) != 6 or sorted(sl) != list(range(6)): errs.append("C2 group / stage count: %d groups, stages %s" % (len(gr), sorted(sl)))
+ else:
+ for k in range(6):
+ a = calls(gr[k]); b = [c for c in calls(sl[k]) if c != 'topk_restore9']
+ if a != b: errs.append("C2 stage %d phases %s != body9 group %s" % (k, b, a))
+ for k in (4, 5):
+ if 'topk_restore9' not in calls(sl[k]): errs.append("C2 stage %d lacks the top-k restore" % k)
+ for k in (0, 1, 2, 3):
+ if 'topk_restore9' in calls(sl[k]): errs.append("C2 stage %d must not restore" % k)
+ # C3
+ wl = [l.strip() for l in b9.split('\n') if 'p.seldbg[' in l and '=' in l and 'threadIdx.x' in l]
+ ws = [l.strip() for l in sl.get(3, '').split('\n') if 'p.seldbg[' in l]
+ if wl != ws or len(wl) != 2: errs.append("C3 writer lines differ: %s vs %s" % (wl, ws))
+ rb = grab(text, 'topk_restore9')
+ idx = re.findall(r'p\.seldbg\[([^\]]*)\]', rb)
+ if idx != ['threadIdx.x', '64 + threadIdx.x']: errs.append("C3 restore indices %s" % idx)
+ if not re.search(r'threadIdx\.x < p\.R \* S::TOPK', rb): errs.append("C3 restore guard missing")
+ if not all('threadIdx.x < p.R * S::TOPK' in l for l in wl): errs.append("C3 writer guard")
+ MAXR = int(re.search(r'constexpr int MAXR = (\d+)', text).group(1))
+ SELDBG = int(re.search(r'SELDBG_INTS = (\d+)', text).group(1)); SB = int(re.search(r'STAMP_BASE = (\d+)', text).group(1))
+ for m in re.finditer(r'struct (\w+) \{ static constexpr int D = \d+, H = \d+, LR = \d+, NEXP = \d+, TOPK = (\d+)', text):
+ top = int(m.group(2)); hi = 64 + MAXR * top
+ if not (hi <= SB <= SELDBG): errs.append("C3 shape %s: 64 + %d * %d = %d vs STAMP_BASE %d / SELDBG %d" % (m.group(1), MAXR, top, hi, SB, SELDBG))
+ if MAXR * top > 64: errs.append("C3 shape %s: sel region overlaps weight region" % m.group(1))
+ # C4
+ ln = [l for l in text.split('\n') if 'moe_fused9s_kernel<S7' in l and '<<<' in l]
+ if len(ln) != 6: errs.append("C4 %d stage launches, expected 6" % len(ln))
+ for k, l in enumerate(ln):
+ if '<<<(dim3(p.G)), (dim3(mf::THREADS)), (0), (stream)>>>(p, vmask)' not in l or ('ABL, %d>' % k) not in l: errs.append("C4 launch %d: %s" % (k, l.strip()))
+ return errs
+
+def mutate(text, k):
+ if k == 1: return text.replace("ph_router9<S>(p, s);\n if constexpr (STAGE == 3)", "mf7::gbar7<false>(p, *(int*)&sink); ph_router9<S>(p, s);\n if constexpr (STAGE == 3)")
+ if k == 2: return text.replace("topk_restore9<S>(p, s); ph_combine9<S>(p, s); }", "topk_restore9<S>(p, s); ph_combine9<S>(p, s); gfinish(p); }")
+ if k == 3: return text.replace("ph_router9<S>(p, s);\n if constexpr (STAGE == 3)", "ph_finalize9<S, false>(p, s);\n if constexpr (STAGE == 3)")
+ if k == 4: return text.replace("{ topk_restore9<S>(p, s); ph_down9<S, ABL>(p, s); }", "{ topk_restore9<S>(p, s); }")
+ if k == 5: return text.replace("s.sel[threadIdx.x] = p.seldbg[threadIdx.x];", "s.sel[threadIdx.x] = p.seldbg[threadIdx.x + 1];")
+ if k == 6: return text.replace("ph_topk_tail9", "ph_topk_tail9", 1).replace("__attribute__((device)) inline __attribute__((always_inline)) void ph_topk_tail9(const Params& p, Smem<S>& s)\n{", "__attribute__((device)) inline __attribute__((always_inline)) void ph_topk_tail9(const Params& p, Smem<S>& s)\n{ __hip_atomic_fetch_add(p.bar, 1u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);")
+ if k == 7: return text.replace("p.seldbg[64 + threadIdx.x] = (int) __half_as_ushort(s.wt[threadIdx.x]);\n if (vm & V_TDOWN)", "p.seldbg[65 + threadIdx.x] = (int) __half_as_ushort(s.wt[threadIdx.x]);\n if (vm & V_TDOWN)")
+ if k == 8: return text.replace("moe_fused9s_kernel<S7, (bool) INL, ABL, 3>))<<<(dim3(p.G)),", "moe_fused9s_kernel<S7, (bool) INL, ABL, 3>))<<<(dim3(p.G + 1)),")
+ raise ValueError
+
+if __name__ == '__main__':
+ text = open(sys.argv[1]).read()
+ e = run(text)
+ print("BASE:", "PASS" if not e else "FAIL"); [print(" ", x) for x in e]
+ ok = not e
+ for k in range(1, 9):
+ mt = mutate(text, k)
+ if mt == text: print("M%d: mutation did not apply" % k); ok = False; continue
+ em = run(mt)
+ print("M%d: %s" % (k, "fails (good): " + em[0][:90] if em else "PASSES (BAD)")); ok &= bool(em)
+ print("RESULT", "PASS" if ok else "FAIL"); sys.exit(0 if ok else 1)
diff --git a/tools/qwen/serve.py b/tools/qwen/serve.py
index 360535d..1446476 100644
--- a/tools/qwen/serve.py
+++ b/tools/qwen/serve.py
@@ -506,6 +506,11 @@ SERVE_ENV = (("EXL3_MOE_FUSED", "1"), ("EXL3_MOE_VALU", "1"), ("EXL3_VERIFY_ATTN
# draft prefill deferred behind the first token (first round is a plain target step; flushed before the second round,
# at job end and on rewind, so the draft cache stays complete). 0 for either goes back.
("EXL3_PREFILL_CHUNK", "4096"), ("EXL3_PF_DEFER", "1"),
+ # the last prefill chunk runs to the end of the prompt (a tail of up to 1024 rows beyond the 4096-row chunk is merged
+ # into it) instead of a second forward pass that reads every expert again; the last-page recurrent state is written from
+ # inside the chunk. 0 for EXL3_PF_NO_TAIL goes back. Tuned dense-GEMM solutions for the larger row classes ship in
+ # exllamav3/model/dense_gemm_tune_seed.txt.
+ ("EXL3_PF_NO_TAIL", "1"), ("EXL3_PF_TAIL_MERGE", "1024"),
# the batched R-row sparse attention launch is row-invariant (the split plan no longer depends on R, see
# qsa_split_plan; EXL3_QSA_ROWINV=0 goes back), so verify keeps ONE launch and speculative == plain bitwise above the
# QSA sparse threshold (2051 tokens). The per-row fallback is EXL3_VERIFY_QSA_PROJ=1 EXL3_VERIFY_QSA_ATTN=all.
@@ -598,7 +603,7 @@ class QwenEngine:
"""Target model + MTP drafter + (optional) vision tower + one Generator."""
def __init__(self, model_path: str, ctx: int, ndt: int = 3, draft_policy: str = "mix",
- vision: bool = True, max_chunk_size: int = 2048):
+ vision: bool = True, max_chunk_size: int = 2048, cache_bits: int = 8):
# The measured Qwen serving configuration. Read at import time by the engine:
# set before importing exllamav3. The caller's environment wins.
for k, v in SERVE_ENV:
@@ -614,7 +619,15 @@ class QwenEngine:
self.tokenizer = Tokenizer.from_config(self.config)
self.eos = list(self.config.eos_token_id_list)
self.model = Model.from_config(self.config)
- self.cache = Cache(self.model, max_num_tokens=ctx, max_history=3)
+ # cache_bits 8 (default) = packed int8 K/V pages (about 40 % smaller than fp16), indexer planes stay fp16;
+ # 0 = the fp16 K/V pages (--cache-bits 0)
+ self.cache_bits = cache_bits
+ from exllamav3 import CacheLayer_quant
+ qkw = dict(layer_type=CacheLayer_quant, k_bits=cache_bits, v_bits=cache_bits) if cache_bits else {}
+ self.cache = Cache(self.model, max_num_tokens=ctx, max_history=3, **qkw)
+ if os.environ.get("EXL3_WARM_DENSE", "1") != "0":
+ from exllamav3.model.dense_warmup import seed_dense_tune
+ seed_dense_tune()
with Heartbeat("loading target model"):
self.model.load(max_chunk_size=max_chunk_size, progressbar=False)
from exllamav3.modules.hyperconnections import GS_STATS
@@ -622,7 +635,7 @@ class QwenEngine:
self.draft_model = self.draft_cache = None
if draft_policy != "off":
self.draft_model = Model.from_config(self.config, component="mtp")
- self.draft_cache = Cache(self.draft_model, max_num_tokens=ctx, max_history=3)
+ self.draft_cache = Cache(self.draft_model, max_num_tokens=ctx, max_history=3, **qkw)
with Heartbeat("loading MTP drafter"):
self.draft_model.load(progressbar=False)
self.vision = None
@@ -684,7 +697,9 @@ class QwenEngine:
# dense GEMM warm-up at load (EXL3_WARM_DENSE=0 = off): the first request at a new row-count class
# no longer pays the rocBLAS solution screening (0.15-4 s per shape).
from exllamav3.model.dense_warmup import warm_dense_gemm
- warm_dense_gemm([self.model, self.draft_model], max_rows=self.generator.max_chunk_size)
+ warm_dense_gemm([self.model, self.draft_model],
+ max_rows=self.generator.max_chunk_size + (int(os.environ.get("EXL3_PF_TAIL_MERGE", "0"))
+ if os.environ.get("EXL3_PF_NO_TAIL", "0") == "1" else 0))
ids = self.tokenizer.encode("<|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n",
add_bos=False, encode_special_tokens=True)
job = self.Job(input_ids=ids, max_new_tokens=24, sampler=self._sampler({"temperature": 0.0}),
@@ -697,6 +712,9 @@ class QwenEngine:
def count_tokens(self, text: str) -> int:
return int(self.tokenizer.encode(text, add_bos=False, encode_special_tokens=True).numel())
+ def token_str(self, token_id: int) -> str:
+ return self.tokenizer.tokenizer.decode([int(token_id)], skip_special_tokens=False)
+
def _sampler(self, s: dict[str, Any]):
from exllamav3.generator.sampler import ArgmaxSampler, ComboSampler
if s["temperature"] == 0 or s.get("top_k") == 1:
@@ -736,7 +754,7 @@ class QwenEngine:
images: list[str] | None = None, speculative: bool = True, cache_prompt: bool = True,
cancel: asyncio.Event | None = None, seed: int | None = None, reasoning_first: bool = False,
thinking_budget: int | None = None, loop_guard: bool | None = None,
- loop_final: bool | None = None) -> AsyncIterator[str]:
+ loop_final: bool | None = None, logprobs: int | None = None) -> AsyncIterator[str]:
"""Yield decoded text pieces. The caller serializes calls. Final stats land in self.last_stats.
Final check (on with the guard, loop_final=False turns it off): when the turn ends normally and the visible text
@@ -746,7 +764,11 @@ class QwenEngine:
Loop guard (default on, EXL3_LOOP_GUARD=0 or loop_guard=False turns it off): when the think block loops (or
thinking_budget tokens are used) the job is cancelled and restarted from prompt + the thinking kept so far +
"\n</think>\n\n", so the answer proceeds. A loop inside the answer ends the turn (finish_reason stop).
- Nothing is changed while no loop is detected."""
+ Nothing is changed while no loop is detected.
+
+ logprobs (None = off, k = 0..20): per generated token the log-probability of the token and of the k most likely tokens,
+ taken from the model distribution before temperature and truncation. They land in last_stats["logprobs"], one entry
+ per entry of token_ids ((token_logprob, [(id, logprob), ...]), None for a token the guard forced)."""
loop = asyncio.get_running_loop()
self.last_stats = {}
if cancel is not None and cancel.is_set():
@@ -770,6 +792,7 @@ class QwenEngine:
if guard_on or budget:
mon = LoopMonitor("think" if reasoning_first else "answer", close_id, budget, detect=guard_on)
token_ids: list[int] = [] # everything streamed to the client, all segments
+ lps: list = [] # parallel to token_ids when logprobs is asked
fired: dict[str, Any] | None = None
marks: list[tuple[int, int]] = [(0, 0)] # (tokens, characters) streamed after each event of this segment
chars = 0
@@ -788,7 +811,8 @@ class QwenEngine:
while True:
job = self.Job(input_ids=job_ids, max_new_tokens=max(max_tokens - generated + discount, 1),
sampler=self._sampler(sampling), stop_conditions=self.eos + list(stop),
- embeddings=embs or None, decode_special_tokens=True, seed=seed)
+ embeddings=embs or None, decode_special_tokens=True, seed=seed,
+ **({} if logprobs is None else {"return_probs": True, "return_top_tokens": logprobs}))
self.generator.enqueue(job)
seg: list[int] = []
marks = [(0, 0)]
@@ -806,6 +830,8 @@ class QwenEngine:
t = ev.get("token_ids")
toks = t.flatten().tolist() if t is not None and t.numel() else []
token_ids += toks
+ if logprobs is not None:
+ lps += self._event_logprobs(ev, len(toks))
seg += toks
generated += len(toks)
if ev.get("text"):
@@ -824,8 +850,14 @@ class QwenEngine:
redo = True
break
if ev.get("eos"):
- self.last_stats = {k: v for k, v in ev.items() if k not in ("job", "token_ids", "text", "held")}
+ self.last_stats = {k: v for k, v in ev.items() if k not in ("job", "token_ids", "text", "held") and not k.startswith("stop_token_")}
self.last_stats["token_ids"] = token_ids
+ if logprobs is not None:
+ self.last_stats["logprobs"] = lps
+ stop_lp = self._stop_logprobs(ev)
+ if stop_lp is not None: # the sampled stop token: no content, but its position is scored
+ self.last_stats["logprobs"] = lps + [stop_lp]
+ self.last_stats["logprob_token_ids"] = token_ids + [int(ev["eos_triggering_token_id"])]
if fired:
self.last_stats.update(prompt_tokens=int(ids.numel()), new_tokens=generated,
cached_tokens=min(int(self.last_stats.get("cached_tokens", 0)), int(ids.numel())),
@@ -849,6 +881,8 @@ class QwenEngine:
discount += len(token_ids) - keep_tokens
del token_ids[keep_tokens:]
token_ids += close_seq
+ del lps[keep_tokens:]
+ lps += [None] * len(close_seq)
generated += len(close_seq)
chars += len(THINK_CLOSE_TEXT)
vis += THINK_CLOSE_TEXT
@@ -869,6 +903,8 @@ class QwenEngine:
if hit["phase"] == "answer" or close_id is None:
self.last_stats = {"prompt_tokens": n_total, "new_tokens": generated, "cached_tokens": 0,
"eos_reason": "loop_guard", "token_ids": token_ids, "loop_guard": fired}
+ if logprobs is not None:
+ self.last_stats["logprobs"] = lps
return
# think block: keep the thinking up to the cut (on an event boundary), force the close, restart from there
keep_tokens, keep_chars = max(m for m in marks if m[0] <= hit["cut"])
@@ -880,6 +916,8 @@ class QwenEngine:
vis = vis[:chars]
del token_ids[len(token_ids) - len(seg) + keep_tokens:]
token_ids += close_seq
+ del lps[len(token_ids) - len(close_seq):]
+ lps += [None] * len(close_seq)
generated += len(close_seq)
chars += len(THINK_CLOSE_TEXT)
vis += THINK_CLOSE_TEXT
@@ -889,11 +927,33 @@ class QwenEngine:
if generated - discount >= max_tokens:
self.last_stats = {"prompt_tokens": n_total, "new_tokens": generated, "cached_tokens": 0,
"eos_reason": "max_new_tokens", "token_ids": token_ids, "loop_guard": fired}
+ if logprobs is not None:
+ self.last_stats["logprobs"] = lps
return
extra = self.torch.tensor([seg[:keep_tokens] + close_seq], dtype=ids.dtype)
job_ids = self.torch.cat([ids, extra.to(ids.device)], dim=-1)
mon.start_phase("answer")
+ @staticmethod
+ def _stop_logprobs(ev: dict[str, Any]):
+ """Logprob entry of the stop token a stream event ended on (None when the event carries none)."""
+ if ev.get("stop_token_prob") is None or ev.get("eos_reason") != "stop_token":
+ return None
+ e = QwenEngine._event_logprobs({"token_probs": ev["stop_token_prob"], "top_k_tokens": ev.get("stop_token_top_k_tokens"),
+ "top_k_probs": ev.get("stop_token_top_k_probs")}, 1)[0]
+ return e
+
+ @staticmethod
+ def _event_logprobs(ev: dict[str, Any], n: int) -> list:
+ """(token_logprob, [(id, logprob), ...]) for the n tokens of a stream event."""
+ probs, ids, tops = ev.get("token_probs"), ev.get("top_k_tokens"), ev.get("top_k_probs")
+ if probs is None or probs.numel() != n:
+ return [None] * n
+ pl = probs.flatten().tolist()
+ il = ids.reshape(n, -1).tolist() if ids is not None else [[]] * n
+ tl = tops.reshape(n, -1).tolist() if tops is not None else [[]] * n
+ return [(math.log(max(pl[i], 1e-45)), [(a, math.log(max(b, 1e-45))) for a, b in zip(il[i], tl[i])]) for i in range(n)]
+
def spec_stats(self) -> dict[str, Any]:
return {"speculative": self.spec_on, "draft_policy": self.draft_policy if self.spec_on else "off", "ndt": self.ndt}
@@ -901,6 +961,55 @@ class QwenEngine:
# ---------------------------------------------------------------------------- HTTP
+MAX_TOP_LOGPROBS = 20
+
+
+def logprobs_arg(value: Any, top: Any = None, chat: bool = False) -> int | None:
+ """The k of a request's logprobs fields, None when off. Completions: logprobs = k (0..20). Chat: logprobs = true plus
+ top_logprobs = k (0..20, default 0)."""
+ if chat:
+ if value is None or value is False:
+ if top not in (None, 0):
+ raise BadRequest("top_logprobs needs logprobs = true")
+ return None
+ if value is not True:
+ raise BadRequest("logprobs must be boolean")
+ k = 0 if top is None else top
+ else:
+ if value is None:
+ return None
+ k = value
+ if not isinstance(k, int) or isinstance(k, bool) or not 0 <= k <= MAX_TOP_LOGPROBS:
+ raise BadRequest(f"top_logprobs must be an integer from 0 to {MAX_TOP_LOGPROBS}")
+ return k
+
+
+def format_logprobs(entries: list, token_ids: list[int], token_str, chat: bool) -> dict[str, Any]:
+ """OpenAI logprobs object for the generated tokens. Every token and candidate also carries its id. Values are natural
+ logs of the model distribution before temperature, top-k, top-p and min-p. A token the loop guard forced has none (null)."""
+ def tok(i: int) -> dict[str, Any]:
+ t = token_str(i)
+ return {"token": t, "bytes": list(t.encode("utf-8")), "token_id": int(i)}
+ if chat:
+ content = []
+ for tid, e in zip(token_ids, entries):
+ if e is None:
+ content.append(tok(tid) | {"logprob": None, "top_logprobs": []})
+ else:
+ content.append(tok(tid) | {"logprob": e[0], "top_logprobs": [tok(a) | {"logprob": b} for a, b in e[1]]})
+ return {"content": content}
+ toks, offs, pos = [], [], 0
+ for tid in token_ids:
+ t = token_str(tid)
+ toks.append(t)
+ offs.append(pos)
+ pos += len(t)
+ return {"tokens": toks, "token_ids": [int(t) for t in token_ids], "text_offset": offs,
+ "token_logprobs": [None if e is None else e[0] for e in entries],
+ "top_logprobs": [None if e is None else {token_str(a): b for a, b in e[1]} for e in entries],
+ "top_logprobs_ids": [None if e is None else [[int(a), b] for a, b in e[1]] for e in entries]}
+
+
def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, Any] | None = None,
default_max_tokens: int = 32768) -> web.Application:
"""HTTP layer around a resident engine (also accepts a fake engine in tests)."""
@@ -936,9 +1045,14 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
stop=job["stop"], images=job["images"], speculative=job["speculative"],
cache_prompt=job["cache_prompt"], cancel=job["cancel"],
seed=job.get("seed"), reasoning_first=job.get("reasoning_first", False),
- thinking_budget=job.get("thinking_budget"), loop_guard=job.get("loop_guard"), loop_final=job.get("loop_final")):
+ thinking_budget=job.get("thinking_budget"), loop_guard=job.get("loop_guard"), loop_final=job.get("loop_final"), logprobs=job.get("logprobs")):
out.put_nowait(delta)
- out.put_nowait(("done", dict(getattr(engine, "last_stats", None) or {})))
+ done = dict(getattr(engine, "last_stats", None) or {})
+ print(f"qserve: request prompt={int(done.get('prompt_tokens') or 0)} cached={int(done.get('cached_tokens') or 0)} "
+ f"new={int(done.get('new_tokens') or 0)} prefill_s={float(done.get('time_prefill') or 0):.3f} "
+ f"generate_s={float(done.get('time_generate') or 0):.3f} stop={done.get('eos_reason')}",
+ file=sys.stderr, flush=True)
+ out.put_nowait(("done", done))
except Exception as exc: # noqa: BLE001
out.put_nowait(exc)
finally:
@@ -1000,7 +1114,10 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
raise BadRequest("loop_guard must be boolean")
if body.get("loop_final") is not None and not isinstance(body["loop_final"], bool):
raise BadRequest("loop_final must be boolean")
- return {"seed": seed, "thinking_budget": budget, "loop_guard": body.get("loop_guard"), "loop_final": body.get("loop_final"), "prompt": prompt, "prompt_tokens": prompt_tokens, "max_tokens": max_tokens,
+ lp = logprobs_arg(body.get("logprobs"), body.get("top_logprobs"), chat=True)
+ if lp is not None and body.get("stream"):
+ raise BadRequest("logprobs are returned on non-streaming requests only")
+ return {"logprobs": lp, "seed": seed, "thinking_budget": budget, "loop_guard": body.get("loop_guard"), "loop_final": body.get("loop_final"), "prompt": prompt, "prompt_tokens": prompt_tokens, "max_tokens": max_tokens,
"sampling": sampling_from(body, defaults), "stop": stops, "images": images,
"speculative": body.get("speculative", True) is not False,
"cache_prompt": body.get("cache_prompt", True) is not False,
@@ -1144,6 +1261,9 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
"usage": usage, "timings": timings}
if job["return_token_ids"]:
payload["token_ids"] = stats.get("token_ids", [])
+ if job["logprobs"] is not None:
+ payload["choices"][0]["logprobs"] = format_logprobs(
+ stats.get("logprobs", []), stats.get("logprob_token_ids", stats.get("token_ids", [])), engine.token_str, chat=True)
return web.json_response(payload)
async def apply_template(request: web.Request) -> web.Response:
@@ -1245,6 +1365,9 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
raise BadRequest("seed must be an integer")
if body.get("loop_guard") is not None and not isinstance(body["loop_guard"], bool):
raise BadRequest("loop_guard must be boolean")
+ lp = logprobs_arg(body.get("logprobs"))
+ if lp is not None and body.get("stream"):
+ raise BadRequest("logprobs are returned on non-streaming requests only")
prompt_tokens = engine.count_tokens(prompt)
ctx = getattr(engine, "ctx", None)
if ctx:
@@ -1252,7 +1375,7 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
if room < 1:
raise BadRequest(f"context length exceeded: prompt is {prompt_tokens} tokens, the server context is {ctx}")
max_tokens = min(max_tokens, room)
- job = {"prompt": prompt, "max_tokens": max_tokens, "stop": stops, "images": [], "speculative": body.get("speculative", True) is not False, "seed": seed,
+ job = {"logprobs": lp, "prompt": prompt, "max_tokens": max_tokens, "stop": stops, "images": [], "speculative": body.get("speculative", True) is not False, "seed": seed,
"sampling": sampling_from(body, defaults), "cache_prompt": body.get("cache_prompt", True) is not False,
"loop_guard": body.get("loop_guard"), "cancel": asyncio.Event()}
except json.JSONDecodeError as exc:
@@ -1337,7 +1460,11 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
return web.json_response({"error": {"message": f"{type(exc).__name__}: {exc}", "type": "server_error"}}, status=500)
text, _ = stop_text(full, job["stop"])
reason, usage = reason_usage(stats, text)
- return web.json_response(chunk(text, reason) | {"object": "text_completion", "usage": usage})
+ out_ = chunk(text, reason) | {"object": "text_completion", "usage": usage}
+ if job["logprobs"] is not None:
+ out_["choices"][0]["logprobs"] = format_logprobs(
+ stats.get("logprobs", []), stats.get("logprob_token_ids", stats.get("token_ids", [])), engine.token_str, chat=False)
+ return web.json_response(out_)
async def slots(_: web.Request) -> web.Response:
return web.json_response(engine.slot_store.slots())
@@ -1385,6 +1512,8 @@ def main() -> None:
parser.add_argument("--model", default=DEFAULT_MODEL, help="pack directory")
parser.add_argument("--model-id", default=DEFAULT_MODEL_ID, help="id shown by /v1/models and expected in requests")
parser.add_argument("--ctx", "-c", type=int, default=65536, help="KV cache size in tokens (default 65536)")
+ parser.add_argument("--cache-bits", type=int, default=8, choices=(0, 8),
+ help="bits per K/V element of the attention cache pages (8 = packed int8, the default, about 40 %% smaller; 0 = fp16)")
parser.add_argument("--ndt", type=int, default=3, help="max draft tokens per round (default 3)")
parser.add_argument("--draft-policy", choices=("mix", "mtp", "off"), default="mix",
help="mix = shipped rule (MTP + n-gram lookup, lossless), mtp = fixed MTP chain, off = plain decode")
@@ -1409,7 +1538,8 @@ def main() -> None:
t0 = time.time()
print(f"qserve: starting, model={model_dir} ctx={args.ctx} draft_policy={args.draft_policy} "
f"defaults={ {k: v for k, v in defaults.items() if v is not None} }", flush=True)
- engine = QwenEngine(model_dir, args.ctx, ndt=args.ndt, draft_policy=args.draft_policy, vision=not args.no_vision)
+ engine = QwenEngine(model_dir, args.ctx, ndt=args.ndt, draft_policy=args.draft_policy, vision=not args.no_vision,
+ cache_bits=args.cache_bits)
env = {k: v for k, v in sorted(os.environ.items()) if k.startswith(("EXL3_", "MPW"))}
print(f"qserve: effective env {env}", flush=True)
from exllamav3.generator.slot_store import SlotStore
diff --git a/tools/qwen/test_moe_align.py b/tools/qwen/test_moe_align.py
new file mode 100644
index 0000000..4edd234
--- /dev/null
+++ b/tools/qwen/test_moe_align.py
@@ -0,0 +1,98 @@
+"""CPU test of block_sparse_mlp._aligned_expert_layout (EXL3_MOE_ALIGN_CHUNK): layout properties + mutants.
+Run: nice -n 19 taskset -c 0-7 python tools/qwen/test_moe_align.py [--mutants]"""
+import inspect, os, sys, textwrap, unittest
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", ".."))
+import torch
+from exllamav3.modules import block_sparse_mlp as bsm
+
+CASES = [(9000, 10, 512, 4096, "u"), (16384, 10, 512, 4096, "u"), (16384, 10, 512, 4096, "d0.2"), (4097, 10, 512, 4096, "u"),
+ (4096 * 3 + 1, 10, 512, 4096, "d0.5"), (8192, 10, 64, 1024, "u"), (50, 3, 8, 16, "u"), (33, 10, 512, 16, "d0.1"),
+ (20000, 10, 512, 4096, "one"), (8, 3, 10, 4, "allodd")]
+
+def routing(T, k, E, kind, seed):
+ g = torch.Generator().manual_seed(seed)
+ if kind == "allodd": # every (expert, chunk) segment has an odd length: the pad capacity is exactly used
+ return torch.tensor([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 9, 9]] * (T // 4))
+ if kind == "one": # every token picks experts 0..k-1 except a few
+ sel = torch.arange(k).repeat(T, 1)
+ sel[::7] = torch.arange(E - k, E)
+ return sel.long()
+ prob = torch.ones(E) if kind == "u" else torch.distributions.Dirichlet(torch.full((E,), float(kind[1:]))).sample()
+ x = torch.rand((T, E), generator=g).clamp_min(1e-9)
+ return torch.topk(torch.log(prob) + (-torch.log(-torch.log(x))), k, dim=-1).indices.contiguous()
+
+def check(fn, T, k, E, chunk, kind, seed=0):
+ sel = routing(T, k, E, kind, seed); flat = sel.view(-1); a0 = T * k
+ order, sel_flat, D = fn(flat, T, k, E, chunk)
+ total = a0 + D * k
+ assert order.shape == (total,) and sel_flat.shape == (total,), "shapes"
+ assert torch.equal(order.sort().values, torch.arange(total)), "order is not a permutation of all slots"
+ assert torch.equal(sel_flat[:a0], flat), "real slots keep their expert"
+ es = sel_flat[order]
+ assert bool((es[1:] >= es[:-1]).all()), "order not grouped by expert"
+ nc = (T + chunk - 1) // chunk
+ cid = torch.arange(a0) // (k * chunk)
+ for e in range(E):
+ lst = order[es == e].tolist()
+ runs = [] # (start row in the expert list, chunk, slots, followed by a pad)
+ pos = 0
+ for s in lst:
+ if s < a0:
+ c = int(cid[s])
+ if runs and runs[-1][1] == c and not runs[-1][3] and runs[-1][0] + len(runs[-1][2]) == pos:
+ runs[-1][2].append(s)
+ else:
+ runs.append([pos, c, [s], False])
+ elif runs and runs[-1][0] + len(runs[-1][2]) == pos and not runs[-1][3]:
+ runs[-1][3] = True
+ pos += 1
+ got = {}
+ for st, c, run, padded in runs:
+ assert c not in got, f"expert {e} chunk {c} split in two runs"
+ got[c] = run
+ assert run == sorted(run), "slot order inside a segment"
+ assert st % 2 == 0, f"segment of expert {e} chunk {c} starts at odd row {st}"
+ if not (e == E - 1 and (st, c, run, padded) is not None and runs[-1][1] == c): # the last expert's final run may be followed by the extra dummy slots
+ assert padded == (len(run) % 2 == 1), f"pad rule expert {e} chunk {c}"
+ want = {}
+ for s in (flat == e).nonzero().flatten().tolist(): want.setdefault(int(cid[s]), []).append(s)
+ assert got == want, f"segments of expert {e} differ"
+ # all dummy slots are distinct slots of dummy tokens
+ assert int((order >= a0).sum()) == D * k
+
+class T(unittest.TestCase):
+ def test_all(self):
+ for i, (Tn, k, E, ch, kind) in enumerate(CASES):
+ if Tn * k > 200000: continue
+ with self.subTest(case=(Tn, k, E, ch, kind)): check(bsm._aligned_expert_layout, Tn, k, E, ch, kind, i)
+
+MUTANTS = [
+ ("no even padding", "odd = kc & 1", "odd = kc & 0"),
+ ("pad always", "odd = kc & 1", "odd = (kc >= 0).long()"),
+ ("chunk width", "torch.arange(a0, device = dev) // (top_k * chunk)", "torch.arange(a0, device = dev) // (top_k * chunk * 2)"),
+ ("pad after not before shift", "pos = torch.arange(a0, device = dev) + padbefore[key[srt]]", "pos = torch.arange(a0, device = dev)"),
+ ("pad position off by one", "pad_pos = torch.cumsum(kc, 0) + padbefore", "pad_pos = torch.cumsum(kc, 0) + padbefore + 1"),
+ ("pad expert wrong", "torch.arange(nseg, device = dev) // nc\n", "torch.arange(nseg, device = dev) % num_experts\n"),
+ ("pad slot id wrong", "pad_slot = a0 + padbefore", "pad_slot = a0 + padbefore * 0"),
+ ("unstable sort order", "srt = key.argsort(stable = True)", "srt = key.argsort(stable = True, descending = True)"),
+ ("dummy token count", "dummy_tokens = (nseg + top_k - 1) // top_k", "dummy_tokens = nseg // top_k"),
+ ("extras expert", "torch.full((total + 1,), num_experts - 1,", "torch.full((total + 1,), 0,"),
+]
+
+def run_mutants():
+ src = textwrap.dedent(inspect.getsource(bsm._aligned_expert_layout)); bad = 0
+ for name, a, b in MUTANTS:
+ assert a in src, f"mutant anchor missing: {name}"
+ ns = {"torch": torch}; exec(src.replace(a, b, 1), ns); fn = ns["_aligned_expert_layout"]
+ failed = False
+ for i, (Tn, k, E, ch, kind) in enumerate(CASES):
+ if Tn * k > 200000: continue
+ try: check(fn, Tn, k, E, ch, kind, i)
+ except Exception as ex:
+ failed = True; break
+ print(f"mutant {name:30s}: {'KILLED' if failed else 'SURVIVED'}"); bad += (not failed)
+ print("survivors:", bad); return bad
+
+if __name__ == "__main__":
+ if "--mutants" in sys.argv: sys.exit(1 if run_mutants() else 0)
+ unittest.main()
diff --git a/tools/qwen/test_serve.py b/tools/qwen/test_serve.py
index 6189286..0bd2852 100644
--- a/tools/qwen/test_serve.py
+++ b/tools/qwen/test_serve.py
@@ -443,6 +443,107 @@ class HttpTests(unittest.TestCase):
self.assertEqual(ev[-1]["choices"][0]["finish_reason"], "error")
+class LogprobsTests(unittest.TestCase):
+ ENTRIES = [(-0.5, [(1, -0.5), (9, -1.5)]), (-2.0, [(2, -0.25), (3, -2.0)]), None]
+
+ def engine(self):
+ eng = FakeEngine("abc", {"new_tokens": 3, "prompt_tokens": 2, "eos_reason": "stop_token", "token_ids": [1, 2, 3],
+ "logprobs": self.ENTRIES})
+ eng.token_str = lambda i: f"t{i}"
+ return eng
+
+ def post(self, path, payload):
+ async def fn(client):
+ r = await client.post(path, json={"model": "m"} | payload)
+ return r.status, await r.json()
+ return with_client(self.engine(), fn)
+
+ def test_completions_shape_and_request(self):
+ eng = self.engine()
+
+ async def fn(client):
+ r = await client.post("/v1/completions", json={"model": "m", "prompt": "hi", "max_tokens": 3, "logprobs": 2})
+ return r.status, await r.json()
+ st, body = with_client(eng, fn)
+ self.assertEqual(st, 200)
+ self.assertEqual(eng.calls[0][1]["logprobs"], 2)
+ lp = body["choices"][0]["logprobs"]
+ self.assertEqual(lp["tokens"], ["t1", "t2", "t3"])
+ self.assertEqual(lp["token_ids"], [1, 2, 3])
+ self.assertEqual(lp["token_logprobs"], [-0.5, -2.0, None])
+ self.assertEqual(lp["top_logprobs"][0], {"t1": -0.5, "t9": -1.5})
+ self.assertEqual(lp["top_logprobs_ids"][1], [[2, -0.25], [3, -2.0]])
+ self.assertEqual(lp["text_offset"], [0, 2, 4])
+
+ def test_chat_shape(self):
+ st, body = self.post("/v1/chat/completions", {"messages": [{"role": "user", "content": "hi"}],
+ "logprobs": True, "top_logprobs": 2})
+ self.assertEqual(st, 200)
+ c = body["choices"][0]["logprobs"]["content"]
+ self.assertEqual([x["token_id"] for x in c], [1, 2, 3])
+ self.assertEqual(c[0]["logprob"], -0.5)
+ self.assertEqual([t["token_id"] for t in c[0]["top_logprobs"]], [1, 9])
+ self.assertIsNone(c[2]["logprob"])
+
+ def test_off_by_default_and_bad_values(self):
+ st, body = self.post("/v1/completions", {"prompt": "hi"})
+ self.assertEqual(st, 200)
+ self.assertIsNone(body["choices"][0]["logprobs"])
+ for path, extra in (("/v1/completions", {"prompt": "hi", "logprobs": 21}),
+ ("/v1/completions", {"prompt": "hi", "logprobs": -1}),
+ ("/v1/completions", {"prompt": "hi", "logprobs": 2, "stream": True}),
+ ("/v1/chat/completions", {"messages": [{"role": "user", "content": "x"}], "logprobs": True, "top_logprobs": 25}),
+ ("/v1/chat/completions", {"messages": [{"role": "user", "content": "x"}], "top_logprobs": 3}),
+ ("/v1/chat/completions", {"messages": [{"role": "user", "content": "x"}], "logprobs": 5})):
+ self.assertEqual(self.post(path, extra)[0], 400, (path, extra))
+
+ def stop_engine(self):
+ eng = FakeEngine("", {"new_tokens": 0, "prompt_tokens": 2, "eos_reason": "stop_token", "token_ids": [],
+ "logprobs": [(-0.1, [(151645, -0.1), (9, -2.5)])], "logprob_token_ids": [151645]})
+ eng.token_str = lambda i: f"t{i}"
+ return eng
+
+ def test_stop_token_position_is_scored(self):
+ """max_tokens=1 and the model's argmax is the stop token: no content, finish_reason stop, logprobs present."""
+ async def comp(client):
+ r = await client.post("/v1/completions", json={"model": "m", "prompt": "hi", "max_tokens": 1, "logprobs": 2})
+ return r.status, await r.json()
+ st, body = with_client(self.stop_engine(), comp)
+ ch = body["choices"][0]
+ self.assertEqual((st, ch["text"], ch["finish_reason"]), (200, "", "stop"))
+ self.assertEqual(ch["logprobs"]["token_ids"], [151645])
+ self.assertEqual(ch["logprobs"]["top_logprobs_ids"], [[[151645, -0.1], [9, -2.5]]])
+
+ async def chat(client):
+ r = await client.post("/v1/chat/completions", json={"model": "m", "messages": [{"role": "user", "content": "hi"}],
+ "max_tokens": 1, "logprobs": True, "top_logprobs": 2})
+ return r.status, await r.json()
+ st, body = with_client(self.stop_engine(), chat)
+ ch = body["choices"][0]
+ self.assertEqual((st, ch["finish_reason"]), (200, "stop"))
+ self.assertEqual([x["token_id"] for x in ch["logprobs"]["content"]], [151645])
+ self.assertEqual([t["token_id"] for t in ch["logprobs"]["content"][0]["top_logprobs"]], [151645, 9])
+
+ def test_stop_logprobs_from_event(self):
+ import torch
+ ev = {"eos_reason": "stop_token", "eos_triggering_token_id": 5, "stop_token_prob": torch.tensor([[0.5]]),
+ "stop_token_top_k_tokens": torch.tensor([[[5, 8]]]), "stop_token_top_k_probs": torch.tensor([[[0.5, 0.25]]])}
+ e = serve.QwenEngine._stop_logprobs(ev)
+ self.assertAlmostEqual(e[0], -0.6931471805599453, places=6)
+ self.assertEqual([a for a, _ in e[1]], [5, 8])
+ self.assertIsNone(serve.QwenEngine._stop_logprobs({"eos_reason": "max_new_tokens"}))
+ self.assertIsNone(serve.QwenEngine._stop_logprobs({"eos_reason": "stop_token"}))
+
+ def test_event_logprobs(self):
+ import torch
+ ev = {"token_probs": torch.tensor([[0.5, 0.25]]), "top_k_tokens": torch.tensor([[[7, 8], [4, 5]]]),
+ "top_k_probs": torch.tensor([[[0.5, 0.25], [0.5, 0.25]]])}
+ out = serve.QwenEngine._event_logprobs(ev, 2)
+ self.assertAlmostEqual(out[0][0], -0.6931471805599453, places=6)
+ self.assertEqual([a for a, _ in out[1][1]], [4, 5])
+ self.assertEqual(serve.QwenEngine._event_logprobs({}, 2), [None, None])
+
+
class ReplyRoomTests(unittest.TestCase):
"""The reply budget must never make Job.prepare ask for more pages than the page table holds."""