Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
D-1: the prompt path's QSA attention on tensor cores
Niko1221732a3f4c92ee
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 1e876dd0a..db8f5c9b2 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -189,6 +189,7 @@ if(STRATA_ENABLE_CUDA)src/kernels/cuda/fused_gr.cusrc/kernels/cuda/cvec.cusrc/kernels/cuda/qsa_decode_attn.cu+ src/kernels/cuda/qsa_prompt_attn.cusrc/kernels/cuda/fused_gdn.cusrc/kernels/cuda/dequant_bf16.cusrc/kernels/cuda/qsa_select.cu@@ -198,6 +199,13 @@ if(STRATA_ENABLE_CUDA)src/ngram/ple_reader.cppsrc/platform/direct_file.cpp)target_link_libraries(strata_kernels PUBLIC strata_core strata_artifact)+ # perf-review D-1: the tensor-core prompt attention vs the FP32 kernel and FP64 (GPU, synthetic, no model); with+ # the tests, or alone with -DSTRATA_PARITY_PROMPT_ATTN=ON+ if(STRATA_BUILD_TESTS OR STRATA_PARITY_PROMPT_ATTN)+ add_executable(qsa_prompt_attn_parity src/kernels/qsa_prompt_attn_parity.cpp)+ target_include_directories(qsa_prompt_attn_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES})+ target_link_libraries(qsa_prompt_attn_parity PRIVATE strata_kernels CUDA::cudart)+ endif()# plan v0.3 P6: llama.cpp's block layouts and codebook grids for the i-quant formats (MIT, third_party/ggml)target_include_directories(strata_kernels PRIVATE third_party/ggml)# Match the pinned llama.cpp CUDA arithmetic contract for this adapter only.diff --git a/include/strata/kernels/qsa_prompt_attn.hpp b/include/strata/kernels/qsa_prompt_attn.hppnew file mode 100644index 000000000..37261a104--- /dev/null+++ b/include/strata/kernels/qsa_prompt_attn.hpp@@ -0,0 +1,31 @@+// include/strata/kernels/qsa_prompt_attn.hpp - perf-review D-1: the prompt path's QSA attention on tensor cores.+//+// `qsa_decode_attn_batch` serves a prompt one query at a time with the decode kernel: FP32 dot products with a warp+// reduction per head and cell, 64-cell chunks whose partial sums go through global scratch to a second (merge)+// kernel. At 32K that is 21% of the prompt (5.6 s of 26 s on a 5070, Q2_0, int8 KV), and it is limited by+// instruction issue, not memory (~150 GB/s of logical reads, 3.4 TFLOP/s).+//+// This kernel keeps the same per-query selection (no masking, no union) and reads the same pools, but:+// * one block per (query, KV head) walks all its selected cells in chunks of 32 with an online softmax: no+// split-K scratch and no merge kernel;+// * q.k and p.v are m16n8k16 FP16 MMAs with FP32 accumulation over the 12 query heads of the KV head (+4 pad rows);+// * the stored values enter exactly: int8 codes are exact in FP16 and their per-64 scales are applied in FP32+// (to the q.k partial of each 64-dim group, and folded into p for p.v); FP16 KV is used as is;+// * q and p are split into FP16 hi + lo parts (two MMAs each), so they keep ~22 bits: the result differs from+// the FP32 kernel by summation order and the exp2 rounding, not by an FP16 cast.+// Not bitwise equal to `qsa_decode_attn_batch`; `qsa_prompt_attn_parity` bounds the difference and the prompt+// quality gate (needles, teacher-forced top-1) checks it end to end. Q4_0 KV is not handled (returns false).+#pragma once++#include "strata/kernels/qsa_decode_attn.hpp"++#include <cstdint>++namespace strata::kernels {++/// Same arguments and output as `qsa_decode_attn_batch` minus the scratch. Returns false (nothing launched) when the+/// pools are Q4_0 or the geometry is not 24 heads / 2 KV heads / 256: the caller then uses the old kernel.+bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps,+ int64_t cap, const QsaShapes& s, float* attn, int64_t n_q, void* stream);++} // namespace strata::kernelsdiff --git a/src/kernels/cuda/qsa_prompt_attn.cu b/src/kernels/cuda/qsa_prompt_attn.cunew file mode 100644index 000000000..fac188b69--- /dev/null+++ b/src/kernels/cuda/qsa_prompt_attn.cu@@ -0,0 +1,625 @@+// src/kernels/cuda/qsa_prompt_attn.cu - see include/strata/kernels/qsa_prompt_attn.hpp.+#include "strata/kernels/qsa_prompt_attn.hpp"+#include "strata/kernels/kv_q8.hpp"++#include <cuda_fp16.h>+#include <cuda_runtime.h>+#include <math_constants.h>++#include <cstdio>+#include <cstdlib>+#include <type_traits>++namespace strata::kernels {+namespace {++constexpr int HD = 256; // head_dim+constexpr int G = 12; // query heads per KV head+#ifndef D1_CH+#define D1_CH 32+#endif+constexpr int CH = D1_CH; // cells per chunk+constexpr int THREADS = 128; // 4 warps: scores by cell (8 each), p.v by dimension (64 each = one int8 scale group)+constexpr int QS = HD + 8; // q row stride in halves (bank-conflict-free fragment loads)++__device__ __forceinline__ void mma16816(float* c, const uint32_t* a, const uint32_t* b) {+ asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, "+ "{%0,%1,%2,%3};\n"+ : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3])+ : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b[0]), "r"(b[1]));+}++// Two int8 codes (low byte first) as an exact half2: 1024 + (c + 128) built in the mantissa, minus 1152.+__device__ __forceinline__ uint32_t i8x2_to_h2(uint32_t x) {+ uint32_t y = ((x & 0xffu) | ((x & 0xff00u) << 8)) ^ 0x00800080u;+ y |= 0x64006400u;+ __half2 h = *reinterpret_cast<__half2*>(&y);+ h = __hsub2(h, __halves2half2(__float2half(1152.f), __float2half(1152.f)));+ return *reinterpret_cast<uint32_t*>(&h);+}++__device__ __forceinline__ uint32_t pack_h2(float lo_k, float hi_k) { // element k in the low half+ __half2 h = __floats2half2_rn(lo_k, hi_k);+ return *reinterpret_cast<uint32_t*>(&h);+}++// KV_MODE 1: int8 codes + fp16 scale per 64 values. KV_MODE 0: fp16 values (scales 1).+template <int KV_MODE>+struct Smem {+ using Elem = typename std::conditional<KV_MODE == 1, int8_t, __half>::type;+ static constexpr int ROW = KV_MODE == 1 ? HD + 16 : HD + 8; // elements; 16-byte aligned rows, banks spread+ __half qh[16][QS];+ __half ql[16][QS];+ Elem k[CH][ROW];+ Elem v[CH][ROW];+ float ks[CH][4];+ float vs[CH][4];+ float s[16][CH + 1];+ float qmax[THREADS / 32];+ float alpha[16];+ float lsum[16];+ float mrow[16];+ long long row[CH];+};++template <int KV_MODE>+__global__ void __launch_bounds__(THREADS) prompt_attn_kernel(const float* __restrict__ q, QsaAttnPools p,+ const int32_t* __restrict__ ids,+ const int32_t* __restrict__ steps, int n_kv_heads,+ int page_size, float scale_log2, float* __restrict__ attn,+ int cap) {+ extern __shared__ __align__(16) unsigned char smem_raw[];+ Smem<KV_MODE>& S = *reinterpret_cast<Smem<KV_MODE>*>(smem_raw);+ const int qi = blockIdx.x, kvh = blockIdx.y;+ const int n_head = n_kv_heads * G;+ q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;+ attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;+ ids += (size_t) qi * cap;+ const int n = __ldg(steps + (size_t) qi * kStepCount + kStepWidth);+ const int t = threadIdx.x, lane = t & 31, warp = t >> 5;+ const int gid = lane >> 2, tig = lane & 3;++ // q: 12 heads + 4 zero rows, scaled by a power of two that puts its largest value near 2^14 (exact, and the+ // lo halves stay out of FP16's subnormal range), then split into hi + lo halves+ float qm = 0.0f;+ for (int i = t; i < G * HD; i += THREADS) qm = fmaxf(qm, fabsf(q[i]));+#pragma unroll+ for (int o = 16; o > 0; o >>= 1) qm = fmaxf(qm, __shfl_xor_sync(0xffffffffu, qm, o));+ if (lane == 0) S.qmax[warp] = qm;+ __syncthreads();+ qm = fmaxf(fmaxf(S.qmax[0], S.qmax[1]), fmaxf(S.qmax[2], S.qmax[3]));+ int qe = 0;+ if (qm > 0.0f) frexpf(qm, &qe); // qm < 2^qe+ const float qup = ldexpf(1.0f, 14 - qe), qdown = ldexpf(scale_log2, qe - 14);+ for (int i = t; i < 16 * HD; i += THREADS) {+ const int h = i / HD, d = i % HD;+ const float x = h < G ? q[(size_t) h * HD + d] * qup : 0.0f;+ const __half hi = __float2half_rn(x);+ S.qh[h][d] = hi;+ S.ql[h][d] = __float2half_rn(x - __half2float(hi));+ }+ if (t < 16) { S.mrow[t] = -CUDART_INF_F; S.lsum[t] = 0.0f; }++ float acc[8][4];+#pragma unroll+ for (int j = 0; j < 8; ++j) acc[j][0] = acc[j][1] = acc[j][2] = acc[j][3] = 0.0f;++ for (int c0 = 0; c0 < n; c0 += CH) {+ const int nh = min(CH, n - c0);+ if (t < CH) {+ long long r = -1;+ if (t < nh) {+ const int cell = ids[c0 + t];+ const long long page = (long long) p.page_table[cell / page_size];+ r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);+ }+ S.row[t] = r;+ }+ __syncthreads(); // rows ready; the previous chunk's p.v is done with k, v, s+ // gather the chunk's K and V rows (16-byte pieces) and their scales+ {+ constexpr int PIECES = HD * (int) sizeof(typename Smem<KV_MODE>::Elem) / 16; // per row+ for (int i = t; i < CH * PIECES; i += THREADS) {+ const int c = i / PIECES, pc = i % PIECES;+ const long long r = S.row[c];+ uint4 kx = make_uint4(0, 0, 0, 0), vx = kx;+ if (r >= 0) {+ if constexpr (KV_MODE == 1) {+ kx = __ldg(reinterpret_cast<const uint4*>(p.k_q + r * HD) + pc);+ vx = __ldg(reinterpret_cast<const uint4*>(p.v_q + r * HD) + pc);+ } else {+ kx = __ldg(reinterpret_cast<const uint4*>(p.k_pool + r * HD) + pc);+ vx = __ldg(reinterpret_cast<const uint4*>(p.v_pool + r * HD) + pc);+ }+ }+ *reinterpret_cast<uint4*>(reinterpret_cast<unsigned char*>(&S.k[c][0]) + pc * 16) = kx;+ *reinterpret_cast<uint4*>(reinterpret_cast<unsigned char*>(&S.v[c][0]) + pc * 16) = vx;+ }+ for (int i = t; i < CH * 4; i += THREADS) {+ const int c = i / 4, g = i % 4;+ const long long r = S.row[c];+ float a = 0.0f, b = 0.0f;+ if (r >= 0) {+ if constexpr (KV_MODE == 1) {+ a = __half2float(__ushort_as_half(p.k_scale[r * (HD / KV_Q8_GROUP) + g]));+ b = __half2float(__ushort_as_half(p.v_scale[r * (HD / KV_Q8_GROUP) + g]));+ } else {+ a = b = 1.0f;+ }+ }+ S.ks[c][g] = a;+ S.vs[c][g] = b;+ }+ }+ __syncthreads();+ // scores: warp w takes cells 8w..8w+7 (one n-tile) over all 256 dims, per 64-dim scale group+#pragma unroll+ for (int nt = 0; nt < CH / 32; ++nt) {+ const int cb = (warp + 4 * nt) * 8;+ float sc[4] = {0.f, 0.f, 0.f, 0.f};+#pragma unroll+ for (int g = 0; g < 4; ++g) {+ float tg[4] = {0.f, 0.f, 0.f, 0.f};+#pragma unroll+ for (int kk = 0; kk < 4; ++kk) {+ const int k0 = (g * 4 + kk) * 16;+ uint32_t ah[4], al[4], b[2];+ ah[0] = *reinterpret_cast<const uint32_t*>(&S.qh[gid][k0 + 2 * tig]);+ ah[1] = *reinterpret_cast<const uint32_t*>(&S.qh[gid + 8][k0 + 2 * tig]);+ ah[2] = *reinterpret_cast<const uint32_t*>(&S.qh[gid][k0 + 2 * tig + 8]);+ ah[3] = *reinterpret_cast<const uint32_t*>(&S.qh[gid + 8][k0 + 2 * tig + 8]);+ al[0] = *reinterpret_cast<const uint32_t*>(&S.ql[gid][k0 + 2 * tig]);+ al[1] = *reinterpret_cast<const uint32_t*>(&S.ql[gid + 8][k0 + 2 * tig]);+ al[2] = *reinterpret_cast<const uint32_t*>(&S.ql[gid][k0 + 2 * tig + 8]);+ al[3] = *reinterpret_cast<const uint32_t*>(&S.ql[gid + 8][k0 + 2 * tig + 8]);+ if constexpr (KV_MODE == 1) {+ b[0] = i8x2_to_h2(*reinterpret_cast<const uint16_t*>(&S.k[cb + gid][k0 + 2 * tig]));+ b[1] = i8x2_to_h2(*reinterpret_cast<const uint16_t*>(&S.k[cb + gid][k0 + 2 * tig + 8]));+ } else {+ b[0] = *reinterpret_cast<const uint32_t*>(&S.k[cb + gid][k0 + 2 * tig]);+ b[1] = *reinterpret_cast<const uint32_t*>(&S.k[cb + gid][k0 + 2 * tig + 8]);+ }+ mma16816(tg, ah, b);+#ifndef D1_NO_QLO+ mma16816(tg, al, b);+#endif+ }+ const float s0 = S.ks[cb + 2 * tig][g], s1 = S.ks[cb + 2 * tig + 1][g];+ sc[0] = fmaf(tg[0], s0, sc[0]);+ sc[1] = fmaf(tg[1], s1, sc[1]);+ sc[2] = fmaf(tg[2], s0, sc[2]);+ sc[3] = fmaf(tg[3], s1, sc[3]);+ }+ const int c = cb + 2 * tig;+ S.s[gid][c] = c < nh ? sc[0] * qdown : -CUDART_INF_F;+ S.s[gid][c + 1] = c + 1 < nh ? sc[1] * qdown : -CUDART_INF_F;+ S.s[gid + 8][c] = c < nh ? sc[2] * qdown : -CUDART_INF_F;+ S.s[gid + 8][c + 1] = c + 1 < nh ? sc[3] * qdown : -CUDART_INF_F;+ }+ __syncthreads();+ // online softmax: row t/8, 4 cells per thread, 8 threads per row (lanes 8r..8r+7 of a warp)+ {+ constexpr int PER = CH / 8;+ const int r = t >> 3, sub = t & 7;+ float x[PER], mx = -CUDART_INF_F;+#pragma unroll+ for (int j = 0; j < PER; ++j) { x[j] = S.s[r][sub * PER + j]; mx = fmaxf(mx, x[j]); }+#pragma unroll+ for (int o = 1; o < 8; o <<= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, o));+ const float m_old = S.mrow[r];+ const float m_new = fmaxf(m_old, mx);+ float sum = 0.0f;+#pragma unroll+ for (int j = 0; j < PER; ++j) {+ const float e = x[j] == -CUDART_INF_F ? 0.0f : exp2f(x[j] - m_new);+ S.s[r][sub * PER + j] = e;+ sum += e;+ }+#pragma unroll+ for (int o = 1; o < 8; o <<= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o);+ __syncwarp();+ if (sub == 0) {+ const float a = m_old == -CUDART_INF_F ? 0.0f : exp2f(m_old - m_new);+ S.alpha[r] = a;+ S.lsum[r] = fmaf(S.lsum[r], a, sum);+ S.mrow[r] = m_new;+ }+ }+ __syncthreads();+ // p.v: warp w owns dims [64w, 64w+64), which is int8 scale group w. The scale is folded into p relative to+ // the chunk's largest, times 2^14 (p' <= 2^14: its lo half stays out of FP16's subnormal range); the chunk's+ // sum is then added to the running one in FP32 with the factor taken back out+ {+ float vmax = 0.0f;+#pragma unroll+ for (int c = lane; c < CH; c += 32) vmax = fmaxf(vmax, S.vs[c][warp]);+#pragma unroll+ for (int o = 16; o > 0; o >>= 1) vmax = fmaxf(vmax, __shfl_xor_sync(0xffffffffu, vmax, o));+ const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f, vdown = vmax * (1.0f / 16384.0f);+ float tmp[8][4];+#pragma unroll+ for (int j = 0; j < 8; ++j) tmp[j][0] = tmp[j][1] = tmp[j][2] = tmp[j][3] = 0.0f;+#pragma unroll+ for (int ks = 0; ks < CH / 16; ++ks) {+ const int cA = ks * 16 + 2 * tig, cB = cA + 8;+ const float w0 = S.vs[cA][warp] * vup, w1 = S.vs[cA + 1][warp] * vup, w2 = S.vs[cB][warp] * vup,+ w3 = S.vs[cB + 1][warp] * vup;+ const float p00 = S.s[gid][cA] * w0, p01 = S.s[gid][cA + 1] * w1;+ const float p10 = S.s[gid + 8][cA] * w0, p11 = S.s[gid + 8][cA + 1] * w1;+ const float p02 = S.s[gid][cB] * w2, p03 = S.s[gid][cB + 1] * w3;+ const float p12 = S.s[gid + 8][cB] * w2, p13 = S.s[gid + 8][cB + 1] * w3;+ uint32_t ah[4], al[4];+ ah[0] = pack_h2(p00, p01);+ ah[1] = pack_h2(p10, p11);+ ah[2] = pack_h2(p02, p03);+ ah[3] = pack_h2(p12, p13);+ {+ const __half2* h = reinterpret_cast<const __half2*>(ah);+ float2 f;+ f = __half22float2(h[0]); al[0] = pack_h2(p00 - f.x, p01 - f.y);+ f = __half22float2(h[1]); al[1] = pack_h2(p10 - f.x, p11 - f.y);+ f = __half22float2(h[2]); al[2] = pack_h2(p02 - f.x, p03 - f.y);+ f = __half22float2(h[3]); al[3] = pack_h2(p12 - f.x, p13 - f.y);+ }+#pragma unroll+ for (int j = 0; j < 8; ++j) {+ const int d = warp * 64 + j * 8 + gid;+ uint32_t b[2];+ if constexpr (KV_MODE == 1) {+ const uint32_t x0 = (uint8_t) S.v[cA][d] | ((uint32_t) (uint8_t) S.v[cA + 1][d] << 8);+ const uint32_t x1 = (uint8_t) S.v[cB][d] | ((uint32_t) (uint8_t) S.v[cB + 1][d] << 8);+ b[0] = i8x2_to_h2(x0);+ b[1] = i8x2_to_h2(x1);+ } else {+ const __half2 h0 = __halves2half2(S.v[cA][d], S.v[cA + 1][d]);+ const __half2 h1 = __halves2half2(S.v[cB][d], S.v[cB + 1][d]);+ b[0] = *reinterpret_cast<const uint32_t*>(&h0);+ b[1] = *reinterpret_cast<const uint32_t*>(&h1);+ }+ mma16816(tmp[j], ah, b);+#ifndef D1_NO_PLO+ mma16816(tmp[j], al, b);+#endif+ }+ }+ const float a0 = S.alpha[gid], a1 = S.alpha[gid + 8];+#pragma unroll+ for (int j = 0; j < 8; ++j) {+ acc[j][0] = fmaf(acc[j][0], a0, tmp[j][0] * vdown);+ acc[j][1] = fmaf(acc[j][1], a0, tmp[j][1] * vdown);+ acc[j][2] = fmaf(acc[j][2], a1, tmp[j][2] * vdown);+ acc[j][3] = fmaf(acc[j][3], a1, tmp[j][3] * vdown);+ }+ }+ }+ __syncthreads();+ const float l0 = S.lsum[gid], l1 = S.lsum[gid + 8];+ const float i0 = l0 > 0.0f ? 1.0f / l0 : 0.0f, i1 = l1 > 0.0f ? 1.0f / l1 : 0.0f;+#pragma unroll+ for (int j = 0; j < 8; ++j) {+ const int d = warp * 64 + j * 8 + 2 * tig;+ *reinterpret_cast<float2*>(attn + (size_t) gid * HD + d) = make_float2(acc[j][0] * i0, acc[j][1] * i0);+ if (gid + 8 < G)+ *reinterpret_cast<float2*>(attn + (size_t) (gid + 8) * HD + d) = make_float2(acc[j][2] * i1, acc[j][3] * i1);+ }+}++// ---- v2 (int8 KV): warp w owns dims [64w, 64w+64) for both q.k and p.v, which is also int8 scale group w. So a+// warp needs only its own 64-byte slice of each K and V row: it gathers it itself with cp.async into its own+// double-buffered stage while it computes the previous chunk, and q stays in registers. Only the q.k partial sums+// (one per dim group) cross warps, and they are added in a fixed order: the result is deterministic.+constexpr int CH2 = 32;++struct Smem2 {+ int8_t kv[2][4][2][CH2][64]; // stage, warp, K/V, cell, 64 dims in 16-byte pieces XOR-swizzled by the cell+ float sc[2][4][2][CH2]; // stage, warp, K/V scale of the cell for the warp's group+ float part[4][16][CH2 + 1]; // q.k per dim group+ float p[16][CH2 + 1];+ float qmax[4];+ float alpha[16];+ float lsum[16];+ float mrow[16];+};++__device__ __forceinline__ int swz(int cell, int byte) { // byte offset of (cell, byte) in a stage slice+ return cell * 64 + ((((byte >> 4) ^ (cell >> 1)) & 3) << 4) + (byte & 15);+}+__device__ __forceinline__ void cp_async16(void* smem, const void* gmem, bool valid) {+ const unsigned sa = (unsigned) __cvta_generic_to_shared(smem);+ asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;\n" ::"r"(sa), "l"(gmem), "r"(valid ? 16 : 0));+}+__device__ __forceinline__ void cp_async_commit() { asm volatile("cp.async.commit_group;\n" ::); }+__device__ __forceinline__ void cp_async_wait1() { asm volatile("cp.async.wait_group 1;\n" ::); }++__global__ void __launch_bounds__(THREADS) prompt_attn_i8_kernel(const float* __restrict__ q, QsaAttnPools p,+ const int32_t* __restrict__ ids,+ const int32_t* __restrict__ steps, int n_kv_heads,+ int page_size, float scale_log2,+ float* __restrict__ attn, int cap) {+ extern __shared__ __align__(16) unsigned char smem_raw[];+ Smem2& S = *reinterpret_cast<Smem2*>(smem_raw);+ const int qi = blockIdx.x, kvh = blockIdx.y;+ const int n_head = n_kv_heads * G;+ q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;+ attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;+ ids += (size_t) qi * cap;+ const int n = __ldg(steps + (size_t) qi * kStepCount + kStepWidth);+ const int t = threadIdx.x, lane = t & 31, warp = t >> 5;+ const int gid = lane >> 2, tig = lane & 3;+ const int dim0 = warp * 64;++ // q: the power-of-two prescale over all 12 heads (as v1), then this warp's 64 dims as hi/lo A fragments+ float qm = 0.0f;+ for (int i = t; i < G * HD; i += THREADS) qm = fmaxf(qm, fabsf(q[i]));+#pragma unroll+ for (int o = 16; o > 0; o >>= 1) qm = fmaxf(qm, __shfl_xor_sync(0xffffffffu, qm, o));+ if (lane == 0) S.qmax[warp] = qm;+ if (t < 16) { S.mrow[t] = -CUDART_INF_F; S.lsum[t] = 0.0f; }+ __syncthreads();+ qm = fmaxf(fmaxf(S.qmax[0], S.qmax[1]), fmaxf(S.qmax[2], S.qmax[3]));+ int qe = 0;+ if (qm > 0.0f) frexpf(qm, &qe);+ const float qup = ldexpf(1.0f, 14 - qe), qdown = ldexpf(scale_log2, qe - 14);+ uint32_t qh[4][4], ql[4][4];+#pragma unroll+ for (int kk = 0; kk < 4; ++kk) {+#pragma unroll+ for (int r = 0; r < 4; ++r) {+ const int row = gid + (r & 1) * 8, col = dim0 + kk * 16 + 2 * tig + (r >> 1) * 8;+ float2 x = make_float2(0.f, 0.f);+ if (row < G) x = *reinterpret_cast<const float2*>(q + (size_t) row * HD + col);+ x.x *= qup;+ x.y *= qup;+ const __half2 hi = __floats2half2_rn(x.x, x.y);+ const float2 hf = __half22float2(hi);+ const __half2 lo = __floats2half2_rn(x.x - hf.x, x.y - hf.y);+ qh[kk][r] = *reinterpret_cast<const uint32_t*>(&hi);+ ql[kk][r] = *reinterpret_cast<const uint32_t*>(&lo);+ }+ }++ // the chunk pipeline: cells two chunks ahead, their pool rows one chunk ahead, the data (cp.async) one ahead+ const int n_chunks = (n + CH2 - 1) / CH2;+ auto cell_of = [&](int c) -> int { return c < n ? __ldg(ids + c) : -1; };+ auto row_of = [&](int cell) -> long long {+ if (cell < 0) return -1;+ const long long page = (long long) __ldg(p.page_table + cell / page_size);+ return (page * n_kv_heads + kvh) * page_size + (cell % page_size);+ };+ auto issue = [&](long long r, int st, float& ksr, float& vsr) {+#pragma unroll+ for (int j = 0; j < 4; ++j) {+ const int idx = lane + 32 * j, cell = idx >> 2, pc = idx & 3;+ const long long rr = __shfl_sync(0xffffffffu, r, cell);+ const bool ok = rr >= 0;+ const size_t off = ok ? (size_t) rr * HD + dim0 + pc * 16 : 0;+ cp_async16(&S.kv[st][warp][0][0][0] + swz(cell, pc * 16), p.k_q + off, ok);+ cp_async16(&S.kv[st][warp][1][0][0] + swz(cell, pc * 16), p.v_q + off, ok);+ }+ ksr = r >= 0 ? __half2float(__ushort_as_half(__ldg(p.k_scale + r * (HD / KV_Q8_GROUP) + warp))) : 0.0f;+ vsr = r >= 0 ? __half2float(__ushort_as_half(__ldg(p.v_scale + r * (HD / KV_Q8_GROUP) + warp))) : 0.0f;+ };+ float ksn, vsn;+ issue(row_of(cell_of(lane)), 0, ksn, vsn);+ cp_async_commit();+ S.sc[0][warp][0][lane] = ksn;+ S.sc[0][warp][1][lane] = vsn;+ long long r_next = row_of(cell_of(CH2 + lane));+ int cell_next2 = cell_of(2 * CH2 + lane);++ float acc[8][4];+#pragma unroll+ for (int j = 0; j < 8; ++j) acc[j][0] = acc[j][1] = acc[j][2] = acc[j][3] = 0.0f;++ for (int ci = 0; ci < n_chunks; ++ci) {+ const int st = ci & 1, c0 = ci * CH2;+ const bool more = ci + 1 < n_chunks;+ if (more) issue(r_next, st ^ 1, ksn, vsn);+ cp_async_commit();+ r_next = row_of(cell_next2);+ cell_next2 = cell_of((ci + 3) * CH2 + lane);+ cp_async_wait1();+ __syncwarp();+ const int8_t* K = &S.kv[st][warp][0][0][0];+ const int8_t* V = &S.kv[st][warp][1][0][0];+ // q.k over this warp's 64 dims, times the cell's K scale for this group+#pragma unroll+ for (int nt = 0; nt < CH2 / 8; ++nt) {+ float tg[4] = {0.f, 0.f, 0.f, 0.f};+ const int cell = nt * 8 + gid;+#pragma unroll+ for (int kk = 0; kk < 4; ++kk) {+ uint32_t b[2];+ b[0] = i8x2_to_h2(*reinterpret_cast<const uint16_t*>(K + swz(cell, kk * 16 + 2 * tig)));+ b[1] = i8x2_to_h2(*reinterpret_cast<const uint16_t*>(K + swz(cell, kk * 16 + 2 * tig + 8)));+ mma16816(tg, qh[kk], b);+ mma16816(tg, ql[kk], b);+ }+ const int c = nt * 8 + 2 * tig;+ const float s0 = S.sc[st][warp][0][c], s1 = S.sc[st][warp][0][c + 1];+ S.part[warp][gid][c] = tg[0] * s0;+ S.part[warp][gid][c + 1] = tg[1] * s1;+ S.part[warp][gid + 8][c] = tg[2] * s0;+ S.part[warp][gid + 8][c + 1] = tg[3] * s1;+ }+ __syncthreads();+ // online softmax over the four groups' sum (fixed order): row t/8, 4 cells per thread+ {+ const int r = t >> 3, sub = t & 7;+ float x[4], mx = -CUDART_INF_F;+#pragma unroll+ for (int j = 0; j < 4; ++j) {+ const int c = sub * 4 + j;+ x[j] = c0 + c < n ? (((S.part[0][r][c] + S.part[1][r][c]) + S.part[2][r][c]) + S.part[3][r][c]) * qdown+ : -CUDART_INF_F;+ mx = fmaxf(mx, x[j]);+ }+#pragma unroll+ for (int o = 1; o < 8; o <<= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, o));+ const float m_old = S.mrow[r];+ const float m_new = fmaxf(m_old, mx);+ float sum = 0.0f;+#pragma unroll+ for (int j = 0; j < 4; ++j) {+ const float e = x[j] == -CUDART_INF_F ? 0.0f : exp2f(x[j] - m_new);+ S.p[r][sub * 4 + j] = e;+ sum += e;+ }+#pragma unroll+ for (int o = 1; o < 8; o <<= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o);+ __syncwarp();+ if (sub == 0) {+ const float a = m_old == -CUDART_INF_F ? 0.0f : exp2f(m_old - m_new);+ S.alpha[r] = a;+ S.lsum[r] = fmaf(S.lsum[r], a, sum);+ S.mrow[r] = m_new;+ }+ }+ __syncthreads();+ // p.v over this warp's 64 dims (as v1)+ {+ float vmax = S.sc[st][warp][1][lane];+#pragma unroll+ for (int o = 16; o > 0; o >>= 1) vmax = fmaxf(vmax, __shfl_xor_sync(0xffffffffu, vmax, o));+ const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f, vdown = vmax * (1.0f / 16384.0f);+ float tmp[8][4];+#pragma unroll+ for (int j = 0; j < 8; ++j) tmp[j][0] = tmp[j][1] = tmp[j][2] = tmp[j][3] = 0.0f;+#pragma unroll+ for (int ks = 0; ks < CH2 / 16; ++ks) {+ const int cA = ks * 16 + 2 * tig, cB = cA + 8;+ const float w0 = S.sc[st][warp][1][cA] * vup, w1 = S.sc[st][warp][1][cA + 1] * vup,+ w2 = S.sc[st][warp][1][cB] * vup, w3 = S.sc[st][warp][1][cB + 1] * vup;+ const float p00 = S.p[gid][cA] * w0, p01 = S.p[gid][cA + 1] * w1;+ const float p10 = S.p[gid + 8][cA] * w0, p11 = S.p[gid + 8][cA + 1] * w1;+ const float p02 = S.p[gid][cB] * w2, p03 = S.p[gid][cB + 1] * w3;+ const float p12 = S.p[gid + 8][cB] * w2, p13 = S.p[gid + 8][cB + 1] * w3;+ uint32_t ah[4], al[4];+ ah[0] = pack_h2(p00, p01);+ ah[1] = pack_h2(p10, p11);+ ah[2] = pack_h2(p02, p03);+ ah[3] = pack_h2(p12, p13);+ {+ const __half2* h = reinterpret_cast<const __half2*>(ah);+ float2 f;+ f = __half22float2(h[0]); al[0] = pack_h2(p00 - f.x, p01 - f.y);+ f = __half22float2(h[1]); al[1] = pack_h2(p10 - f.x, p11 - f.y);+ f = __half22float2(h[2]); al[2] = pack_h2(p02 - f.x, p03 - f.y);+ f = __half22float2(h[3]); al[3] = pack_h2(p12 - f.x, p13 - f.y);+ }+#pragma unroll+ for (int j = 0; j < 8; ++j) {+ const int d = j * 8 + gid;+ const uint32_t x0 = (uint8_t) V[swz(cA, d)] | ((uint32_t) (uint8_t) V[swz(cA + 1, d)] << 8);+ const uint32_t x1 = (uint8_t) V[swz(cB, d)] | ((uint32_t) (uint8_t) V[swz(cB + 1, d)] << 8);+ uint32_t b[2];+ b[0] = i8x2_to_h2(x0);+ b[1] = i8x2_to_h2(x1);+ mma16816(tmp[j], ah, b);+ mma16816(tmp[j], al, b);+ }+ }+ const float a0 = S.alpha[gid], a1 = S.alpha[gid + 8];+#pragma unroll+ for (int j = 0; j < 8; ++j) {+ acc[j][0] = fmaf(acc[j][0], a0, tmp[j][0] * vdown);+ acc[j][1] = fmaf(acc[j][1], a0, tmp[j][1] * vdown);+ acc[j][2] = fmaf(acc[j][2], a1, tmp[j][2] * vdown);+ acc[j][3] = fmaf(acc[j][3], a1, tmp[j][3] * vdown);+ }+ }+ if (more) {+ S.sc[st ^ 1][warp][0][lane] = ksn;+ S.sc[st ^ 1][warp][1][lane] = vsn;+ }+ __syncwarp();+ }+ __syncthreads();+ const float l0 = S.lsum[gid], l1 = S.lsum[gid + 8];+ const float i0 = l0 > 0.0f ? 1.0f / l0 : 0.0f, i1 = l1 > 0.0f ? 1.0f / l1 : 0.0f;+#pragma unroll+ for (int j = 0; j < 8; ++j) {+ const int d = dim0 + j * 8 + 2 * tig;+ *reinterpret_cast<float2*>(attn + (size_t) gid * HD + d) = make_float2(acc[j][0] * i0, acc[j][1] * i0);+ if (gid + 8 < G)+ *reinterpret_cast<float2*>(attn + (size_t) (gid + 8) * HD + d) = make_float2(acc[j][2] * i1, acc[j][3] * i1);+ }+}++bool launch_i8(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap,+ const QsaShapes& s, float* attn, int64_t n_q, cudaStream_t st) {+ static bool attr = false;+ const int bytes = (int) sizeof(Smem2);+ if (!attr) {+ if (cudaFuncSetAttribute(prompt_attn_i8_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) !=+ cudaSuccess) {+ cudaGetLastError();+ return false;+ }+ attr = true;+ }+ const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD);+ for (int64_t q0 = 0; q0 < n_q; q0 += 65535) {+ const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535;+ prompt_attn_i8_kernel<<<dim3((unsigned) nb, (unsigned) s.n_head_kv), THREADS, bytes, st>>>(+ q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv,+ (int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap);+ }+ const cudaError_t e = cudaGetLastError();+ if (e != cudaSuccess) {+ std::fprintf(stderr, "qsa_prompt_attn_batch: %s\n", cudaGetErrorString(e));+ std::exit(1);+ }+ return true;+}++template <int KV_MODE>+bool launch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap,+ const QsaShapes& s, float* attn, int64_t n_q, cudaStream_t st) {+ static bool attr = false;+ const int bytes = (int) sizeof(Smem<KV_MODE>);+ if (!attr) {+ if (cudaFuncSetAttribute(prompt_attn_kernel<KV_MODE>, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) !=+ cudaSuccess) {+ cudaGetLastError();+ return false;+ }+ attr = true;+ }+ const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD);+ for (int64_t q0 = 0; q0 < n_q; q0 += 65535) {+ const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535;+ prompt_attn_kernel<KV_MODE><<<dim3((unsigned) nb, (unsigned) s.n_head_kv), THREADS, bytes, st>>>(+ q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv,+ (int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap);+ }+ const cudaError_t e = cudaGetLastError();+ if (e != cudaSuccess) {+ std::fprintf(stderr, "qsa_prompt_attn_batch: %s\n", cudaGetErrorString(e));+ std::exit(1);+ }+ return true;+}++} // namespace++bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps,+ int64_t cap, const QsaShapes& s, float* attn, int64_t n_q, void* stream) {+ if (n_q <= 0) return true;+ if (pools.k_q4 != nullptr || s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !ids ||+ !steps || !pools.page_table)+ return false;+ cudaStream_t st = (cudaStream_t) stream;+ if (pools.k_q != nullptr) {+ if (!pools.v_q || !pools.k_scale || !pools.v_scale) return false;+ // STRATA_PROMPT_ATTN_V1=1 (debug): the first version, same accuracy, another summation order - the control+ // for how far the model amplifies an FP32-level change+ static const bool v1 = std::getenv("STRATA_PROMPT_ATTN_V1") != nullptr;+ if (v1) return launch<1>(q, pools, ids, steps, cap, s, attn, n_q, st);+ return launch_i8(q, pools, ids, steps, cap, s, attn, n_q, st);+ }+ if (!pools.k_pool || !pools.v_pool) return false;+ return launch<0>(q, pools, ids, steps, cap, s, attn, n_q, st);+}++} // namespace strata::kernelsdiff --git a/src/kernels/qsa_prompt_attn_parity.cpp b/src/kernels/qsa_prompt_attn_parity.cppnew file mode 100644index 000000000..3b3fe1945--- /dev/null+++ b/src/kernels/qsa_prompt_attn_parity.cpp@@ -0,0 +1,209 @@+// src/kernels/qsa_prompt_attn_parity.cpp - perf-review D-1: the tensor-core prompt attention (qsa_prompt_attn.hpp)+// against the FP32 kernel it replaces (`qsa_decode_attn_batch`) and an FP64 host reference (GPU, synthetic, no model).+//+// Int8 and FP16 pools with random codes, scales and queries; selections shaped like the prompt path's (the 2,051+// widest, a recent window plus older cells that drift slowly from one query to the next, so neighbours share most+// of them as they do in a real prompt; short contexts take every cell). Checks:+// 1. against FP64, the new kernel's error is no larger than a small multiple of the old kernel's (both FP32 math);+// 2. the new and old outputs agree to a relative 1e-4 of the output scale;+// then times both over a prompt chunk (the old one in batches of 32, as prefill.cpp calls it).+// Usage: qsa_prompt_attn_parity [context=32768] [queries=2048] [reps=5]+#include "strata/kernels/qsa.hpp"+#include "strata/kernels/qsa_decode_attn.hpp"+#include "strata/kernels/qsa_prompt_attn.hpp"++#include <cuda_fp16.h>+#include <cuda_runtime.h>++#include <algorithm>+#include <cmath>+#include <cstdio>+#include <cstdlib>+#include <random>+#include <vector>++namespace k = strata::kernels;++namespace {+void ck(cudaError_t e, const char* w) {+ if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); }+}+template <typename T> T* up(const std::vector<T>& h) {+ T* d = nullptr;+ ck(cudaMalloc(&d, h.size() * sizeof(T) + 64), "malloc");+ ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload");+ return d;+}+float h2f(uint16_t b) { __half h; *reinterpret_cast<uint16_t*>(&h) = b; return __half2float(h); }+uint16_t f2h(float f) { __half h = __float2half(f); return *reinterpret_cast<uint16_t*>(&h); }++int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16+ const k::QsaShapes s = k::qsa_real_shapes();+ const int64_t HD = s.head_dim, NKV = s.n_head_kv, NH = s.n_head, PS = s.page_size;+ const int64_t pages = (ctx + PS - 1) / PS, rows = pages * NKV * PS;+ std::mt19937 rng(1234 + fmt);+ std::normal_distribution<float> nd(0.f, 1.f);+ std::uniform_int_distribution<int> code(-127, 127);+ std::uniform_real_distribution<float> sc(0.005f, 0.03f);+ // pools; page table a shuffled permutation (the readers must follow it)+ std::vector<int8_t> kq, vq;+ std::vector<uint16_t> ks, vs, kh, vh;+ if (fmt == 1) {+ kq.resize(rows * HD); vq.resize(rows * HD); ks.resize(rows * 4); vs.resize(rows * 4);+ for (auto& x : kq) x = (int8_t) code(rng);+ for (auto& x : vq) x = (int8_t) code(rng);+ for (auto& x : ks) x = f2h(sc(rng));+ for (auto& x : vs) x = f2h(sc(rng));+ } else {+ kh.resize(rows * HD); vh.resize(rows * HD);+ for (auto& x : kh) x = f2h(nd(rng) * 1.5f);+ for (auto& x : vh) x = f2h(nd(rng));+ }+ std::vector<int32_t> table(pages);+ for (int64_t i = 0; i < pages; ++i) table[i] = (int32_t) i;+ std::shuffle(table.begin(), table.end(), rng);+ // queries at positions ctx - nq .. ctx - 1+ const int64_t cap = k::qsa_selection_width(ctx, s);+ std::vector<int32_t> ids((size_t) (nq * cap), 0), steps((size_t) (nq * k::kStepCount), 0);+ std::vector<float> q((size_t) (nq * NH * HD));+ for (auto& x : q) x = nd(rng) * 2.0f;+ std::vector<int32_t> old_cells;+ for (int64_t i = 0; i < nq; ++i) {+ const int64_t pos = ctx - nq + i, nkv = pos + 1;+ const int64_t w = k::qsa_selection_width(nkv, s);+ int32_t* sel = ids.data() + i * cap;+ steps[i * k::kStepCount + k::kStepWidth] = (int32_t) w;+ if (w == nkv) {+ for (int64_t c = 0; c < w; ++c) sel[c] = (int32_t) c;+ continue;+ }+ const int64_t recent = 512, older = w - recent;+ if ((int64_t) old_cells.size() != older) { // the older cells: a set that drifts ~3% per query+ std::vector<int32_t> all((size_t) (nkv - recent));+ for (int64_t c = 0; c < nkv - recent; ++c) all[c] = (int32_t) c;+ std::shuffle(all.begin(), all.end(), rng);+ old_cells.assign(all.begin(), all.begin() + older);+ } else {+ std::uniform_int_distribution<int64_t> pick(0, older - 1), any(0, nkv - recent - 1);+ for (int r = 0; r < older / 32; ++r) {+ const int32_t c = (int32_t) any(rng);+ if (std::find(old_cells.begin(), old_cells.end(), c) == old_cells.end()) old_cells[pick(rng)] = c;+ }+ }+ std::vector<int32_t> v(old_cells);+ for (int64_t c = nkv - recent; c < nkv; ++c) v.push_back((int32_t) c);+ std::sort(v.begin(), v.end());+ std::copy(v.begin(), v.end(), sel);+ }+ k::QsaAttnPools pl;+ if (fmt == 1) { pl.k_q = up(kq); pl.v_q = up(vq); pl.k_scale = up(ks); pl.v_scale = up(vs); }+ else { pl.k_pool = up(kh); pl.v_pool = up(vh); }+ pl.page_table = up(table);+ const int32_t* d_ids = up(ids);+ const int32_t* d_steps = up(steps);+ const float* d_q = up(q);+ float *d_old = nullptr, *d_new = nullptr, *scratch = nullptr;+ const int64_t batch = 32;+ ck(cudaMalloc(&d_old, nq * NH * HD * 4), "malloc");+ ck(cudaMalloc(&d_new, nq * NH * HD * 4), "malloc");+ ck(cudaMalloc(&scratch, batch * k::qsa_decode_attn_scratch_floats(cap, s) * 4), "malloc");+ auto old_run = [&]() {+ for (int64_t t0 = 0; t0 < nq; t0 += batch)+ k::qsa_decode_attn_batch(d_q + t0 * NH * HD, pl, d_ids + t0 * cap, d_steps + t0 * k::kStepCount, cap, s,+ scratch, d_old + t0 * NH * HD, std::min(batch, nq - t0), nullptr);+ };+ auto new_run = [&]() {+ if (!k::qsa_prompt_attn_batch(d_q, pl, d_ids, d_steps, cap, s, d_new, nq, nullptr)) {+ std::fprintf(stderr, "qsa_prompt_attn_batch refused the pools\n");+ std::exit(2);+ }+ };+ old_run();+ new_run();+ ck(cudaDeviceSynchronize(), "run");+ std::vector<float> o((size_t) (nq * NH * HD)), nw(o.size());+ ck(cudaMemcpy(o.data(), d_old, o.size() * 4, cudaMemcpyDeviceToHost), "down");+ ck(cudaMemcpy(nw.data(), d_new, nw.size() * 4, cudaMemcpyDeviceToHost), "down");+ // 1. FP64 reference on a sample of queries+ double err_old = 0, err_new = 0, ref_scale = 0;+ for (int64_t i = 0; i < nq; i += std::max<int64_t>(1, nq / 16)) {+ const int64_t w = steps[i * k::kStepCount + k::kStepWidth];+ const int32_t* sel = ids.data() + i * cap;+ for (int64_t h = 0; h < NH; ++h) {+ const int64_t kvh = h / (NH / NKV);+ std::vector<double> sco((size_t) w);+ double mx = -1e300;+ for (int64_t c = 0; c < w; ++c) {+ const int64_t cell = sel[c], row = ((int64_t) table[cell / PS] * NKV + kvh) * PS + cell % PS;+ double a = 0;+ for (int64_t d = 0; d < HD; ++d) {+ const double kv = fmt == 1 ? (double) kq[row * HD + d] * h2f(ks[row * 4 + d / 64]) : h2f(kh[row * HD + d]);+ a += (double) q[(i * NH + h) * HD + d] * kv;+ }+ sco[c] = a / 16.0;+ mx = std::max(mx, sco[c]);+ }+ double l = 0;+ for (auto& x : sco) { x = std::exp(x - mx); l += x; }+ for (int64_t d = 0; d < HD; ++d) {+ double a = 0;+ for (int64_t c = 0; c < w; ++c) {+ const int64_t cell = sel[c], row = ((int64_t) table[cell / PS] * NKV + kvh) * PS + cell % PS;+ const double vv = fmt == 1 ? (double) vq[row * HD + d] * h2f(vs[row * 4 + d / 64]) : h2f(vh[row * HD + d]);+ a += sco[c] * vv;+ }+ const double r = a / l;+ const size_t at = (size_t) ((i * NH + h) * HD + d);+ ref_scale = std::max(ref_scale, std::fabs(r));+ err_old = std::max(err_old, std::fabs(o[at] - r));+ err_new = std::max(err_new, std::fabs(nw[at] - r));+ }+ }+ }+ // 2. new vs old everywhere+ double diff = 0, scale = 0;+ for (size_t i = 0; i < o.size(); ++i) {+ diff = std::max(diff, (double) std::fabs(o[i] - nw[i]));+ scale = std::max(scale, (double) std::fabs(o[i]));+ }+ // 3. speed+ cudaEvent_t e0, e1;+ cudaEventCreate(&e0);+ cudaEventCreate(&e1);+ float ms_old = 0, ms_new = 0;+ cudaEventRecord(e0);+ for (int r = 0; r < reps; ++r) old_run();+ cudaEventRecord(e1);+ ck(cudaEventSynchronize(e1), "time");+ cudaEventElapsedTime(&ms_old, e0, e1);+ cudaEventRecord(e0);+ for (int r = 0; r < reps; ++r) new_run();+ cudaEventRecord(e1);+ ck(cudaEventSynchronize(e1), "time");+ cudaEventElapsedTime(&ms_new, e0, e1);+ const bool ok1 = err_new <= std::max(4.0 * err_old, 1e-6 * ref_scale);+ const bool ok2 = diff <= 1e-4 * scale;+ std::printf("%s %s ctx %lld, %lld queries: vs FP64 old %.3g new %.3g (output scale %.3g); new vs old %.3g (%.2g of "+ "scale); %.3f -> %.3f ms per chunk (%.2fx)\n",+ ok1 && ok2 ? "PASS" : "FAIL", fmt == 1 ? "int8" : "fp16", (long long) ctx, (long long) nq, err_old,+ err_new, ref_scale, diff, diff / scale, ms_old / reps, ms_new / reps, ms_old / ms_new);+ cudaFree((void*) d_ids); cudaFree((void*) d_steps); cudaFree((void*) d_q); cudaFree(d_old); cudaFree(d_new);+ cudaFree(scratch);+ cudaFree((void*) pl.k_q); cudaFree((void*) pl.v_q); cudaFree((void*) pl.k_scale); cudaFree((void*) pl.v_scale);+ cudaFree((void*) pl.k_pool); cudaFree((void*) pl.v_pool); cudaFree((void*) pl.page_table);+ return ok1 && ok2 ? 0 : 1;+}+} // namespace++int main(int argc, char** argv) {+ const int64_t ctx = argc > 1 ? std::atoll(argv[1]) : 32768;+ const int64_t nq = argc > 2 ? std::atoll(argv[2]) : 2048;+ const int reps = argc > 3 ? std::atoi(argv[3]) : 5;+ int fails = 0;+ fails += run(1, ctx, nq, reps);+ fails += run(0, ctx, nq, reps);+ fails += run(1, 1500, std::min<int64_t>(nq, 1500), reps); // short context: the selection is every cell+ fails += run(1, 2100, std::min<int64_t>(nq, 256), reps); // the identity-to-sparse edge+ std::printf("FAILURES: %d\n", fails);+ return fails;+}diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cppindex f57670a16..81eb292f4 100644--- a/src/prefill/prefill.cpp+++ b/src/prefill/prefill.cpp@@ -19,6 +19,7 @@#include "strata/core/native_head.hpp"#include "strata/kernels/verify_kernels.hpp"#include "strata/kernels/qsa_decode_attn.hpp"+#include "strata/kernels/qsa_prompt_attn.hpp"#include "strata/kernels/qsa_select.hpp"#include "strata/prefill/gemm.hpp"#include "strata/prefill/moe_mmq.hpp"@@ -1164,6 +1165,26 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& estrata::kernels::qsa_block_topk(m.sel_scores, steps0, nb, m.max_blocks, m.cap, s,m.sel_ids + t0 * m.cap, m.cs);}+ // STRATA_SEL_OVERLAP (debug, D-1's question): how much do neighbouring queries' selections share?+ // Per tile of 16 queries: the union of their selected cells against the sum of their widths.+ if (static const bool ovl = std::getenv("STRATA_SEL_OVERLAP") != nullptr; ovl && qsa_index == 0) {+ std::vector<int32_t> ids((size_t) (T * m.cap));+ cudaMemcpyAsync(ids.data(), m.sel_ids, ids.size() * 4, cudaMemcpyDeviceToHost, m.cs);+ cudaStreamSynchronize(m.cs);+ double sum_w = 0, sum_u = 0;+ for (int64_t t0 = 0; t0 + 16 <= T; t0 += 16) {+ std::vector<int32_t> u;+ for (int64_t t = t0; t < t0 + 16; ++t) {+ const int64_t w = m.steps_host[(size_t) (t * strata::kernels::kStepCount + strata::kernels::kStepWidth)];+ sum_w += (double) w;+ u.insert(u.end(), ids.begin() + t * m.cap, ids.begin() + t * m.cap + w);+ }+ std::sort(u.begin(), u.end());+ sum_u += (double) (std::unique(u.begin(), u.end()) - u.begin());+ }+ std::fprintf(stderr, "strata prefill: selection overlap at %lld: 16-query tiles read %.1f%% of the "+ "cells one query at a time does\n", (long long) p0, sum_w > 0 ? 100.0 * sum_u / sum_w : 0.0);+ }// STRATA_IDX_FP16_CHECK: would FP16 pooled indexer keys select the same cells? (the KV-streaming// design's last question). Every query is selected again from the pooled keys and `dead` rounded// to fp16 (exactly what an fp16 store reads back); the agreement with the fp32 selection is@@ -1232,12 +1253,18 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& econst strata::kernels::QsaAttnPools pools = staged ? pools_of(m.stage, m.ident_table): core::qsa_attn_pools(st);pt.mark(kPfQsaAttn, cs);- for (int64_t t0 = 0; t0 < T; t0 += m.attn_batch) {- const int64_t nb = std::min(m.attn_batch, T - t0);- strata::kernels::qsa_decode_attn_batch(m.q + t0 * ZV, pools, m.sel_ids + t0 * m.cap,- m.steps_dev + t0 * strata::kernels::kStepCount, m.cap, s,- m.attn_scratch, m.attn + t0 * ZV, nb, m.cs);- }+ // perf-review D-1: the whole chunk on tensor cores, one block per (query, KV head), FP32-level+ // accuracy but not bitwise (qsa_prompt_attn.hpp). Q4_0 KV, or STRATA_PROMPT_ATTN_OLD=1: the+ // decode kernel, 32 queries at a time+ static const bool old_attn = std::getenv("STRATA_PROMPT_ATTN_OLD") != nullptr;+ if (old_attn || !strata::kernels::qsa_prompt_attn_batch(m.q, pools, m.sel_ids, m.steps_dev, m.cap, s,+ m.attn, T, m.cs))+ for (int64_t t0 = 0; t0 < T; t0 += m.attn_batch) {+ const int64_t nb = std::min(m.attn_batch, T - t0);+ strata::kernels::qsa_decode_attn_batch(m.q + t0 * ZV, pools, m.sel_ids + t0 * m.cap,+ m.steps_dev + t0 * strata::kernels::kStepCount, m.cap,+ s, m.attn_scratch, m.attn + t0 * ZV, nb, m.cs);+ }if (st.kv_q4) strata::kernels::fwht256_inplace_cuda(m.attn, T * 24, m.cs);pt.mark(kPfQsa, cs);gate_attn(m.attn, m.Qf, m.attn_h, T, m.cs);