From ffac97f74ff4b7433d7c72737164f3541c2fd2ff Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 6 Oct 2026 15:37:44 +0200 Subject: [PATCH] Verify window: 2-4 token dense projections read an interleaved copy of the q8_1 activations (fork F4) A one-int-a-column interleaved copy of the window's q8_1 blocks lets a warp decode each weight block once and apply it to every token with the single-column dot's own expression (the same *_q8_dot_impl calls), walking the chunks of the exact multi-column layout and adding the four virtual warps' sums in warp order, so every output is bitwise the multi-column kernel's. IQ4_XS, Q4_K, Q5_K and Q6_K projections (and the head) of 2-4 tokens use it; the copy is made from xq_ by one small kernel, so the fused HC-read producer works too. STRATA_MMVQ_IL=0 keeps native_mmvq's kernels. CUDA only (HIP keeps its kernels). mmvq_il_parity checks every case bitwise for rows 1/2/4 and the table; --bench times it. Ported by hand from Eddoursul's fork (738e166, b67a291), with the IQ3_S and Q8_0 parts and the 5-8 column widths left out. Co-authored-by: Eddoursul --- CMakeLists.txt | 7 + include/strata/core/verify.hpp | 1 + include/strata/kernels/native_mmvq.hpp | 17 ++ src/core/verify.cpp | 38 +++- src/kernels/cuda/native_mmvq.cu | 300 +++++++++++++++++++++++++ src/kernels/cuda/q8_1_il.cuh | 99 ++++++++ src/kernels/mmvq_il_parity.cpp | 178 +++++++++++++++ 7 files changed, 632 insertions(+), 8 deletions(-) create mode 100644 src/kernels/cuda/q8_1_il.cuh create mode 100644 src/kernels/mmvq_il_parity.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 9e9002a3..90c78a03 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -721,6 +721,13 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) set_tests_properties(mmvq_multi_parity_cuda_layout PROPERTIES ENVIRONMENT "STRATA_MMVQ_WAVE=0") endif() endif() + if(STRATA_ENABLE_CUDA) + # fork F4: the 2-4 column dense projections from the interleaved q8_1 copy, bitwise vs native_mmvq (GPU, synthetic) + add_executable(mmvq_il_parity src/kernels/mmvq_il_parity.cpp) + target_include_directories(mmvq_il_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(mmvq_il_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME mmvq_il_parity COMMAND mmvq_il_parity) + endif() # the IQ kernels that decode a weight part once for every column/entry, bitwise vs the per-column ones # (GPU, synthetic, no model; --bench adds old/new timings) add_executable(iq_multi_parity src/kernels/iq_multi_parity.cpp) diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index acbe4c2e..2f5d606d 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -422,6 +422,7 @@ private: float *ple_ = nullptr, *emb_ = nullptr, *R_ = nullptr, *mixed_ = nullptr, *bo_ = nullptr; float *inj_ = nullptr, *inj2_ = nullptr, *lo_ = nullptr, *rs_ = nullptr, *xn_ = nullptr; uint8_t* xq_ = nullptr; // T columns of q8_1 + uint8_t* xil_ = nullptr; // fork F4: the interleaved copy of xq_'s 2-4 columns uint8_t* sh_xq_ = nullptr; // T columns of q8_1 for shared expert branch float *qkv_L_ = nullptr, *h_L_ = nullptr, *gate_L_ = nullptr, *beta_L_ = nullptr; // per GDN layer float *z_ = nullptr, *y_ = nullptr, *y_dummy_ = nullptr; diff --git a/include/strata/kernels/native_mmvq.hpp b/include/strata/kernels/native_mmvq.hpp index ae39fe1c..799ef7db 100644 --- a/include/strata/kernels/native_mmvq.hpp +++ b/include/strata/kernels/native_mmvq.hpp @@ -134,4 +134,21 @@ void native_mmvq(int ggml_type, const void* weights, const void* x_q8_1, float* bool native_mmvq_pair(int ggml_type, const void* w1, const void* w2, const void* x_q8_1, float* y1, float* y2, int n_in, int n_out, int ncols, void* stream); +// Fork F4 (Eddoursul): 2..4 columns also INTERLEAVED, so one 16-byte load reads a position of every column: CP = 2 (2 +// columns) or 4 (3-4), zero-padded; nb = n_in / 32 blocks; int32 bm[nb][8][CP] (block-major), int32 pm[8][nb][CP] +// (position-major), float d[nb][CP] (each block's scale as the dots read it, __low2float of ds). +constexpr int native_q8_1_il_cp(int ncols) { return ncols <= 2 ? 2 : ncols <= 4 ? 4 : 8; } +std::size_t native_q8_1_il_bytes(int n_in, int ncols); +// Writes the interleaved copy of 2..4 columns of plain q8_1 blocks (native_quantize_q8_1's, or a fused producer's) +// to x_il (native_q8_1_il_bytes): the same values in the same bytes. +void native_q8_1_interleave(const void* x_q8_1, void* x_il, int n_in, int ncols, void* stream); +// True when native_mmvq_il runs its own kernel for this call (IQ4_XS, Q4_K, Q5_K, Q6_K, 2-4 columns, the exact layout). +bool native_mmvq_il_supported(int ggml_type, int ncols, int n_out); +// native_mmvq for 2..4 columns whose copy native_q8_1_interleave wrote, bitwise native_mmvq's output: kernels in which a +// warp takes 1, 2 or 4 rows and reads the columns from the interleaved copy; native_mmvq (x_q8_1) when not supported. +void native_mmvq_il(int ggml_type, const void* weights, const void* x_q8_1, const void* x_il, float* y, int n_in, + int n_out, int ncols, void* stream); +// Tests and benchmarks: every native_mmvq_il call takes `rows` a warp (0: the table). +void native_mmvq_il_tune(int rows); + } // namespace strata::kernels diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 8a4309e4..78cc8709 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -64,6 +64,9 @@ inline bool g_lfuse_gate() { static const bool on = [] { const char* v = std::ge inline bool g_lfuse_pair() { static const bool on = [] { const char* v = std::getenv("STRATA_LFUSE_PAIR"); return v == nullptr || v[0] != '0'; }(); return on; } inline bool g_qdedup() { static const bool on = [] { const char* v = std::getenv("STRATA_VERIFY_QDEDUP"); return v != nullptr && std::atoi(v) != 0; }(); return on; } // S26 STRATA_QFUSE=1: activation q8_1 images written by their producers (the GDN output norm) - the same bytes +// fork F4 (Eddoursul): 2-4 token dense projections read an interleaved copy of the q8_1 activations (bitwise the same +// outputs); STRATA_MMVQ_IL=0 keeps native_mmvq's multi-column kernels +inline bool g_mmvq_il() { static const bool on = [] { const char* v = std::getenv("STRATA_MMVQ_IL"); return v == nullptr || v[0] != '0'; }(); return on; } inline bool g_qfuse() { static const bool on = [] { const char* v = std::getenv("STRATA_QFUSE"); return v != nullptr && std::atoi(v) != 0; }(); return on; } #define VDBG(...) do { if (g_dbg) { std::fprintf(stderr, "verify dbg: " __VA_ARGS__); std::fflush(stderr); } } while (0) @@ -476,6 +479,7 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& lo_ = b.take(T * (uint64_t) g.hc_lr); rs_ = b.take(T * HC); xn_ = b.take(T * HC * N); xq_ = b.take(strata::kernels::native_q8_1_bytes(max_in, (int) T)); sh_xq_ = b.take(strata::kernels::native_q8_1_bytes(max_in, (int) T)); + xil_ = b.take(strata::kernels::native_q8_1_il_bytes(max_in, 4)); qkv_L_ = b.take(nG * T * C); h_L_ = b.take(nG * T * C); gate_L_ = b.take(nG * T * HV); beta_L_ = b.take(nG * T * HV); z_ = b.take(T * ZV); y_ = b.take(T * ZV); y_dummy_ = b.take(T * ZV); @@ -825,6 +829,18 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { const bool q8_attn = gr_read_group(0, pending, inj2_, inj_); // true: xq_ holds mixed's q8_1 (STRATA_QFUSE) stamp(l, 1, grp); float* xm = mixed_ + tb * N; + bool il_ready = false; // xil_ holds xq_'s interleaved copy (reset whenever xq_ is rewritten) + auto mm = [&](const WeightRef* w, float* out, int n_in, int n_out) { + if (g_mmvq_il() && strata::kernels::native_mmvq_il_supported(w->native_type, n, n_out)) { + if (!il_ready) { + strata::kernels::native_q8_1_interleave(xq_, xil_, n_in, n, cs); + il_ready = true; + } + strata::kernels::native_mmvq_il(w->native_type, w->native_data, xq_, xil_, out, n_in, n_out, n, cs); + } else { + native_mmvq(w->native_type, w->native_data, xq_, out, n_in, n_out, n, cs); + } + }; try { if (!is_qsa_layer(g, l)) { // ======================= GDN ======================= @@ -845,7 +861,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { float* gate = gate_L_ + (size_t) gi * MT * HV; float* beta = beta_L_ + (size_t) gi * MT * HV; if (!q8_attn) native_quantize_q8_1(xm, xq_, (int) N, n, cs); - native_mmvq(wqkv->native_type, wqkv->native_data, xq_, qkv + (size_t) tb * C, (int) N, (int) C, n, cs); + mm(wqkv, qkv + (size_t) tb * C, (int) N, (int) C); stamp(l, 2, grp); if (batch_rec_) { // contiguous rows may be proposals for the same slot for (int t = tb; t < te;) { @@ -866,7 +882,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { (const float*) wsa->data, gate + (size_t) tb * HV, beta + (size_t) tb * HV, (int) N, (int) HV, n, cs); stamp(l, 4, grp); - native_mmvq(wg->native_type, wg->native_data, xq_, z_ + (size_t) tb * ZV, (int) N, (int) ZV, n, cs); + mm(wg, z_ + (size_t) tb * ZV, (int) N, (int) ZV); stamp(l, 5, grp); // the recurrence from the untouched state over tokens [0, te); outputs only for this group's if (batch_rec_) { // each slot's recurrence over its own proposed-token group @@ -887,7 +903,8 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { // STRATA_QFUSE: done above by gdn_step_norm_multi - but a batch's per-slot recurrence passes it no q8_1 // destination (#1139: the out-projection read stale bytes), so that case quantizes here as without it if (!g_qfuse() || batch_rec_) native_quantize_q8_1(y_ + (size_t) tb * ZV, xq_, (int) ZV, n, cs); - native_mmvq(wout->native_type, wout->native_data, xq_, bo_ + tb * N, (int) ZV, (int) N, n, cs); + il_ready = false; + mm(wout, bo_ + tb * N, (int) ZV, (int) N); } else { // ======================= QSA ======================= const int64_t qi = qsa_idx[(size_t) l]; @@ -924,8 +941,8 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { else for (int t = tb; t < te; ++t) bf16_gemv_fp32_mmvf(mixed_ + t * N, (const uint16_t*) wik->data, idx_raw + t * ID, (int) N, (int) ID, cs); stamp(l, 7, grp); - native_mmvq(wk->native_type, wk->native_data, xq_, kcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD), n, cs); - native_mmvq(wv->native_type, wv->native_data, xq_, vcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD), n, cs); + mm(wk, kcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD)); + mm(wv, vcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD)); if (qb) norm_rope(kcur_ + tb * NKV * HD, wkn, (int) (n * NKV), (int) HD, pos_k + tb * NKV); else for (int t = tb; t < te; ++t) norm_rope(kcur_ + t * NKV * HD, wkn, (int) NKV, (int) HD, pos_ + t * NH); if (st.kv_rot) { // K and V rotated before they are stored (kv_q4.hpp) @@ -1004,8 +1021,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { } } stamp(l, 9, grp); - native_mmvq(wq->native_type, wq->native_data, xq_, qfull_ + tb * NH * 2 * HD, (int) N, (int) (NH * 2 * HD), - n, cs); + mm(wq, qfull_ + tb * NH * 2 * HD, (int) N, (int) (NH * 2 * HD)); if (qb) { if (fuse_nr) { // the q/gate split reads q straight out of the q|gate rows (stride 2 * HD) native_qsa_rms_norm_rope(qfull_ + tb * NH * 2 * HD, (int) (2 * HD), (const float*) wqn->data, @@ -1086,7 +1102,8 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { } stamp(l, 14, grp); native_quantize_q8_1(attn32_ + tb * NH * HD, xq_, (int) (NH * HD), n, cs); - native_mmvq(wo->native_type, wo->native_data, xq_, bo_ + tb * N, (int) (NH * HD), (int) N, n, cs); + il_ready = false; + mm(wo, bo_ + tb * N, (int) (NH * HD), (int) N); } } catch (const std::exception& e) { err = "verify layer " + std::to_string(l) + ": " + e.what(); @@ -1416,6 +1433,11 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { if (head_ != nullptr && head_->loaded()) { try { native_quantize_q8_1(head_mixed_, xq_, (int) N, T, cs); + if (g_mmvq_il() && strata::kernels::native_mmvq_il_supported(head_->type(), (int) T, (int) n_vocab_)) { + strata::kernels::native_q8_1_interleave(xq_, xil_, (int) N, (int) T, cs); + strata::kernels::native_mmvq_il(head_->type(), head_->weights(), xq_, xil_, head_logits_, (int) N, + (int) n_vocab_, (int) T, cs); + } else native_mmvq(head_->type(), head_->weights(), xq_, head_logits_, (int) N, (int) n_vocab_, T, cs); } catch (const std::exception& e) { err = std::string("verify head: ") + e.what(); diff --git a/src/kernels/cuda/native_mmvq.cu b/src/kernels/cuda/native_mmvq.cu index d099532a..764b6074 100644 --- a/src/kernels/cuda/native_mmvq.cu +++ b/src/kernels/cuda/native_mmvq.cu @@ -28,6 +28,9 @@ #include "strata/kernels/q8_1_finite.hpp" #include "strata/kernels/iq_kernels.hpp" #include "s26_tsum.cuh" +#if !defined(__HIPCC__) +#include "q8_1_il.cuh" +#endif #include #include @@ -1268,6 +1271,203 @@ void launch_multi(const void* weights, const void* x_q8_1, float* y, int n_in, i } } +#if !defined(__HIPCC__) // CUDA only: the HIP paths keep native_mmvq's kernels +// ============================ ncols = 2..4 from interleaved activations (fork F4, Eddoursul) ============================ +// +// `native_quantize_q8_1_il` also writes the columns interleaved (native_mmvq.hpp), so one load reads the same int of +// every column. A warp takes R rows and walks their blocks in the chunks of the exact layout above - its lane l's chunk +// m is what thread 32 (m % 4) + l does in iteration m / 4 - with a sum per virtual warp, added in warp order before the +// xor tree; each weight block is decoded once (the traits' `load`) and every column takes the single-column dot's own +// expression (the same *_q8_dot_impl calls), so each value is bitwise the multi-column kernel's. K-quants read the +// block-major copy; IQ4_XS, whose lanes read the same int of consecutive blocks, the position-major one. +struct IlIQ4XS { + using F = IQ4XSTraits; + static constexpr bool PM = true; + template + __device__ static void apply(const F::W& r, const X& x, int kby, int iqs, float (&out)[NC]) { + const int b = kby + iqs / 4; + int u0[4][NC], u1[4][NC]; +#pragma unroll + for (int j = 0; j < 4; ++j) { + x.u(b, j, u0[j]); + x.u(b, j + 4, u1[j]); + } + float d8[NC]; + x.scales(b, d8); +#pragma unroll + for (int c = 0; c < NC; ++c) { + int sumi = 0; +#pragma unroll + for (int j = 0; j < 4; ++j) { + sumi = STRATA_DP4A(r.v[j].x, u0[j][c], sumi); + sumi = STRATA_DP4A(r.v[j].y, u1[j][c], sumi); + } + sumi *= r.ls - 32; + const float d = r.dw * d8[c]; + out[c] = d * sumi; + } + } +}; +struct IlQ4K { + using F = Q4KTraits; + static constexpr bool PM = false; + template + __device__ static void apply(const F::W& r, const X& x, int kby, int iqs, float (&out)[NC]) { + int u[4][NC]; + float d8[2][NC]; +#pragma unroll + for (int i = 0; i < 2; ++i) { + const int b = kby + r.bq8_offset + i; + x.u(b, (iqs / 2) % 4, u[2 * i]); + x.u(b, (iqs / 2) % 4 + 4, u[2 * i + 1]); + x.scales(b, d8[i]); + } + const uint8_t* sc = reinterpret_cast(r.aux); +#pragma unroll + for (int c = 0; c < NC; ++c) { + const int uc[4] = {u[0][c], u[1][c], u[2][c], u[3][c]}; + const float dc[2] = {d8[0][c], d8[1][c]}; + out[c] = q4_q8_dot_impl(r.v, uc, sc, sc + 2, r.dm, dc); + } + } +}; +struct IlQ5K { + using F = Q5KTraits; + static constexpr bool PM = false; + template + __device__ static void apply(const F::W& r, const X& x, int kby, int iqs, float (&out)[NC]) { + int u[4][NC]; + float d8[2][NC]; +#pragma unroll + for (int i = 0; i < 2; ++i) { + const int b = kby + r.bq8_offset + i; + x.u(b, (iqs / 2) % 4, u[2 * i]); + x.u(b, (iqs / 2) % 4 + 4, u[2 * i + 1]); + x.scales(b, d8[i]); + } + const uint8_t* sc = reinterpret_cast(r.aux); +#pragma unroll + for (int c = 0; c < NC; ++c) { + const int uc[4] = {u[0][c], u[1][c], u[2][c], u[3][c]}; + const float dc[2] = {d8[0][c], d8[1][c]}; + out[c] = q5_q8_dot_impl(r.vl, r.vh, uc, sc, sc + 2, r.dm, dc); + } + } +}; +struct IlQ6K { + using F = Q6KTraits; + static constexpr bool PM = false; + template + __device__ static void apply(const F::W& r, const X& x, int kby, int iqs, float (&out)[NC]) { + int u[2][NC]; + float d8[2][NC]; +#pragma unroll + for (int i = 0; i < 2; ++i) { + x.u(kby + r.bq8_offset + 2 * i, iqs % 8, u[i]); + x.scales(kby + r.bq8_offset + 2 * i, d8[i]); + } +#pragma unroll + for (int c = 0; c < NC; ++c) { + const int uc[2] = {u[0][c], u[1][c]}; + const float dc[2] = {d8[0][c], d8[1][c]}; + out[c] = q6_q8_dot_impl(r.vl, r.vh, uc, r.scales, r.d, dc); + } + } +}; + +template +__launch_bounds__(4 * WARP) +__global__ void native_mmvq_il_kernel(const typename I::F::Block* __restrict__ w, const int* __restrict__ xq, + const float* __restrict__ xd, float* __restrict__ y, int n_in, int n_out) { + using F = typename I::F; + constexpr int SUB = WARP / F::T; // weight blocks a chunk covers + const int lane = int(threadIdx.x) & (WARP - 1); + const auto x = q8_1_cols(xq, xd, n_in / Q8K); + const int bpr = n_in / F::DIV; + const int kqs = F::kqs(lane); + const int nm = (bpr + SUB - 1) / SUB; + // A grid-stride loop over the row groups, though the grid gives each warp one: without it ptxas gives several + // instances fewer registers (the fork measured Q6_K's at 3 columns 10-50% slower). + for (int grp = int(blockIdx.x) * 4 + (int(threadIdx.x) >> 5); grp * R < n_out; grp += int(gridDim.x) * 4) { + const int row0 = grp * R; + float acc[4][R][NC]; +#pragma unroll + for (int v = 0; v < 4; ++v) +#pragma unroll + for (int i = 0; i < R; ++i) +#pragma unroll + for (int c = 0; c < NC; ++c) acc[v][i][c] = 0.0f; + for (int m0 = 0; m0 < nm; m0 += 4) { +#pragma unroll + for (int v = 0; v < 4; ++v) { + const int kbx = SUB * (m0 + v) + lane / F::T; + if (kbx < bpr) { +#pragma unroll + for (int i = 0; i < R; ++i) { + const int row = min(row0 + i, n_out - 1); // a partial last group recomputes its last row + const typename F::W wv = F::load(w + std::size_t(row) * bpr + kbx, kqs); + float o[NC]; + I::template apply(wv, x, kbx * F::KBY, kqs, o); +#pragma unroll + for (int c = 0; c < NC; ++c) acc[v][i][c] += o[c]; + } + } + } + } +#pragma unroll + for (int i = 0; i < R; ++i) +#pragma unroll + for (int c = 0; c < NC; ++c) { + float s = acc[0][i][c]; + s += acc[1][i][c]; + s += acc[2][i][c]; + s += acc[3][i][c]; + s = warp_sum(s); + if (lane == 0 && row0 + i < n_out) y[std::size_t(c) * n_out + row0 + i] = s; + } + } +} + +template +void launch_il(const void* weights, const void* x_il, float* y, int n_in, int n_out, int ncols, cudaStream_t s) { + const auto* w = static_cast(weights); + const unsigned blocks = unsigned(((n_out + R - 1) / R + 3) / 4); + const Q81IlParts parts = q8_1_il_parts(x_il, n_in, ncols); + const int* xq = I::PM ? parts.pm : parts.bm; + const float* xd = parts.d; + switch (ncols) { +#define STRATA_IL_CASE(N) case N: native_mmvq_il_kernel<<>>(w, xq, xd, y, n_in, n_out); break; + STRATA_IL_CASE(2) STRATA_IL_CASE(3) STRATA_IL_CASE(4) +#undef STRATA_IL_CASE + default: throw std::invalid_argument("native_mmvq_il requires 2 <= ncols <= 4"); + } +} + +template +void launch_il_rows(int r, const void* weights, const void* x_il, float* y, int n_in, int n_out, int ncols, cudaStream_t s) { + switch (r) { + case 1: launch_il(weights, x_il, y, n_in, n_out, ncols, s); break; + case 4: launch_il(weights, x_il, y, n_in, n_out, ncols, s); break; + default: launch_il(weights, x_il, y, n_in, n_out, ncols, s); break; + } +} + +// The interleaved copy (native_mmvq.hpp) of columns already quantized into plain q8_1 blocks, whoever wrote them (the +// quantizer, a fused norm): the same bytes, one int of a block a thread. +__global__ void native_q8_1_interleave_kernel(const Q81Block* __restrict__ y, int* __restrict__ bm, int* __restrict__ pm, + float* __restrict__ dl, int nb, int n_total, int cp) { + const int i = int(blockIdx.x) * 256 + int(threadIdx.x); + if (i >= n_total) return; + const int c = i / (nb * 8), r = i - c * nb * 8, b = r / 8, p = r % 8; + const Q81Block& blk = y[std::size_t(c) * nb + b]; + const int q = reinterpret_cast(blk.qs)[p]; + bm[(std::size_t(b) * 8 + p) * cp + c] = q; + pm[(std::size_t(p) * nb + b) * cp + c] = q; + if (p == 0) dl[std::size_t(b) * cp + c] = __low2float(blk.ds); +} + +#endif // !__HIPCC__ + void validate_shape(int n_in, int ncols, int block_elems = Q8K) { if (n_in <= 0 || n_in % block_elems != 0) { throw std::invalid_argument("native MMVQ requires n_in > 0 and divisible by its block element count"); @@ -2236,4 +2436,104 @@ void native_mmvq(int ggml_type, const void* weights, const void* x_q8_1, float* } } +#if !defined(__HIPCC__) +std::size_t native_q8_1_il_bytes(int n_in, int ncols) { + validate_shape(n_in, ncols); + return std::size_t(n_in / Q8K) * std::size_t(native_q8_1_il_cp(ncols)) * (16 * sizeof(int) + sizeof(float)); +} + +void native_q8_1_interleave(const void* x_q8_1, void* x_il, int n_in, int ncols, void* stream) { + validate_shape(n_in, ncols); + if (ncols < 2 || ncols > 4) throw std::invalid_argument("native_q8_1_interleave requires 2 <= ncols <= 4"); + validate_pointer(x_q8_1); + validate_pointer(x_il); + validate_stream(stream); + const int nb = n_in / Q8K, cp = native_q8_1_il_cp(ncols); + const Q81IlParts parts = q8_1_il_parts(x_il, n_in, ncols); + const int n_total = nb * 8 * ncols; + native_q8_1_interleave_kernel<<(stream)>>>( + static_cast(x_q8_1), const_cast(parts.bm), const_cast(parts.pm), + const_cast(parts.d), nb, n_total, cp); + launch_check(); +} + +namespace { +// Rows a warp at 2-4 columns ([ncols - 2]) by the matrix's row count, in classes: below 2048 (the keys' 512), 4096 (the +// output projections' 2560), 8192 (the gate projection's 6144), 12288 (qkv's 10240), and more (the queries' 12288, the +// head's 248K); 0: native_mmvq's kernels. The fork tuned its table on an RTX 3090. This one is read off +// mmvq_il_parity --bench on an RTX 3060 (sm_86) and an RTX 5070 (sm_120) together: per cell the rows count (1/2/4) whose +// worse card still takes at least 3% off native_mmvq's time, else 0; classes without a measured shape take their +// neighbour's value. Every choice is bitwise the same output, so the table is only speed. +struct IlRows { int type; uint8_t r[3][5]; }; +constexpr IlRows kIlRows[] = { + {23, {{0, 0, 0, 0, 0}, {0, 0, 2, 4, 4}, {0, 1, 1, 1, 1}}}, // IQ4_XS + {12, {{0, 0, 1, 1, 1}, {0, 1, 1, 1, 1}, {0, 1, 1, 1, 1}}}, // Q4_K + {13, {{0, 0, 1, 1, 1}, {0, 4, 1, 1, 1}, {0, 1, 1, 1, 2}}}, // Q5_K + {14, {{0, 0, 1, 1, 0}, {0, 0, 1, 1, 2}, {0, 0, 1, 1, 1}}}, // Q6_K +}; +int il_rows(int type, int ncols, int n_out) { + const int cls = n_out < 2048 ? 0 : n_out < 4096 ? 1 : n_out < 8192 ? 2 : n_out < 12288 ? 3 : 4; + for (const IlRows& e : kIlRows) + if (e.type == type) return e.r[ncols - 2][cls]; + return 0; +} +int g_tune_rows = 0; // native_mmvq_il_tune (tests, benchmarks): rows a warp for every shape (0: the table) +} // namespace +void native_mmvq_il_tune(int rows) { g_tune_rows = rows; } + +namespace { +// sm_80 and newer only (measured on sm_86 and sm_120): Pascal/Volta/Turing keep native_mmvq's kernels unchanged +bool il_arch_ok() { + static int ok[16] = {}; // 0 unknown, 1 yes, -1 no, by device ordinal + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 16) return false; + if (ok[dev] == 0) { + int major = 0; + ok[dev] = (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess && major >= 8) ? 1 : -1; + } + return ok[dev] > 0; +} +} // namespace + +bool native_mmvq_il_supported(int ggml_type, int ncols, int n_out) { + if (ncols < 2 || ncols > 4 || !g_multi_exact || !il_arch_ok()) return false; + return (g_tune_rows ? g_tune_rows : il_rows(ggml_type, ncols, n_out)) != 0 && + (ggml_type == 23 || ggml_type == 12 || ggml_type == 13 || ggml_type == 14); +} + +void native_mmvq_il(int ggml_type, const void* weights, const void* x_q8_1, const void* x_il, float* y, int n_in, + int n_out, int ncols, void* stream) { + if (!native_mmvq_il_supported(ggml_type, ncols, n_out)) { + native_mmvq(ggml_type, weights, x_q8_1, y, n_in, n_out, ncols, stream); + return; + } + const int r = g_tune_rows ? g_tune_rows : il_rows(ggml_type, ncols, n_out); + validate_shape(n_in, ncols, QK); + validate_pointer(weights); + validate_pointer(x_il); + validate_pointer(y); + validate_stream(stream); + const auto s = static_cast(stream); + switch (ggml_type) { + case 23: launch_il_rows(r, weights, x_il, y, n_in, n_out, ncols, s); break; + case 12: launch_il_rows(r, weights, x_il, y, n_in, n_out, ncols, s); break; + case 13: launch_il_rows(r, weights, x_il, y, n_in, n_out, ncols, s); break; + case 14: launch_il_rows(r, weights, x_il, y, n_in, n_out, ncols, s); break; + } + launch_check(); +} + +#else // HIP: no interleaved path +std::size_t native_q8_1_il_bytes(int n_in, int ncols) { return native_q8_1_bytes(n_in, ncols) * 2; } +void native_q8_1_interleave(const void*, void*, int, int, void*) { + throw std::invalid_argument("native_q8_1_interleave is CUDA only"); +} +bool native_mmvq_il_supported(int, int, int) { return false; } +void native_mmvq_il(int ggml_type, const void* weights, const void* x_q8_1, const void*, float* y, int n_in, int n_out, + int ncols, void* stream) { + native_mmvq(ggml_type, weights, x_q8_1, y, n_in, n_out, ncols, stream); +} +void native_mmvq_il_tune(int) {} +#endif // !__HIPCC__ + } // namespace strata::kernels diff --git a/src/kernels/cuda/q8_1_il.cuh b/src/kernels/cuda/q8_1_il.cuh new file mode 100644 index 00000000..49c7a5a1 --- /dev/null +++ b/src/kernels/cuda/q8_1_il.cuh @@ -0,0 +1,99 @@ +// src/kernels/cuda/q8_1_il.cuh - the interleaved copy of 2..8 q8_1 activation columns (native_mmvq.hpp) as the +// multi-column dot products read it, for native_mmvq.cu and iq_kernels.cu. +#pragma once + +#include "strata/kernels/native_mmvq.hpp" + +#include +#include + +#include +#include + +namespace strata::kernels { +namespace { + +// NC columns of the block-major (PM false) or position-major copy: u(b, p, o) = int p of q8_1 block b of every column, +// scales(b, o) = their scales +template struct Q81Il { + static constexpr int CP = native_q8_1_il_cp(NC); + const int* __restrict__ q; + const float* __restrict__ d; + int nb; // blocks a column + __device__ __forceinline__ void u(int b, int p, int (&o)[NC]) const { + const int* s = q + std::size_t(PM ? p * nb + b : b * 8 + p) * CP; + if constexpr (CP == 2) { + const int2 a = *reinterpret_cast(s); + o[0] = a.x; + o[1] = a.y; + } else { + const int4 a = *reinterpret_cast(s); + o[0] = a.x; + if constexpr (NC > 1) o[1] = a.y; + if constexpr (NC > 2) o[2] = a.z; + if constexpr (NC > 3) o[3] = a.w; + if constexpr (NC > 4) { + const int4 e = *reinterpret_cast(s + 4); + o[4] = e.x; + if constexpr (NC > 5) o[5] = e.y; + if constexpr (NC > 6) o[6] = e.z; + if constexpr (NC > 7) o[7] = e.w; + } + } + } + __device__ __forceinline__ void scales(int b, float (&o)[NC]) const { + const float* s = d + std::size_t(b) * CP; + if constexpr (CP == 2) { + const float2 a = *reinterpret_cast(s); + o[0] = a.x; + o[1] = a.y; + } else { + const float4 a = *reinterpret_cast(s); + o[0] = a.x; + if constexpr (NC > 1) o[1] = a.y; + if constexpr (NC > 2) o[2] = a.z; + if constexpr (NC > 3) o[3] = a.w; + if constexpr (NC > 4) { + const float4 e = *reinterpret_cast(s + 4); + o[4] = e.x; + if constexpr (NC > 5) o[5] = e.y; + if constexpr (NC > 6) o[6] = e.z; + if constexpr (NC > 7) o[7] = e.w; + } + } + } +}; + +// One column's plain q8_1 blocks (36 bytes: the half2 scale and sum, then 32 codes) behind Q81Il's interface +struct Q81One { + const uint8_t* __restrict__ x; + __device__ __forceinline__ void u(int b, int p, int (&o)[1]) const { + o[0] = reinterpret_cast(x + std::size_t(b) * 36 + 4)[p]; + } + __device__ __forceinline__ void scales(int b, float (&o)[1]) const { + o[0] = __low2float(*reinterpret_cast(x + std::size_t(b) * 36)); + } +}; + +// The activations a kernel for NC columns reads: one column's q8_1 blocks, 2+ columns' interleaved copy (nb blocks a +// column) +template +__device__ __forceinline__ auto q8_1_cols(const void* xq, const float* xd, int nb) { + if constexpr (NC == 1) return Q81One{static_cast(xq)}; + else return Q81Il{static_cast(xq), xd, nb}; +} + +// The copy's parts inside the buffer native_q8_1_il_bytes sizes: bm, pm (int32) and d (float). +struct Q81IlParts { + const int* bm; + const int* pm; + const float* d; +}; +inline Q81IlParts q8_1_il_parts(const void* x_il, int n_in, int ncols) { + const std::size_t words = std::size_t(n_in / 32) * 8 * std::size_t(native_q8_1_il_cp(ncols)); + const int* bm = static_cast(x_il); + return {bm, bm + words, reinterpret_cast(bm + 2 * words)}; +} + +} // namespace +} // namespace strata::kernels diff --git a/src/kernels/mmvq_il_parity.cpp b/src/kernels/mmvq_il_parity.cpp new file mode 100644 index 00000000..9c08b6e5 --- /dev/null +++ b/src/kernels/mmvq_il_parity.cpp @@ -0,0 +1,178 @@ +// src/kernels/mmvq_il_parity.cpp - native_mmvq_il (2-4 columns from the interleaved q8_1 copy, fork F4) against +// native_mmvq's multi-column kernels, bitwise, for every rows-a-warp choice; --bench times both per call. +// +// build/mmvq_il_parity [--bench] +// +// The same Q8_1 bytes feed both paths (quantize_q8_1_rows, then native_q8_1_interleave). Weights are random bytes with +// the block scales rewritten as normal fp16 values, so every output is finite (a NaN would compare equal whatever +// produced it). The bench cycles through enough copies of the weights to miss the L2 cache, as a layer's call does. +#include "strata/kernels/iq_kernels.hpp" +#include "strata/kernels/native_mmvq.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace strata::kernels; + +struct Case { + const char* name; + int type, n_in, n_out, block_elems, block_bytes, scale_at[2]; +}; +// the engine's dense shapes: qkv 10240 / gate 6144 / out 2560 (GDN), q 12288 / k,v 512 / o 2560 (QSA), the head +const Case CASES[] = { + {"IQ4_XS 2560x10240", 23, 2560, 10240, 256, 136, {0, -1}}, + {"IQ4_XS 2560x6144", 23, 2560, 6144, 256, 136, {0, -1}}, + {"IQ4_XS 4096x2560", 23, 4096, 2560, 256, 136, {0, -1}}, + {"IQ4_XS 2560x512", 23, 2560, 512, 256, 136, {0, -1}}, + {"Q4_K 2560x10240", 12, 2560, 10240, 256, 144, {0, 2}}, + {"Q4_K 4096x2560", 12, 4096, 2560, 256, 144, {0, 2}}, + {"Q4_K odd rows 2560x2051", 12, 2560, 2051, 256, 144, {0, 2}}, + {"Q5_K 2560x12288", 13, 2560, 12288, 256, 176, {0, 2}}, + {"Q5_K 2560x6144", 13, 2560, 6144, 256, 176, {0, 2}}, + {"Q5_K 4096x2560", 13, 4096, 2560, 256, 176, {0, 2}}, + {"Q5_K head 2560x248320", 13, 2560, 248320, 256, 176, {0, 2}}, + {"Q6_K 2560x12288", 14, 2560, 12288, 256, 210, {208, -1}}, + {"Q6_K 2560x10240", 14, 2560, 10240, 256, 210, {208, -1}}, + {"Q6_K 4096x2560", 14, 4096, 2560, 256, 210, {208, -1}}, + {"Q6_K odd rows 2560x2051", 14, 2560, 2051, 256, 210, {208, -1}}, + {"Q6_K 2560x512", 14, 2560, 512, 256, 210, {208, -1}}, +}; + +uint16_t sane_half(std::mt19937& rng) { + const uint32_t r = rng(); + return (uint16_t) (((r >> 31) << 15) | ((5u + (r >> 10) % 5u) << 10) | (r & 0x3ffu)); +} +bool ck(cudaError_t e, const char* what) { + if (e == cudaSuccess) return true; + std::printf("CUDA: %s: %s\n", what, cudaGetErrorString(e)); + return false; +} + +int run_case(const Case& c, bool bench, cudaStream_t s) { + if (c.type == 13 && c.n_out > 100000 && !bench) { /* the head: parity too, just big */ } + const std::size_t wbytes = native_mmvq_weight_bytes(c.type, c.n_in, c.n_out); + std::mt19937 rng(77u + (unsigned) c.type * 31u + (unsigned) c.n_out); + std::vector w(wbytes); + for (auto& b : w) b = (uint8_t) (rng() & 0xff); + const std::size_t n_blocks = (std::size_t) c.n_out * (std::size_t) (c.n_in / c.block_elems); + if (n_blocks * (std::size_t) c.block_bytes != wbytes) { + std::printf("%s: weight bytes mismatch\n", c.name); + return 1; + } + for (std::size_t k = 0; k < n_blocks; ++k) + for (int at : c.scale_at) + if (at >= 0) { + const uint16_t h = sane_half(rng); + std::memcpy(&w[k * (std::size_t) c.block_bytes + (std::size_t) at], &h, 2); + } + const int copies = bench ? (int) std::max(1, std::min(24, (192u << 20) / wbytes)) : 1; + std::vector dw(copies, nullptr); + for (int i = 0; i < copies; ++i) { + if (!ck(cudaMalloc(&dw[i], wbytes), "malloc w") || !ck(cudaMemcpy(dw[i], w.data(), wbytes, cudaMemcpyHostToDevice), "copy w")) + return 1; + } + int bad = 0; + for (int T = 2; T <= 4; ++T) { + std::vector x((std::size_t) T * c.n_in); + std::normal_distribution nd(0.f, 1.f); + for (auto& v : x) v = nd(rng); + float* dx = nullptr; + void *xq = nullptr, *xil = nullptr; + float *yref = nullptr, *yil = nullptr; + const std::size_t ybytes = (std::size_t) T * c.n_out * 4; + if (!ck(cudaMalloc(&dx, x.size() * 4), "malloc x") || + !ck(cudaMalloc(&xq, native_q8_1_bytes(c.n_in, T)), "malloc xq") || + !ck(cudaMalloc(&xil, native_q8_1_il_bytes(c.n_in, T)), "malloc xil") || + !ck(cudaMalloc((void**) &yref, ybytes), "malloc yref") || !ck(cudaMalloc((void**) &yil, ybytes), "malloc yil")) + return 1; + ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "copy x"); + quantize_q8_1_rows(dx, T, c.n_in, xq, s); + native_q8_1_interleave(xq, xil, c.n_in, T, s); + native_mmvq(c.type, dw[0], xq, yref, c.n_in, c.n_out, T, s); + ck(cudaStreamSynchronize(s), "ref"); + std::vector a((std::size_t) T * c.n_out), b(a.size()); + ck(cudaMemcpy(a.data(), yref, ybytes, cudaMemcpyDeviceToHost), "read ref"); + double best_ref = 0, best_il[5] = {0, 0, 0, 0, 0}; + int table_r = 0; + for (int r : {0, 1, 2, 4}) { + native_mmvq_il_tune(r); + cudaMemset(yil, 0xff, ybytes); + native_mmvq_il(c.type, dw[0], xq, xil, yil, c.n_in, c.n_out, T, s); + ck(cudaStreamSynchronize(s), "il"); + ck(cudaMemcpy(b.data(), yil, ybytes, cudaMemcpyDeviceToHost), "read il"); + long long diff = 0, nonfinite = 0; + for (std::size_t i = 0; i < a.size(); ++i) { + float fa; + std::memcpy(&fa, &a[i], 4); + if (!std::isfinite(fa)) ++nonfinite; + if (a[i] != b[i]) ++diff; + } + const bool used = r != 0 || native_mmvq_il_supported(c.type, T, c.n_out); + if (diff != 0 || nonfinite != 0) { + ++bad; + std::printf("FAIL %-26s T=%d rows=%d: %lld bits differ, %lld non-finite of %zu\n", c.name, T, r, diff, nonfinite, a.size()); + } + (void) used; + if (bench && r != 0) { + cudaEvent_t e0, e1; + cudaEventCreate(&e0); + cudaEventCreate(&e1); + const int reps = 200; + for (int rep = 0; rep < 2; ++rep) { // rep 0 warms, rep 1 times + cudaEventRecord(e0, s); + for (int i = 0; i < reps; ++i) native_mmvq_il(c.type, dw[i % copies], xq, xil, yil, c.n_in, c.n_out, T, s); + cudaEventRecord(e1, s); + cudaEventSynchronize(e1); + } + float ms; + cudaEventElapsedTime(&ms, e0, e1); + best_il[r] = 1000.0 * ms / reps; + cudaEventDestroy(e0); + cudaEventDestroy(e1); + } + } + native_mmvq_il_tune(0); + if (bench) { + cudaEvent_t e0, e1; + cudaEventCreate(&e0); + cudaEventCreate(&e1); + const int reps = 200; + for (int rep = 0; rep < 2; ++rep) { + cudaEventRecord(e0, s); + for (int i = 0; i < reps; ++i) native_mmvq(c.type, dw[i % copies], xq, yref, c.n_in, c.n_out, T, s); + cudaEventRecord(e1, s); + cudaEventSynchronize(e1); + } + float ms; + cudaEventElapsedTime(&ms, e0, e1); + best_ref = 1000.0 * ms / reps; + (void) table_r; + std::printf("BENCH %-26s T=%d multi %.1f us | il rows1 %.1f rows2 %.1f rows4 %.1f us\n", c.name, T, best_ref, + best_il[1], best_il[2], best_il[4]); + } + cudaFree(dx); cudaFree(xq); cudaFree(xil); cudaFree(yref); cudaFree(yil); + } + for (void* p : dw) cudaFree(p); + return bad; +} +} // namespace + +int main(int argc, char** argv) { + const bool bench = argc > 1 && std::string(argv[1]) == "--bench"; + cudaStream_t s; + cudaStreamCreate(&s); + int bad = 0; + for (const Case& c : CASES) bad += run_case(c, bench, s); + std::printf("%s\n", bad ? "mmvq_il_parity: FAIL" : "mmvq_il_parity: OK (every case, T 2-4, rows 1/2/4 and the table, bitwise)"); + return bad ? 1 : 0; +}