From 8401c21f9dd377bcaf14619991b5b41a17e49ecb Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 30 Oct 2026 13:22:33 +0100 Subject: [PATCH] [SYCL] prompt attention on the int8 DPAS (ESIMD, Battlemage): hi/lo int8 Q and P, 2D block loads for the four-cell selection blocks; default on for Battlemage, STRATA_PROMPT_ATTN_ESIMD=0 off --- sycl/CMakeLists.txt | 1 + .../strata/kernels/qsa_prompt_attn_esimd.hpp | 12 + sycl/src/kernels/cuda/qsa_prompt_attn.dp.cpp | 2 + .../kernels/cuda/qsa_prompt_attn_esimd.dp.cpp | 444 ++++++++++++++++++ sycl/src/kernels/qsa_prompt_attn_parity.cpp | 27 ++ tools/arc/kl.py | 25 + 6 files changed, 511 insertions(+) create mode 100644 sycl/include/strata/kernels/qsa_prompt_attn_esimd.hpp create mode 100644 sycl/src/kernels/cuda/qsa_prompt_attn_esimd.dp.cpp create mode 100644 tools/arc/kl.py diff --git a/sycl/CMakeLists.txt b/sycl/CMakeLists.txt index dac10518..895b9ac2 100644 --- a/sycl/CMakeLists.txt +++ b/sycl/CMakeLists.txt @@ -245,6 +245,7 @@ foreach(k IN LISTS _kernel_cu) endforeach() strata_resolve(_kernels ${_kernel_files} src/kernels/ngram.cpp src/ngram/ple_reader.cpp src/platform/direct_file.cpp) list(APPEND _kernels ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/cuda/qsa_prompt_attn_xmx.dp.cpp) # port-only: the XMX prompt attention +list(APPEND _kernels ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/cuda/qsa_prompt_attn_esimd.dp.cpp) # port-only: the int8 DPAS (ESIMD) prompt attention add_library(strata_kernels STATIC ${_kernels}) target_include_directories(strata_kernels PRIVATE ${STRATA_ROOT}/third_party/ggml) target_link_libraries(strata_kernels PUBLIC strata_core) diff --git a/sycl/include/strata/kernels/qsa_prompt_attn_esimd.hpp b/sycl/include/strata/kernels/qsa_prompt_attn_esimd.hpp new file mode 100644 index 00000000..d29f8807 --- /dev/null +++ b/sycl/include/strata/kernels/qsa_prompt_attn_esimd.hpp @@ -0,0 +1,12 @@ +// SYCL port (ARC-W): the QSA prompt attention on the int8 DPAS (ESIMD, Battlemage) - see qsa_prompt_attn_esimd.dp.cpp. +#pragma once +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/qsa_decode_attn.hpp" +#include +namespace strata::kernels { +/// The contract of qsa_prompt_attn_batch (q [n_q, n_head, 256], ids [n_q, cap], steps, attn [n_q, n_head, 256]) for int8 KV. +/// Returns false (nothing launched) when the device, shape or pools are not handled, so the caller keeps its fallback. +/// On by default on Battlemage; STRATA_PROMPT_ATTN_ESIMD=0 turns it off. +bool qsa_prompt_attn_esimd(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::kernels diff --git a/sycl/src/kernels/cuda/qsa_prompt_attn.dp.cpp b/sycl/src/kernels/cuda/qsa_prompt_attn.dp.cpp index 3fa30702..310ae175 100644 --- a/sycl/src/kernels/cuda/qsa_prompt_attn.dp.cpp +++ b/sycl/src/kernels/cuda/qsa_prompt_attn.dp.cpp @@ -10,6 +10,7 @@ #include #include "strata/kernels/qsa_prompt_attn.hpp" #include "strata/kernels/qsa_prompt_attn_xmx.hpp" +#include "strata/kernels/qsa_prompt_attn_esimd.hpp" #include "strata/kernels/gfx_arch.hpp" #include "strata/kernels/kv_q8.hpp" #include "strata/kernels/kv_q4.hpp" @@ -2009,6 +2010,7 @@ bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int3 (void) cc[dev]; // SYCL: the mma.sync kernel below is not ported (upstream's Turing/sm_80 split - `turing` - does not // apply); its XMX port takes the same arguments + if (qsa_prompt_attn_esimd(q, pools, ids, steps, cap, s, attn, n_q, stream)) return true; if (qsa_prompt_attn_xmx(q, pools, ids, steps, cap, s, attn, n_q, stream)) return true; return false; // the caller takes the older kernel } diff --git a/sycl/src/kernels/cuda/qsa_prompt_attn_esimd.dp.cpp b/sycl/src/kernels/cuda/qsa_prompt_attn_esimd.dp.cpp new file mode 100644 index 00000000..9a8b9000 --- /dev/null +++ b/sycl/src/kernels/cuda/qsa_prompt_attn_esimd.dp.cpp @@ -0,0 +1,444 @@ +// SYCL port (ARC-W): the QSA prompt attention on the int8 DPAS (ESIMD, Battlemage). +// +// The FP32 prompt kernel (qsa_decode_attn_batch, 64-cell chunks + a merge kernel) is compute bound at ~60% of the +// card's FP32 peak and takes 22-24% of a prompt. This kernel runs both products on the s8 8x16x32 DPAS. +// +// * One work-group of NTH = 4 hardware threads per (query, KV head). Thread t owns the output dims [64 t, 64 t + 64), +// which is also V's scale group t, and computes Q.K for 32 of every 128 selected cells (a "super-step"). +// * Q.K: A = 8 cells x 32 dims of K's int8 codes (a row of K is contiguous, so A is eight 32-byte slices), B = the +// 32 dims x 16 heads of Q (12 real heads, 4 zero lanes), D = 8 cells x 16 heads. Q is quantized per head to +// hi + lo int8 (x ~ sq (hi + lo / 254), error ~ 1.5e-5 of the head's largest value) so the product keeps ~15 bits; +// K's per-64-dim scale is applied per cell row to each 64-dim group's int32 sum. The scores of the thread's 32 +// cells go to local memory; one barrier later every thread has all 128. +// * Softmax: every thread reads the 128 score rows (lane = head), takes the running max, rescales its output +// accumulators and forms p = exp2(s - m). +// * P.V: A = P (8 heads x 32 cells, int8 hi + lo of p * v_scale[cell][group t], scaled to 127 by the super-step's +// largest v scale), B = the thread's 64 dims of 32 V rows packed four cells to a dword (a 4x4 byte transpose in +// registers), D = 8 heads x 16 dims into float accumulators held in registers (12 heads in two 8-row tiles x 4 +// dim tiles). +// * Not bitwise the FP32 kernel: Q and P are 16-bit (hi + lo int8) numbers, the sums are exact int32, the scales and +// the softmax are FP32. qsa_prompt_attn_parity bounds the difference against FP64. +// int8 KV only (the default); anything else keeps the caller's fallback. +#include "strata/kernels/qsa_prompt_attn_esimd.hpp" +#include "strata/kprof.hpp" +#include "strata/core/geometry.hpp" +#include "strata/sycl_queue.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef STRATA_I8_NO_ESIMD +namespace strata::kernels { +namespace { +using namespace sycl::ext::intel::esimd; +namespace xmx = sycl::ext::intel::esimd::xmx; + +constexpr int HD = 256, G = 12, NTH = 4, SS = 128; +static_assert(HD == strata::core::kCompiledGeometry.head_dim && G == strata::core::kCompiledGeometry.n_head / strata::core::kCompiledGeometry.n_head_kv, + "qsa_prompt_attn_esimd is compiled for core/geometry.hpp"); +constexpr uint32_t QT_OFF = 0; // Q^T B tiles: [8 K steps][LV levels][128 dwords] + +SYCL_ESIMD_FUNCTION inline simd dpas8(simd acc, simd b, simd a) { + return xmx::dpas<8, 8, int, int, int, int, xmx::dpas_argument_type::s8, xmx::dpas_argument_type::s8>(acc, b, a); +} + +// row index of 32 selected cells (selection positions c_first ...), as the page table maps them; positions past n take `fallback` +SYCL_ESIMD_FUNCTION inline simd cell_rows(const int32_t* idsb, const int32_t* pt, int c_first, int n, int kvh, int nkv, + int pshift, int pmask, int fallback) { + simd lane(0, 1); + simd pos = simd(c_first) + simd(lane); + simd_mask<32> ok = pos < n; + simd cell = gather(idsb, lane * 4u, ok, simd(0)); + simd poff = simd(cell >> pshift) * 4u; + simd page = gather(pt, poff, ok, simd(0)); + simd rows = ((page * nkv + kvh) << pshift) + (cell & pmask); + rows.merge(simd(fallback), !ok); + return rows; +} + +template +SYCL_ESIMD_FUNCTION constexpr float level_coef(int l) { return LV == 2 ? (l == 0 ? 254.0f : 1.0f) : (l == 0 ? 64516.0f : (l == 1 ? 254.0f : 1.0f)); } + +// x in [-127, 127] as LV int8 levels: x ~ o[0] + o[1] / 254 + o[2] / 254^2 +template +SYCL_ESIMD_FUNCTION inline void split_lv(simd x, simd* o) { + simd r = x; +#pragma unroll + for (int l = 0; l < LV; ++l) { + simd f = rnde(r); // |r| <= 127 at every level, so the rounded value fits an int8 + o[l] = f; + r = (r - f) * 254.0f; + } +} + +constexpr unsigned SURF_H = (1u << 24) - 1u; // 2D block loads: the surface height - 1 (no clamping) + +// four consecutive pool rows starting at element i of a row-index vector +template +SYCL_ESIMD_FUNCTION inline bool contig4(const simd& r, int i) { + const int r0 = r[i]; + return r[i + 1] == r0 + 1 && r[i + 2] == r0 + 2 && r[i + 3] == r0 + 3; +} + +struct Args { + const float* q; + const int8_t* kq; + const uint16_t* ks; + const int8_t* vq; + const uint16_t* vs; + const int32_t* pt; + const int32_t* ids; + const int32_t* steps; + float* attn; + int nkv, cap, pshift, pmask; + float scale_log2; + int dbg; +}; + +// ---- Q.K for one tile of 8 cells: S[cell][head] -> local memory (rows = cells, lanes = heads) +// FAST: the 8 cells are two runs of four consecutive pool rows (the indexer selects blocks of four cells): 2D block loads +template +SYCL_ESIMD_FUNCTION inline void qk_tile(const Args& a, const simd& rows, int pos0, int n, const simd& cscale, + uint32_t s_dst) { + simd sacc = 0.0f; + simd kall; + simd dA[4], dB[4]; + if constexpr (FAST) { + const int rA = rows[0], rB = rows[4]; +#pragma unroll + for (int pp = 0; pp < 4; ++pp) { + dA[pp] = sycl::ext::intel::experimental::esimd::lsc_load_2d( + reinterpret_cast(a.kq), 255u, SURF_H, 255u, 64 * pp, rA); + dB[pp] = sycl::ext::intel::experimental::esimd::lsc_load_2d( + reinterpret_cast(a.kq), 255u, SURF_H, 255u, 64 * pp, rB); + } + } else { +#pragma unroll + for (int j = 0; j < 8; ++j) { + const size_t r = (size_t) rows[j]; + kall.template select<64, 1>(64 * j) = block_load(reinterpret_cast(a.kq) + r * 64); + } + } + // K scales: 8 rows x 4 halves as 16 dwords + simd so; +#pragma unroll + for (int j = 0; j < 8; ++j) { so[2 * j] = (uint32_t) rows[j] * 8u; so[2 * j + 1] = (uint32_t) rows[j] * 8u + 4u; } + simd sd = gather(reinterpret_cast(a.ks), so); + simd ksh = sd.template bit_cast_view(); + simd ksf = ksh; +#pragma unroll + for (int g = 0; g < 4; ++g) { + simd acc[QL]; +#pragma unroll + for (int l = 0; l < QL; ++l) acc[l] = 0; +#pragma unroll + for (int ss = 0; ss < 2; ++ss) { + const int s = 2 * g + ss; + simd A; + if constexpr (FAST) { + simd da = dA[s >> 1].template bit_cast_view(), db = dB[s >> 1].template bit_cast_view(); + A.template select<32, 1>(0) = da.template select<32, 1>((s & 1) * 32); + A.template select<32, 1>(32) = db.template select<32, 1>((s & 1) * 32); + } else { +#pragma unroll + for (int j = 0; j < 8; ++j) A.template select<8, 1>(8 * j) = kall.template select<8, 1>(64 * j + 8 * s); + } +#pragma unroll + for (int l = 0; l < QL; ++l) { + simd bq = slm_block_load(QT_OFF + (uint32_t) (s * QL + l) * 512u); + acc[l] = dpas8(acc[l], bq, A); + } + } + simd tf; + if constexpr (QL == 2) { + simd ti = acc[0] * 254 + acc[1]; + tf = ti; + } else { + tf = 0.0f; +#pragma unroll + for (int l = 0; l < QL; ++l) { + simd fl = acc[l]; + tf += fl * level_coef(l); + } + } +#pragma unroll + for (int j = 0; j < 8; ++j) { + const float ksc = ksf[4 * j + g]; + sacc.template select<16, 1>(16 * j) += tf.template select<16, 1>(16 * j) * ksc; + } + } +#pragma unroll + for (int j = 0; j < 8; ++j) { + simd row = sacc.template select<16, 1>(16 * j) * cscale; + const float madd = (pos0 + j >= n) ? -INFINITY : 0.0f; + row += madd; + sacc.template select<16, 1>(16 * j) = row; + } + slm_block_store(s_dst, sacc); +} + +// ---- P.V for one step of 32 cells: O += P' V (this thread's 64 dims); lsum += sum p +template +SYCL_ESIMD_FUNCTION inline void pv_step(const Args& a, simd& O, simd& lsum, const simd& m_new, + uint32_t s_row0, const simd& vsf, const simd& rowsV, int t) { + constexpr float COEF0P = PL == 2 ? 254.0f : 64516.0f; + simd ap[PL][2]; // [level][heads 0-7, 8-15]: 8 rows x 32 cells + simd prow[32]; + simd pm = 0.0f; // per head: the largest p * v_scale of these 32 cells +#pragma unroll + for (int c = 0; c < 32; ++c) { + simd srow = slm_block_load(s_row0 + (uint32_t) c * 64u); + simd p = exp2(srow - m_new); + lsum += p; + const float vsc = vsf[c]; + prow[c] = p * vsc; + pm = max(pm, prow[c]); + } + simd pinv = 127.0f / pm; + pinv.merge(simd(0.0f), pm <= 0.0f); + const simd osv = pm * (1.0f / (127.0f * COEF0P)); +#pragma unroll + for (int c = 0; c < 32; ++c) { + simd r = prow[c] * pinv; + simd pb[PL]; + split_lv<16, PL>(r, pb); +#pragma unroll + for (int l = 0; l < PL; ++l) { + ap[l][0].template select<8, 32>(c) = pb[l].template select<8, 1>(0); + ap[l][1].template select<8, 32>(c) = pb[l].template select<8, 1>(8); + } + } + // V: 32 rows x this thread's 64 dims, four cells to a dword + simd vt; // [k4][64 dims] +#pragma unroll + for (int k4 = 0; k4 < 8; ++k4) { + simd w; + if constexpr (FAST) { + simd v2 = sycl::ext::intel::experimental::esimd::lsc_load_2d( + reinterpret_cast(a.vq), 255u, SURF_H, 255u, 64 * t, (int) rowsV[4 * k4]); + w = v2.template bit_cast_view(); + } else { + auto wb = w.template bit_cast_view(); +#pragma unroll + for (int j = 0; j < 4; ++j) { + const size_t r = (size_t) rowsV[4 * k4 + j]; + wb.template select<64, 4>(j) = block_load(reinterpret_cast(a.vq) + r * HD + 64 * t); + } + } + vt.template select<64, 1>(64 * k4) = w; + } + simd aq[PL][2]; +#pragma unroll + for (int l = 0; l < PL; ++l) { + aq[l][0] = ap[l][0].template bit_cast_view(); + aq[l][1] = ap[l][1].template bit_cast_view(); + } +#pragma unroll + for (int nt = 0; nt < 4; ++nt) { + simd B; +#pragma unroll + for (int k4 = 0; k4 < 8; ++k4) B.template select<16, 1>(16 * k4) = vt.template select<16, 1>(64 * k4 + 16 * nt); + simd z = 0; + simd f0 = 0.0f, f1 = 0.0f; +#pragma unroll + for (int l = 0; l < PL; ++l) { + simd d0 = dpas8(z, B, aq[l][0]), d1 = dpas8(z, B, aq[l][1]); + simd e0 = d0, e1 = d1; + f0 += e0 * level_coef(l); + f1 += e1 * level_coef(l); + } +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float s0 = osv[i], s1 = osv[8 + i]; + O.template select<16, 1>((0 * 4 + nt) * 128 + 16 * i) += f0.template select<16, 1>(16 * i) * s0; + O.template select<16, 1>((1 * 4 + nt) * 128 + 16 * i) += f1.template select<16, 1>(16 * i) * s1; + } + } +} + +template struct TagEsimdAttn; + +template +void launch(sycl::queue& q, const Args a, int64_t n_q) { + constexpr uint32_t S_OFF = 8u * QL * 512u; // the scores of one super-step: [128 cells][16 heads] floats + constexpr uint32_t SLM_BYTES = S_OFF + 8192u; + constexpr float COEF0Q = QL == 2 ? 254.0f : 64516.0f; + auto props = sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size<256>}; + strata::kprof::kp(&q, __FILE__, __func__, __LINE__)->submit([&](sycl::handler& h) { + h.parallel_for>(sycl::nd_range<3>(sycl::range<3>((size_t) n_q, (size_t) a.nkv, (size_t) NTH), sycl::range<3>(1, 1, NTH)), props, + [=](sycl::nd_item<3> ndi) SYCL_ESIMD_KERNEL { + slm_init(); + const int qi = (int) ndi.get_group(0), kvh = (int) ndi.get_group(1), t = (int) ndi.get_local_id(2); + const int n_head = a.nkv * G; + const int n = a.steps[(size_t) qi * kStepCount + kStepWidth]; + const int32_t* idsb = a.ids + (size_t) qi * a.cap; + float* outp = a.attn + ((size_t) qi * n_head + (size_t) kvh * G) * HD + 64 * t; + const float* qp = a.q + ((size_t) qi * n_head + (size_t) kvh * G) * HD; + + // ---- Q: per-head int8 levels, the B tiles of this thread's two K steps (2t, 2t + 1) + const simd lane16(0, 1); + simd sqv = 0.0f; // lane h: the head's scale (largest |q| / 127) + { + simd bq[QL][2]; // [level][step 2t, 2t + 1] +#pragma unroll + for (int l = 0; l < QL; ++l) { bq[l][0] = 0; bq[l][1] = 0; } +#pragma unroll + for (int hh = 0; hh < G; ++hh) { + const float* row = qp + (size_t) hh * HD; + simd r0 = block_load(row), r1 = block_load(row + 64); + simd r2 = block_load(row + 128), r3 = block_load(row + 192); + simd mx = max(max(abs(r0), abs(r1)), max(abs(r2), abs(r3))); + const float amax = hmax(mx); + const float inv = amax > 0.0f ? 127.0f / amax : 0.0f; + sqv.merge(simd(amax * (1.0f / 127.0f)), lane16 == (uint32_t) hh); + simd mine = block_load(row + 64 * t); + simd qb[QL]; + split_lv<64, QL>(mine * inv, qb); +#pragma unroll + for (int l = 0; l < QL; ++l) { + simd qd = qb[l].template bit_cast_view(); + bq[l][0].template select<8, 16>(hh) = qd.template select<8, 1>(0); + bq[l][1].template select<8, 16>(hh) = qd.template select<8, 1>(8); + } + } + const uint32_t s0 = QT_OFF + (uint32_t) (2 * t) * (uint32_t) QL * 512u; +#pragma unroll + for (int l = 0; l < QL; ++l) { + slm_block_store(s0 + (uint32_t) l * 512u, bq[l][0]); + slm_block_store(s0 + (uint32_t) (QL + l) * 512u, bq[l][1]); + } + } + barrier(); + // S[cell][head] = sum_g ks[cell][g] * (sum of the levels) * sq[head] * scale_log2 + const simd cscale = sqv * (a.scale_log2 / COEF0Q); + + // the selection's first cell stands in for positions past n (finite scales, weight 0) + int fallback = 0; + if (n > 0) { + const int c = idsb[0]; + fallback = ((a.pt[c >> a.pshift] * a.nkv + kvh) << a.pshift) + (c & a.pmask); + } + + simd O = 0.0f; // [rt][nt] tiles of (8 heads x 16 dims) + simd m = -INFINITY, l = 0.0f; + + for (int c0 = 0; c0 < n; c0 += SS) { + // ---- Q.K for this thread's 32 cells + simd rowsK = cell_rows(idsb + c0 + 32 * t, a.pt, c0 + 32 * t, n, kvh, a.nkv, a.pshift, a.pmask, fallback); +#pragma unroll + for (int tl = 0; tl < 4; ++tl) { + simd r8 = rowsK.template select<8, 1>(8 * tl); + const bool fast = !(a.dbg & 16) && contig4(rowsK, 8 * tl) && contig4(rowsK, 8 * tl + 4); + const uint32_t dst = S_OFF + (uint32_t) (32 * t + 8 * tl) * 64u; + if (a.dbg & 2) continue; + if (fast) qk_tile(a, r8, c0 + 32 * t + 8 * tl, n, cscale, dst); + else qk_tile(a, r8, c0 + 32 * t + 8 * tl, n, cscale, dst); + } + barrier(); + // ---- softmax over the 128 cells + simd mx = -INFINITY; +#pragma unroll 1 + for (int b = 0; b < 16; ++b) { + simd blk = slm_block_load(S_OFF + (uint32_t) b * 512u); +#pragma unroll + for (int r = 0; r < 8; ++r) mx = max(mx, simd(blk.template select<16, 1>(16 * r))); + } + const simd m_new = max(m, mx); + const simd alpha = exp2(m - m_new); +#pragma unroll + for (int hh = 0; hh < 16; ++hh) { + const float av = alpha[hh]; +#pragma unroll + for (int nt = 0; nt < 4; ++nt) { + auto tile = O.template select<16, 1>(((hh >> 3) * 4 + nt) * 128 + (hh & 7) * 16); + tile *= av; + } + } + l *= alpha; + simd lsum = 0.0f; +#pragma unroll + for (int st = 0; st < 4; ++st) { + // V rows of the step's 32 cells, and their scales for this thread's group + const simd rowsV = cell_rows(idsb + c0 + 32 * st, a.pt, c0 + 32 * st, n, kvh, a.nkv, a.pshift, a.pmask, fallback); + simd vo = simd(rowsV) * 8u + (uint32_t) ((t >> 1) * 4); + simd vd = gather(reinterpret_cast(a.vs), vo); + simd shv = (uint32_t) ((t & 1) * 16); + simd v16 = ((vd >> shv) & 0xffffu); + simd vh = v16.template bit_cast_view(); + simd vf = vh; + simd lane(0, 1); + simd_mask<32> ok = (simd(c0 + 32 * st) + simd(lane)) < n; + vf.merge(simd(0.0f), !ok); + bool fastv = !(a.dbg & 16); +#pragma unroll + for (int g4 = 0; g4 < 8; ++g4) fastv = fastv && contig4(rowsV, 4 * g4); + if (fastv) pv_step(a, O, lsum, m_new, S_OFF + (uint32_t) (32 * st) * 64u, vf, rowsV, t); + else pv_step(a, O, lsum, m_new, S_OFF + (uint32_t) (32 * st) * 64u, vf, rowsV, t); + } + l += lsum; + m = m_new; + barrier(); + } + // ---- out = O / l +#pragma unroll + for (int hh = 0; hh < G; ++hh) { + const float lv = l[hh]; + const float il = lv > 0.0f ? 1.0f / lv : 0.0f; +#pragma unroll + for (int nt = 0; nt < 4; ++nt) { + simd v = O.template select<16, 1>(((hh >> 3) * 4 + nt) * 128 + (hh & 7) * 16) * il; + block_store(outp + (size_t) hh * HD + 16 * nt, v); + } + } + }); + }); +} +} // namespace + +bool qsa_prompt_attn_esimd(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) { + static const int mode = [] { const char* v = std::getenv("STRATA_PROMPT_ATTN_ESIMD"); return v ? std::atoi(v) : 1; }(); // default on (Battlemage); =0 off + if (mode == 0 || n_q <= 0) return false; + if (pools.k_q == nullptr || pools.v_q == nullptr || pools.k_scale == nullptr || pools.v_scale == nullptr || pools.k_q4 != nullptr || + pools.v_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; + const int64_t ps = s.page_size; + if (ps <= 0 || (ps & (ps - 1)) != 0) return false; + dpct::queue_ptr st = strata::q_of(stream); + if (strata::intel_gpu_gen(st->get_device()) != strata::IntelGpuGen::Battlemage) return false; + static bool told = false; + if (!told) { told = true; std::fprintf(stderr, "strata: prompt attention on the int8 DPAS (ESIMD)\n"); } + static const int lv = [] { const char* v = std::getenv("STRATA_ESIMD_LV"); return v ? std::atoi(v) : 2; }(); + int sh = 0; + while ((1 << sh) < ps) ++sh; + Args a{q, pools.k_q, pools.k_scale, pools.v_q, pools.v_scale, pools.page_table, ids, steps, attn, + (int) s.n_head_kv, (int) cap, sh, (int) (ps - 1), 1.4426950408889634f / std::sqrt((float) HD), + std::getenv("STRATA_ESIMD_DBG") != nullptr ? std::atoi(std::getenv("STRATA_ESIMD_DBG")) : 0}; + for (int64_t q0 = 0; q0 < n_q; q0 += 65535) { + const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535; + Args b = a; + b.q = q + q0 * s.n_head * HD; + b.ids = ids + q0 * cap; + b.steps = steps + q0 * kStepCount; + b.attn = attn + q0 * s.n_head * HD; + if (lv == 3) launch<3, 3>(*st, b, nb); + else if (lv == 32) launch<3, 2>(*st, b, nb); + else if (lv == 23) launch<2, 3>(*st, b, nb); + else launch<2, 2>(*st, b, nb); + } + return true; +} +} // namespace strata::kernels +#else +namespace strata::kernels { +bool qsa_prompt_attn_esimd(const float*, const QsaAttnPools&, const int32_t*, const int32_t*, int64_t, const QsaShapes&, float*, int64_t, void*) { return false; } +} +#endif diff --git a/sycl/src/kernels/qsa_prompt_attn_parity.cpp b/sycl/src/kernels/qsa_prompt_attn_parity.cpp index b0f44347..17e772e0 100644 --- a/sycl/src/kernels/qsa_prompt_attn_parity.cpp +++ b/sycl/src/kernels/qsa_prompt_attn_parity.cpp @@ -132,6 +132,23 @@ int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16, 2 for (int64_t c = 0; c < w; ++c) sel[c] = (int32_t) c; continue; } + if (std::getenv("QA_BLOCK4")) { // the engine's selections are whole blocks of four cells (idx_block): 128 recent blocks + random older ones, then the tail cells + std::mt19937 r3((unsigned) (i / 4) * 2654435761u + 7); + const int64_t nbk = nkv / 4, take = std::min(nbk, w / 4); + std::vector blocks; + for (int64_t b = std::max(0, nbk - 128); b < nbk; ++b) blocks.push_back((int32_t) b); + std::vector rest; + for (int64_t b = 0; b < std::max(0, nbk - 128); ++b) rest.push_back((int32_t) b); + std::shuffle(rest.begin(), rest.end(), r3); + for (int64_t b = 0; (int64_t) blocks.size() < take && b < (int64_t) rest.size(); ++b) blocks.push_back(rest[b]); + std::sort(blocks.begin(), blocks.end()); + std::vector v; + for (int32_t b : blocks) for (int r = 0; r < 4; ++r) v.push_back(b * 4 + r); + for (int64_t c = nbk * 4; c < nkv; ++c) v.push_back((int32_t) c); + steps[i * k::kStepCount + k::kStepWidth] = (int32_t) v.size(); + std::copy(v.begin(), v.end(), sel); + 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 all((size_t) (nkv - recent)); @@ -298,6 +315,16 @@ int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16, 2 } const double r = a / l; const size_t at = (size_t) ((i * NH + h) * HD + d); + if (std::getenv("PARITY_DUMP2") && fmt == 1 && i == 0 && h == 0 && d == 0) { + for (int c = 0; c < 4; ++c) for (int n = 0; n < 6; ++n) { + const int64_t cell = sel[c], row = ((int64_t) table[cell / PS] * NKV + 0) * PS + cell % PS; + double a2 = 0; + for (int64_t dd = 0; dd < HD; ++dd) a2 += (double) q[(i * NH + n) * HD + dd] * ((double) kq[row * HD + dd] * h2f(ks[row * 4 + dd / 64])); + std::printf("S c%d n%d ref %.5f new %.5f\n", c, n, a2 / 16.0 * 1.4426950408889634, (double) nw[c * 16 + n]); + } + } + if (std::getenv("PARITY_DUMP") && i == 0 && (d == 3 || d == 70)) + std::printf("dump h%lld d%lld ref %.5f old %.5f new %.5f\n", (long long) h, (long long) d, r, (double) o[at], (double) nw[at]); 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)); diff --git a/tools/arc/kl.py b/tools/arc/kl.py new file mode 100644 index 00000000..a5ab8fdf --- /dev/null +++ b/tools/arc/kl.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python3 +"""kl.py A.bin B.bin ... : KL(A||B), top-1 agreement and max |dlogit| between first-token logit dumps (STRATA_DUMP_FIRST_LOGITS).""" +import sys +import numpy as np + + +def load(p): + return np.fromfile(p, dtype=np.float32).astype(np.float64) + + +def lsm(x): + m = x.max() + return x - m - np.log(np.exp(x - m).sum()) + + +a = load(sys.argv[1]) +la = lsm(a) +pa = np.exp(la) +for p in sys.argv[2:]: + b = load(p) + lb = lsm(b) + kl = float((pa * (la - lb)).sum()) + top = np.argsort(-a)[:5] + print(f"{p}: KL(A||B)={kl:.3e} top1 {'same' if a.argmax() == b.argmax() else 'DIFF'} max|dlogit|={np.abs(a - b).max():.4f} " + f"max|dlogit| top5={np.abs(a[top] - b[top]).max():.4f} A top1 p={pa.max():.3f}")