From 6edf8bde75a81381de7f039974fc66eed94cac52 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 2 Oct 2026 19:30:41 +0200 Subject: [PATCH 01/55] HIP: admit gfx1151 (Strix Halo, RDNA3.5) as an experimental target, with sudot4 --- cmake/hip_backend.cmake | 5 +++-- include/strata/hip_compat/intrinsics.hpp | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/cmake/hip_backend.cmake b/cmake/hip_backend.cmake index 255ee381..51765606 100644 --- a/cmake/hip_backend.cmake +++ b/cmake/hip_backend.cmake @@ -8,10 +8,11 @@ endif() # maintainers; gfx1101 (RX 7800 XT, #254) and gfx1200 (RX 9060 XT, #256) by their owners. gfx1102 (RX 7600) has the # same LDS limit and dot4 instruction and passed ctest (#192), but no model run has been reported yet. RDNA2 gfx1030 (RX 6800 / 6900) has the # same LDS limit and wave32 but an older dot4 instruction (v_dot4_i32_i8, hip_compat/intrinsics.hpp); a community -# report ran it (#311), the maintainers have not. +# report ran it (#311), the maintainers have not. gfx1151 (Ryzen AI Max / Strix Halo, Radeon 8060S, RDNA3.5) is the +# same wave32 / 64 KiB LDS / sudot4 family as gfx1100, on a unified-memory APU; experimental. set(_strata_hip_validated gfx1100 gfx1201) set(_strata_hip_community gfx1101 gfx1200) -set(_strata_hip_unvalidated gfx1102 gfx1030) +set(_strata_hip_unvalidated gfx1102 gfx1030 gfx1151) # CMake hands HIP a ';' list, but a -DCMAKE_HIP_ARCHITECTURES typed by hand (or ROCm's own Windows tooling) may use # spaces, which foreach(IN LISTS) would otherwise treat as one element. string(REPLACE " " ";" _strata_hip_norm "${CMAKE_HIP_ARCHITECTURES}") diff --git a/include/strata/hip_compat/intrinsics.hpp b/include/strata/hip_compat/intrinsics.hpp index a789e38c..97915263 100644 --- a/include/strata/hip_compat/intrinsics.hpp +++ b/include/strata/hip_compat/intrinsics.hpp @@ -15,7 +15,8 @@ __device__ __forceinline__ int signed_byte(uint32_t word, int lane) { // CUDA's signed __dp4a: four signed byte products accumulated modulo 2^32. __device__ __forceinline__ int dp4a(int a, int b, int c) { -#if (defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1200__) || \ +#if (defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || \ + defined(__gfx1151__) || defined(__gfx1200__) || \ defined(__gfx1201__)) && __has_builtin(__builtin_amdgcn_sudot4) // RDNA3 and RDNA4 expose the signed/unsigned dot4 form (v_dot4_i32_iu8). Mark // both packed operands signed to preserve CUDA __dp4a semantics; keep the From 601b7765b60c9378076d32426892e119e3094797 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 2 Oct 2026 19:48:51 +0200 Subject: [PATCH 02/55] HIP: the matrix-core prompt attention (STRATA_HIP_WMMA=1) on gfx11 (RDNA3 / RDNA3.5) too gfx11's v_wmma_f32_16x16x16_f16 takes all 16 k per lane (lanes 16..31 repeat 0..15) and returns C rows 2i + lane/16; the kernel loads its fragments in that layout. Opt-in as on gfx12. --- src/kernels/cuda/qsa_prompt_attn.cu | 85 ++++++++++++++++++-------- src/kernels/qsa_prompt_attn_parity.cpp | 4 +- 2 files changed, 60 insertions(+), 29 deletions(-) diff --git a/src/kernels/cuda/qsa_prompt_attn.cu b/src/kernels/cuda/qsa_prompt_attn.cu index 4af82be2..30de4b34 100644 --- a/src/kernels/cuda/qsa_prompt_attn.cu +++ b/src/kernels/cuda/qsa_prompt_attn.cu @@ -697,12 +697,30 @@ bool launch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const // FP32-level accuracy, deterministic, but not bitwise equal to qsa_decode_attn_batch (another summation order). // Fragment layout (16x16x16, wave32, checked on gfx1201): A lane l holds A[l % 16][(l / 16) * 8 + i], B lane l holds // B[(l / 16) * 8 + i][l % 16], C/D lane l holds D[(l / 16) * 8 + i][l % 16], i = 0..7. +// gfx11 (RDNA3 / RDNA3.5: gfx110x, gfx115x) has the same instruction with another layout: A lane l holds all 16 k of +// row l % 16 (lanes 16..31 repeat lanes 0..15), B lane l all 16 k of column l % 16, and C/D lane l holds +// D[2 * i + l / 16][l % 16]. PA_KL is the k values per lane (8 or 16), PA_KOFF(half) the first one, PA_ROW the C row. #if defined(__gfx1200__) || defined(__gfx1201__) #define STRATA_PA_WMMA 1 +#define STRATA_PA_GFX11 0 +#elif defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || \ + defined(__gfx1151__) +#define STRATA_PA_WMMA 1 +#define STRATA_PA_GFX11 1 #else #define STRATA_PA_WMMA 0 +#define STRATA_PA_GFX11 0 #endif -typedef _Float16 wh8 __attribute__((ext_vector_type(8))); +#if STRATA_PA_GFX11 +constexpr int PA_KL = 16; +#define PA_KOFF(half) 0 +#define PA_ROW(i, half) (2 * (i) + (half)) +#else +constexpr int PA_KL = 8; +#define PA_KOFF(half) ((half) * 8) +#define PA_ROW(i, half) ((half) * 8 + (i)) +#endif +typedef _Float16 wh8 __attribute__((ext_vector_type(PA_KL))); typedef float wf8 __attribute__((ext_vector_type(8))); constexpr int WCH = 32; // cells per chunk (two 16-cell tiles) constexpr int WVS = 80; // staged V row stride in bytes (64 codes, 16-byte aligned, banks spread) @@ -719,7 +737,9 @@ struct alignas(16) SmemW { }; __device__ __forceinline__ wf8 wmma_f16(wh8 a, wh8 b, wf8 c) { -#if STRATA_PA_WMMA +#if STRATA_PA_WMMA && STRATA_PA_GFX11 + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c); +#elif STRATA_PA_WMMA return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c); #else __builtin_trap(); @@ -727,13 +747,10 @@ __device__ __forceinline__ wf8 wmma_f16(wh8 a, wh8 b, wf8 c) { #endif } -__device__ __forceinline__ wh8 i8x8_to_h8(uint2 x) { // exact: |code| <= 128 +__device__ __forceinline__ wh8 i8_to_h(const uint32_t* x) { // PA_KL codes, exact: |code| <= 128 wh8 h; #pragma unroll - for (int i = 0; i < 4; ++i) { - h[i] = (_Float16) (int) (int8_t) (x.x >> (8 * i)); - h[4 + i] = (_Float16) (int) (int8_t) (x.y >> (8 * i)); - } + for (int i = 0; i < PA_KL; ++i) h[i] = (_Float16) (int) (int8_t) (x[i / 4] >> (8 * (i % 4))); return h; } @@ -765,21 +782,24 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float* int qe = 0; if (qm > 0.0f) frexpf(qm, &qe); const float qup = ldexpf(1.0f, 14 - qe), qdown = ldexpf(scale_log2, qe - 14); - // q A fragments of this wave's 64 dims: row = col (heads 12..15 zero), k = dim0 + kk*16 + half*8 + i + // q A fragments of this wave's 64 dims: row = col (heads 12..15 zero), k = dim0 + kk*16 + PA_KOFF(half) + i wh8 qh[4], ql[4]; #pragma unroll for (int kk = 0; kk < 4; ++kk) { - float x[8]; + float x[PA_KL]; if (col < G) { - const float4* src = reinterpret_cast(q + (size_t) col * HD + dim0 + kk * 16 + half * 8); - const float4 a = src[0], b = src[1]; - x[0] = a.x; x[1] = a.y; x[2] = a.z; x[3] = a.w; x[4] = b.x; x[5] = b.y; x[6] = b.z; x[7] = b.w; + const float4* src = reinterpret_cast(q + (size_t) col * HD + dim0 + kk * 16 + PA_KOFF(half)); +#pragma unroll + for (int j = 0; j < PA_KL / 4; ++j) { + const float4 a = src[j]; + x[4 * j] = a.x; x[4 * j + 1] = a.y; x[4 * j + 2] = a.z; x[4 * j + 3] = a.w; + } } else { #pragma unroll - for (int i = 0; i < 8; ++i) x[i] = 0.0f; + for (int i = 0; i < PA_KL; ++i) x[i] = 0.0f; } #pragma unroll - for (int i = 0; i < 8; ++i) { + for (int i = 0; i < PA_KL; ++i) { const float v = x[i] * qup; const _Float16 hi = (_Float16) v; qh[kk][i] = hi; @@ -826,14 +846,23 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float* if (rr >= 0) ksc = __half2float(__ushort_as_half(__ldg(p.k_scale + rr * (HD / KV_Q8_GROUP) + warp))); #pragma unroll for (int kk = 0; kk < 4; ++kk) { - uint2 kx = make_uint2(0, 0); - if (rr >= 0) kx = __ldg(reinterpret_cast(p.k_q + rr * HD + dim0 + kk * 16 + half * 8)); - const wh8 b = i8x8_to_h8(kx); + uint32_t kx[PA_KL / 4] = {}; + if (rr >= 0) { + const uint32_t* src = reinterpret_cast(p.k_q + rr * HD + dim0 + kk * 16 + PA_KOFF(half)); +#if STRATA_PA_GFX11 + const uint4 v = __ldg(reinterpret_cast(src)); + kx[0] = v.x; kx[1] = v.y; kx[2] = v.z; kx[3] = v.w; +#else + const uint2 v = __ldg(reinterpret_cast(src)); + kx[0] = v.x; kx[1] = v.y; +#endif + } + const wh8 b = i8_to_h(kx); s = wmma_f16(qh[kk], b, s); s = wmma_f16(ql[kk], b, s); } #pragma unroll - for (int i = 0; i < 8; ++i) S.part[warp][half * 8 + i][nt * 16 + col] = s[i] * ksc; + for (int i = 0; i < 8; ++i) S.part[warp][PA_ROW(i, half)][nt * 16 + col] = s[i] * ksc; } __syncthreads(); // online softmax over the four groups' sum (fixed order): row t/8, 4 cells per thread @@ -880,10 +909,10 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float* for (int j = 0; j < 4; ++j) tmp[j] = wf8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; #pragma unroll for (int ks = 0; ks < 2; ++ks) { - const int cb = ks * 16 + half * 8; // this lane's 8 cells + const int cb = ks * 16 + PA_KOFF(half); // this lane's PA_KL cells wh8 ah, al; #pragma unroll - for (int i = 0; i < 8; ++i) { + for (int i = 0; i < PA_KL; ++i) { const float pv = S.p[col][cb + i] * (S.vs[warp][cb + i] * vup); const _Float16 hi = (_Float16) pv; ah[i] = hi; @@ -894,14 +923,14 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float* const int d = j * 16 + col; wh8 b; #pragma unroll - for (int i = 0; i < 8; ++i) b[i] = (_Float16) (int) (int8_t) S.v[warp][cb + i][d]; + for (int i = 0; i < PA_KL; ++i) b[i] = (_Float16) (int) (int8_t) S.v[warp][cb + i][d]; tmp[j] = wmma_f16(ah, b, tmp[j]); tmp[j] = wmma_f16(al, b, tmp[j]); } } float a[8]; #pragma unroll - for (int i = 0; i < 8; ++i) a[i] = S.alpha[half * 8 + i]; + for (int i = 0; i < 8; ++i) a[i] = S.alpha[PA_ROW(i, half)]; #pragma unroll for (int j = 0; j < 4; ++j) #pragma unroll @@ -913,14 +942,14 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float* float inv[8]; #pragma unroll for (int i = 0; i < 8; ++i) { - const float l = S.lsum[half * 8 + i]; + const float l = S.lsum[PA_ROW(i, half)]; inv[i] = l > 0.0f ? 1.0f / l : 0.0f; } #pragma unroll for (int j = 0; j < 4; ++j) #pragma unroll for (int i = 0; i < 8; ++i) { - const int row = half * 8 + i; + const int row = PA_ROW(i, half); if (row < G) attn[(size_t) row * HD + dim0 + j * 16 + col] = acc[j][i] * inv[i]; } #else @@ -928,20 +957,22 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float* #endif } -// gfx12 (RDNA4) only, and only on request: the output differs from the default kernel's in its last bits +// gfx12 (RDNA4) and gfx11 (RDNA3 / RDNA3.5), only on request: the output differs from the default kernel's in its +// last bits bool hip_wmma_usable() { static const bool want = [] { const char* e = std::getenv("STRATA_HIP_WMMA"); return e != nullptr && e[0] == '1'; }(); if (!want) return false; - static int arch[64] = {}; // 0 unknown, 1 gfx12, 2 other + static int arch[64] = {}; // 0 unknown, 1 gfx11 / gfx12, 2 other int dev = 0; if (hipGetDevice(&dev) != hipSuccess || dev < 0 || dev >= 64) { (void) hipGetLastError(); return false; } if (arch[dev] == 0) { hipDeviceProp_t prop{}; if (hipGetDeviceProperties(&prop, dev) != hipSuccess) { (void) hipGetLastError(); return false; } - arch[dev] = std::strncmp(prop.gcnArchName, "gfx12", 5) == 0 ? 1 : 2; + arch[dev] = std::strncmp(prop.gcnArchName, "gfx12", 5) == 0 || std::strncmp(prop.gcnArchName, "gfx11", 5) == 0 + ? 1 : 2; static bool told = false; if (!told) { told = true; diff --git a/src/kernels/qsa_prompt_attn_parity.cpp b/src/kernels/qsa_prompt_attn_parity.cpp index c5dad7c9..14efdc2b 100644 --- a/src/kernels/qsa_prompt_attn_parity.cpp +++ b/src/kernels/qsa_prompt_attn_parity.cpp @@ -204,8 +204,8 @@ int main(int argc, char** argv) { int dev = 0; hipDeviceProp_t prop{}; if (hipGetDevice(&dev) != hipSuccess || hipGetDeviceProperties(&prop, dev) != hipSuccess) return 2; - if (std::strncmp(prop.gcnArchName, "gfx12", 5) != 0) { - std::printf("SKIP: %s is not gfx12 (the matrix-core prompt attention is RDNA4 only)\n", prop.gcnArchName); + if (std::strncmp(prop.gcnArchName, "gfx12", 5) != 0 && std::strncmp(prop.gcnArchName, "gfx11", 5) != 0) { + std::printf("SKIP: %s is not gfx11 / gfx12 (the matrix-core prompt attention)\n", prop.gcnArchName); return 77; } #if defined(_WIN32) From c6a0d4033be7d2154bdae5cd55f95960898e41dc Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 2 Oct 2026 19:48:58 +0200 Subject: [PATCH 03/55] prefill: MMQ groups of a fully resident layer in row-count order (opt-in STRATA_MMQ_RESIDENT_SORT_NE=1) Port of the Aurora experiment (mmq-resident-rowcount-sorting-v1, +13% 8K prompt on gfx1151 over 0.1.30 + Lt, identical output ids there): each 16-expert MMQ group's max_rows is close to its experts' own row counts, so less tile padding. Host-only; slot/src/off rebuilt before the upload. --- src/prefill/mmq_resident_sort.hpp | 59 +++++++++++++++++++++++++++++++ src/prefill/prefill.cpp | 15 ++++++-- 2 files changed, 71 insertions(+), 3 deletions(-) create mode 100644 src/prefill/mmq_resident_sort.hpp diff --git a/src/prefill/mmq_resident_sort.hpp b/src/prefill/mmq_resident_sort.hpp new file mode 100644 index 00000000..2e03856b --- /dev/null +++ b/src/prefill/mmq_resident_sort.hpp @@ -0,0 +1,59 @@ +// Host-only opt-in grouping permutation. No HIP calls, device math, or precision changes. +#pragma once + +#include +#include +#include +#include +#include + +namespace strata::prefill::detail { + +inline bool mmq_resident_sort_flag(const char* value) { + return value != nullptr && std::strcmp(value, "1") == 0; +} + +inline bool mmq_resident_sort_requested() { + static const bool on = mmq_resident_sort_flag(std::getenv("STRATA_MMQ_RESIDENT_SORT_NE")); + return on; +} + +inline bool mmq_resident_sort_eligible(bool requested, bool use_mmq, bool native_layout, bool has_cache, + const int32_t* layer_resident, int64_t n_expert, + bool stream_all, bool layer_stream_empty) { + if (!requested || !use_mmq || native_layout || !has_cache || !layer_resident || n_expert <= 0) return false; + // All experts, including unselected ones: leave every partial/streamed layer in ID order. + if (stream_all && !layer_stream_empty) return false; + for (int64_t e = 0; e < n_expert; ++e) if (layer_resident[e] < 0) return false; + return true; +} + +// Preconditions are established by the existing caller: IDs were range-checked and counted; +// order contains each positive-count expert once in ID order; off has count.size()+1 entries; +// routes fits its original int32 offsets, and slot/src each have routes writable entries. +// After sorting, off[e] is an expert-indexed START, not an ID-prefix end at off[e+1]. +inline void mmq_resident_sort_rows(const int32_t* ids, int64_t routes, int32_t k, + const std::vector& count, std::vector& off, + std::vector& order, int32_t* slot, int32_t* src) { + std::stable_sort(order.begin(), order.end(), [&](int32_t a, int32_t b) { + return count[(size_t) a] != count[(size_t) b] + ? count[(size_t) a] < count[(size_t) b] : a < b; + }); + std::fill(off.begin(), off.end(), 0); + int32_t cursor = 0; + for (int32_t e : order) { + off[(size_t) e] = cursor; + cursor += count[(size_t) e]; + } + off.back() = cursor; + std::vector fill(off.begin(), off.end() - 1); + // Preserve token-major/rank-major traversal, hence the original within-expert row order. + for (int64_t i = 0; i < routes; ++i) { + const int32_t e = ids[(size_t) i]; + const int32_t p = fill[(size_t) e]++; + slot[(size_t) i] = p; + src[(size_t) p] = (int32_t) (i / k); + } +} + +} // namespace strata::prefill::detail diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index dc35c2be..83ff730b 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -1,5 +1,6 @@ // src/prefill/prefill.cpp - see include/strata/prefill/prefill.hpp. #include "strata/prefill/prefill.hpp" +#include "mmq_resident_sort.hpp" #include "strata/core/mtp.hpp" #include "strata/core/progress.hpp" #include "strata/core/on_device.hpp" @@ -1742,6 +1743,17 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e slot_h[(size_t) i] = p; src_h[(size_t) p] = (int32_t) (i / K); } + // the experts, in id order: resident ones from VRAM, the others through the staging ring + std::vector order; + for (int32_t e = 0; e < m.g->n_expert; ++e) if (m.cnt[(size_t) e] > 0) order.push_back(e); + // Aurora (STRATA_MMQ_RESIDENT_SORT_NE=1, opt-in): a layer whose experts are ALL resident and + // run through MMQ groups takes them in row-count order, so each 16-expert group's max_rows + // (its padded tile rows) is close to its experts' own; slot/src/off are rebuilt coherently + // before the upload, the routed ids, weights and the within-expert row order stay as they are. + if (detail::mmq_resident_sort_eligible(detail::mmq_resident_sort_requested(), use_mmq, lay.native, + m.cache != nullptr, m.host_res ? m.host_res + (size_t) l * m.g->n_expert : nullptr, + m.g->n_expert, stream_all, !stream_all || seq_start[(size_t) l] == seq_start[(size_t) l + 1])) + detail::mmq_resident_sort_rows(ids_h, T * K, (int32_t) K, m.cnt, m.off, order, slot_h, src_h); if (grp_mapped) { copy_i32(m.slot_dev, m.grp_dev + m.grp_tk, T * K, m.cs); copy_i32(m.src_dev, m.grp_dev + 2 * m.grp_tk, T * K, m.cs); @@ -1749,9 +1761,6 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e cudaMemcpyAsync(m.slot_dev, m.slot_host.data(), (size_t) T * K * 4, cudaMemcpyHostToDevice, m.cs); cudaMemcpyAsync(m.src_dev, m.src_host.data(), (size_t) T * K * 4, cudaMemcpyHostToDevice, m.cs); } - // the experts, in id order: resident ones from VRAM, the others through the staging ring - std::vector order; - for (int32_t e = 0; e < m.g->n_expert; ++e) if (m.cnt[(size_t) e] > 0) order.push_back(e); n_order = order.size(); const size_t mmq_gub = use_mmq ? mmq::matrix_bytes(mmq_gt, 1280, N) : 0; const size_t mmq_db = use_mmq ? mmq::matrix_bytes(mmq_dt, N, 640) : 0; From 41dbcdff32caf8b0ddc4f4d0fcce73e974d84d96 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 2 Oct 2026 20:02:17 +0200 Subject: [PATCH 04/55] hip: hipBLASLt tuning table for gfx1151 (Strix Halo, ROCm 7.14.1 / hipBLASLt 100401) All 15 prompt GEMM shapes of Qwen3.8-Flash-Next at chunks 2048 and 8192 (T = 2047/2048/8191/8192), tuned on Aurora (Ryzen AI Max+ 395) with tools/hip/tune_hipblaslt.cpp. --- tools/hip/gfx1151-hipblaslt-100401.txt | 62 ++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 tools/hip/gfx1151-hipblaslt-100401.txt diff --git a/tools/hip/gfx1151-hipblaslt-100401.txt b/tools/hip/gfx1151-hipblaslt-100401.txt new file mode 100644 index 00000000..b39be529 --- /dev/null +++ b/tools/hip/gfx1151-hipblaslt-100401.txt @@ -0,0 +1,62 @@ +# solution IDs are scoped to this hipBLASLt version and device architecture +STRATA_HIPBLASLT_TUNING_V1 gfx1151 100401 +bf16 10240 320 10240 2047 1177 +bf16 128 2560 128 2047 1177 +bf16 1 2560 1 2047 1174 +bf16 2560 2560 2560 2047 1177 +bf16 320 10240 320 2047 1176 +bf16 48 2560 96 2047 1176 +bf16 4 10240 4 2047 1174 +bf16 512 2560 512 2047 1177 +f16 10240 2560 10240 2047 2390 +f16 12288 2560 12288 2047 2390 +f16 2560 6144 2560 2047 2390 +f16 2560 640 2560 2047 2390 +f16 512 2560 512 2047 2389 +f16 6144 2560 6144 2047 2390 +f16 640 2560 640 2047 2389 +bf16 10240 320 10240 2048 1177 +bf16 128 2560 128 2048 1177 +bf16 1 2560 1 2048 1174 +bf16 2560 2560 2560 2048 1177 +bf16 320 10240 320 2048 1176 +bf16 48 2560 96 2048 1176 +bf16 4 10240 4 2048 1175 +bf16 512 2560 512 2048 1176 +f16 10240 2560 10240 2048 2390 +f16 12288 2560 12288 2048 2390 +f16 2560 6144 2560 2048 2390 +f16 2560 640 2560 2048 2390 +f16 512 2560 512 2048 2390 +f16 6144 2560 6144 2048 2390 +f16 640 2560 640 2048 2390 +bf16 10240 320 10240 8191 1177 +bf16 128 2560 128 8191 1177 +bf16 1 2560 1 8191 1175 +bf16 2560 2560 2560 8191 1177 +bf16 320 10240 320 8191 1176 +bf16 48 2560 96 8191 1176 +bf16 4 10240 4 8191 1174 +bf16 512 2560 512 8191 1177 +f16 10240 2560 10240 8191 2390 +f16 12288 2560 12288 8191 2390 +f16 2560 6144 2560 8191 2390 +f16 2560 640 2560 8191 2390 +f16 512 2560 512 8191 2390 +f16 6144 2560 6144 8191 2390 +f16 640 2560 640 8191 2390 +bf16 10240 320 10240 8192 1177 +bf16 128 2560 128 8192 1177 +bf16 1 2560 1 8192 1175 +bf16 2560 2560 2560 8192 1177 +bf16 320 10240 320 8192 1176 +bf16 48 2560 96 8192 1176 +bf16 4 10240 4 8192 1175 +bf16 512 2560 512 8192 1177 +f16 10240 2560 10240 8192 2390 +f16 12288 2560 12288 8192 2390 +f16 2560 6144 2560 8192 2390 +f16 2560 640 2560 8192 2390 +f16 512 2560 512 8192 2390 +f16 6144 2560 6144 8192 2390 +f16 640 2560 640 8192 2390 From 92dde2f72ea15893b42182134eea0210473bf7a6 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 2 Oct 2026 20:17:55 +0200 Subject: [PATCH 05/55] HIP: the WMMA QSA block scorer (STRATA_SELECT_WMMA=1) on gfx11 (RDNA3 / RDNA3.5) too gfx11's bf16 WMMA layout: 16 k per lane, C rows 2i + lane/16. On gfx1151 (qsa_select_bench, 131624 capacity): ctx 32768 x 2048 queries scores 14.2 -> 3.5 ms (4.1x), selections identical 2047/2048; ctx 65536 x 8192 queries 110.1 -> 25.9 ms (4.3x), identical 8192/8192. Still opt-in, as on gfx12. --- src/kernels/cuda/qsa_select.cu | 62 +++++++++++++++++++++++----------- 1 file changed, 42 insertions(+), 20 deletions(-) diff --git a/src/kernels/cuda/qsa_select.cu b/src/kernels/cuda/qsa_select.cu index 2d6638a9..454a7d9c 100644 --- a/src/kernels/cuda/qsa_select.cu +++ b/src/kernels/cuda/qsa_select.cu @@ -291,14 +291,32 @@ __global__ void __launch_bounds__(128) block_scores_tc_kernel(const float* __res // a lane ends up with 8 consecutive blocks of ONE query, written as one run. No LDS for keys: a lane reads its // 32-byte slice of the key row from global (the 16 query tiles of a launch re-read them from L2); the queries are // split once per CTA into LDS. +// gfx11 (RDNA3 / RDNA3.5) has the same instruction with another fragment layout: a lane holds all 16 k of its row +// (A) or column (B) - lanes 16..31 repeat lanes 0..15 - and D[2i + l/16][l%16]; SEL_KL is the k per lane, SEL_KOFF(g) +// the first, SEL_ROW(i, g) the D row of element i. Same products, same order per element as on gfx12. #if defined(__gfx1200__) || defined(__gfx1201__) #define STRATA_SEL_GFX12 1 +#define STRATA_SEL_GFX11 0 +#elif defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || \ + defined(__gfx1151__) +#define STRATA_SEL_GFX12 0 +#define STRATA_SEL_GFX11 1 #else #define STRATA_SEL_GFX12 0 +#define STRATA_SEL_GFX11 0 #endif -typedef short sel_s8 __attribute__((ext_vector_type(8))); +#if STRATA_SEL_GFX11 +constexpr int SEL_KL = 16; +#define SEL_KOFF(g) 0 +#define SEL_ROW(i, g) (2 * (i) + (g)) +#else +constexpr int SEL_KL = 8; +#define SEL_KOFF(g) ((g) * 8) +#define SEL_ROW(i, g) ((g) * 8 + (i)) +#endif +typedef short sel_s8 __attribute__((ext_vector_type(SEL_KL))); typedef float sel_f8 __attribute__((ext_vector_type(8))); -typedef uint32_t sel_u4 __attribute__((ext_vector_type(4))); +typedef uint32_t sel_u4 __attribute__((ext_vector_type(SEL_KL / 2))); constexpr int WQT = 16; // queries per CTA (the N of one WMMA) constexpr int WITER = 4; // key tiles per warp (the CTA covers 4 warps * WITER * 16 blocks) constexpr int WQS = IDX_DIM + 8; // bf16 elements per LDS row: 272 bytes, conflict-free 16-byte reads @@ -306,6 +324,8 @@ constexpr int WQS = IDX_DIM + 8; // bf16 elements per LDS row: 272 byt __device__ __forceinline__ sel_f8 wmma_bf16(const sel_s8& a, const sel_s8& b, const sel_f8& c) { #if STRATA_SEL_GFX12 return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(a, b, c); +#elif STRATA_SEL_GFX11 + return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a, b, c); #else __trap(); return c; @@ -319,7 +339,7 @@ __device__ __forceinline__ void split3(float x, uint32_t& hi, uint32_t& mid, uin lo = __float_as_uint(r1 - __uint_as_float(mid)) & 0xffff0000u; // exact: at most 8 significant bits left } __device__ __forceinline__ uint32_t pack_bf16x2(uint32_t a, uint32_t b) { // low half = a's bf16, high half = b's -#if STRATA_SEL_GFX12 +#if STRATA_SEL_GFX12 || STRATA_SEL_GFX11 return __builtin_amdgcn_perm(b, a, 0x07060302u); #else return (a >> 16) | (b & 0xffff0000u); @@ -360,7 +380,7 @@ __global__ void __launch_bounds__(128) block_scores_wmma_kernel(const float* __r if (b0 >= reach || b0 >= hi_nbid) break; // warp-uniform; later tiles start higher const int64_t row = b0 + l16; const bool rv = row < hi_nbid && row < max_blocks; - const float* kp = pooled + (rv ? row : 0) * IDX_DIM + g * 8; + const float* kp = pooled + (rv ? row : 0) * IDX_DIM + SEL_KOFF(g); // acc: the hi*hi products; cor: the five smaller ones (<= 2^-8 of it). Kept apart and added once at the end: a // correction summed into the big accumulator is rounded to ITS ulp at every one of the 48 steps (measured: 8e-7 // of the score scale; apart, near the warp kernel's) @@ -369,18 +389,19 @@ __global__ void __launch_bounds__(128) block_scores_wmma_kernel(const float* __r for (int h = 0; h < IDX_HEADS; ++h) acc[h] = cor[h] = sel_f8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; #pragma unroll 2 for (int kk = 0; kk < IDX_DIM / 16; ++kk) { - float4 k0 = make_float4(0.f, 0.f, 0.f, 0.f), k1 = k0; - if (rv) { - k0 = *reinterpret_cast(kp + kk * 16); - k1 = *reinterpret_cast(kp + kk * 16 + 4); - } - const float x[8] = {k0.x, k0.y, k0.z, k0.w, k1.x, k1.y, k1.z, k1.w}; - uint32_t hb[8], mb[8], lb[8]; + float x[SEL_KL]; #pragma unroll - for (int j = 0; j < 8; ++j) split3(x[j], hb[j], mb[j], lb[j]); + for (int j = 0; j < SEL_KL / 4; ++j) { + float4 kv = make_float4(0.f, 0.f, 0.f, 0.f); + if (rv) kv = *reinterpret_cast(kp + kk * 16 + 4 * j); + x[4 * j] = kv.x; x[4 * j + 1] = kv.y; x[4 * j + 2] = kv.z; x[4 * j + 3] = kv.w; + } + uint32_t hb[SEL_KL], mb[SEL_KL], lb[SEL_KL]; +#pragma unroll + for (int j = 0; j < SEL_KL; ++j) split3(x[j], hb[j], mb[j], lb[j]); sel_u4 ah, am, al; #pragma unroll - for (int j = 0; j < 4; ++j) { + for (int j = 0; j < SEL_KL / 2; ++j) { ah[j] = pack_bf16x2(hb[2 * j], hb[2 * j + 1]); am[j] = pack_bf16x2(mb[2 * j], mb[2 * j + 1]); al[j] = pack_bf16x2(lb[2 * j], lb[2 * j + 1]); @@ -389,9 +410,9 @@ __global__ void __launch_bounds__(128) block_scores_wmma_kernel(const float* __r Al = __builtin_bit_cast(sel_s8, al); #pragma unroll for (int h = 0; h < IDX_HEADS; ++h) { - const sel_s8 Bh = *reinterpret_cast(&sq[0][h][l16][kk * 16 + g * 8]); - const sel_s8 Bm = *reinterpret_cast(&sq[1][h][l16][kk * 16 + g * 8]); - const sel_s8 Bl = *reinterpret_cast(&sq[2][h][l16][kk * 16 + g * 8]); + const sel_s8 Bh = *reinterpret_cast(&sq[0][h][l16][kk * 16 + SEL_KOFF(g)]); + const sel_s8 Bm = *reinterpret_cast(&sq[1][h][l16][kk * 16 + SEL_KOFF(g)]); + const sel_s8 Bl = *reinterpret_cast(&sq[2][h][l16][kk * 16 + SEL_KOFF(g)]); cor[h] = wmma_bf16(Al, Bh, cor[h]); cor[h] = wmma_bf16(Ah, Bl, cor[h]); cor[h] = wmma_bf16(Am, Bm, cor[h]); @@ -400,11 +421,11 @@ __global__ void __launch_bounds__(128) block_scores_wmma_kernel(const float* __r acc[h] = wmma_bf16(Ah, Bh, acc[h]); } } - // relu per head, heads added in order (as the warp kernel); this lane: query qi, blocks b0 + 8g .. 8g+7 + // relu per head, heads added in order (as the warp kernel); this lane: query qi, blocks b0 + SEL_ROW(i, g) if (qi < nq) { #pragma unroll for (int i = 0; i < 8; ++i) { - const int64_t b = b0 + g * 8 + i; + const int64_t b = b0 + SEL_ROW(i, g); if (b >= nb_q || b >= max_blocks) continue; float score = 0.0f; #pragma unroll @@ -418,7 +439,7 @@ __global__ void __launch_bounds__(128) block_scores_wmma_kernel(const float* __r } } -// the gfx12 kernel needs gfx1200/gfx1201 code objects and a gfx12 device (gfx1100 has WMMA too, with another layout) +// the WMMA kernel needs gfx12 (gfx1200/gfx1201) or gfx11 (gfx110x/gfx115x: the other fragment layout) code objects bool sel_gfx12_device() { static int ok[64] = {}; // per device: 0 unknown, 1 yes, 2 no int dev = 0; @@ -426,7 +447,8 @@ bool sel_gfx12_device() { if (ok[dev] == 0) { cudaDeviceProp prop; ok[dev] = (cudaGetDeviceProperties(&prop, dev) == cudaSuccess && - (std::strncmp(prop.gcnArchName, "gfx1200", 7) == 0 || std::strncmp(prop.gcnArchName, "gfx1201", 7) == 0)) + (std::strncmp(prop.gcnArchName, "gfx1200", 7) == 0 || std::strncmp(prop.gcnArchName, "gfx1201", 7) == 0 || + std::strncmp(prop.gcnArchName, "gfx110", 6) == 0 || std::strncmp(prop.gcnArchName, "gfx115", 6) == 0)) ? 1 : 2; cudaGetLastError(); } From 9a427232831f2ba0260c4b5639afc0914cdd36ad Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 2 Oct 2026 20:22:36 +0200 Subject: [PATCH 06/55] prefill: the GDN recurrence per head, a lane pair per column, the output norm fused (same bits) One block per value head; each column's 128 state rows in the registers of two lanes of one wave (the 32-row group partials swapped within the wave and added in the old order); q/k/v/gate/beta staged in LDS 8 tokens at a time with the next chunk prefetched; the RMS norm + gate of gdn_out_norm_kernel fused per chunk. tests/hip/gdn_rec_head.cpp: y, y16 and the state bitwise equal to the column-split + norm kernels for T 1..2051; 2048 tokens 9.8 -> 6.7 ms on gfx1151 (at the 600-880 MHz the GPU's DPM runs this test at). STRATA_GDN_HEAD=0 keeps the old kernels. --- CMakeLists.txt | 5 + include/strata/prefill/kernels.hpp | 6 ++ src/prefill/kernels.cu | 167 ++++++++++++++++++++++++++++- tests/hip/gdn_rec_head.cpp | 116 ++++++++++++++++++++ 4 files changed, 291 insertions(+), 3 deletions(-) create mode 100644 tests/hip/gdn_rec_head.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 1ce54a60..c64cf4d1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -455,6 +455,11 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_test(NAME hip_prefill_native_batch COMMAND hip_prefill_native_batch) list(APPEND _strata_hip_tests hip_prefill_native_batch) endif() + # Aurora: the prompt GDN recurrence's per-head kernel against the column-split + norm kernels, bitwise + add_executable(hip_gdn_rec_head tests/hip/gdn_rec_head.cpp) + target_link_libraries(hip_gdn_rec_head PRIVATE strata_prefill strata_hip_runtime) + add_test(NAME hip_gdn_rec_head COMMAND hip_gdn_rec_head) + list(APPEND _strata_hip_tests hip_gdn_rec_head) # S6: the AMD fast router against the portable kernel, bitwise add_executable(hip_router_fast tests/hip/router_fast.cpp) target_link_libraries(hip_router_fast PRIVATE strata_kernels strata_hip_runtime) diff --git a/include/strata/prefill/kernels.hpp b/include/strata/prefill/kernels.hpp index 8f6145bf..16e24697 100644 --- a/include/strata/prefill/kernels.hpp +++ b/include/strata/prefill/kernels.hpp @@ -47,6 +47,12 @@ void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, i /// (FP32 and FP16 bits: the out projection is quantized). void gdn_recurrence(float* state, const float* h, const float* gate, const float* beta, const float* z, const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream); +/// The kernels behind gdn_recurrence, for the parity test: 0 = the column-split kernels + the norm kernel (or the +/// one-block-per-head kernel under STRATA_GDN_REC_HEADS), 1 = the per-head kernel with the norm fused, 2 = the +/// one-block-per-head kernel (its fused norm rounds differently). 0 and 1 give the same bits. +void gdn_recurrence_variant(int variant, float* state, const float* h, const float* gate, const float* beta, + const float* z, const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, + void* stream); // ---- MoE /// softmax over 512, top-10 (ties to the lower id), weights renormalised over the ten (the native router). diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index de833442..3f5d6ecd 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -433,6 +433,152 @@ __global__ void __launch_bounds__(CB * RG) gdn_rec_cols_pipe_kernel(float* __res #pragma unroll for (int r = 0; r < RPG; ++r) base[r * rs] = s[r]; } +// Aurora (S23): the recurrence with ONE block per value head, a lane pair per value column (the two halves of the +// column's 128 state rows in the two lanes' registers, lanes l and l + 16 of one wave), and the output norm fused in. +// The same arithmetic in the same order as gdn_rec_cols_pipe_kernel + gdn_out_norm_kernel - the kv / o partials of +// the four 32-row groups are kept apart and added as red[0] + red[1] + red[2] + red[3] (the two lanes swap theirs +// within the wave); the norm's warp sums run over the same 32-column warps - so the same bits +// (tests/hip/gdn_rec_head.cpp). What changes is the schedule: no __syncthreads per token, one pair every HT tokens +// (the chunk's q/k rows staged in LDS, the next chunk's loaded into registers while this one computes), instead of +// four per token. STRATA_GDN_HEAD=0: the old kernels. +constexpr int HT = 8; // tokens per staged chunk +constexpr int HTH = 2 * S; // threads per head block +constexpr int HRS = S + 8; // staged q/k row stride: [rows 0..63, 4 pad, rows 64..127, 4 pad] +constexpr int HPF = HT * 2 * S / 4 / HTH; // float4 of q/k each thread prefetches per chunk (4) +__device__ __forceinline__ int hrow(int r) { return r + (r >= S / 2 ? 4 : 0); } +__global__ void __launch_bounds__(HTH) gdn_rec_head_kernel(float* __restrict__ state, const float* __restrict__ h, + const float* __restrict__ gate, const float* __restrict__ beta, + const float* __restrict__ z, const float* __restrict__ gamma, + float eps, float* __restrict__ y, uint16_t* __restrict__ y16, + int64_t T) { + __shared__ __align__(16) float sqk[2][HT][2][HRS]; // [buffer][token][q | k][row (padded)] + __shared__ float sgb[2][2][HT]; // [buffer][gate | beta][token] + __shared__ float sv[2][HT][S]; // [buffer][token][column] v + __shared__ float soc[HT][S]; + __shared__ float swsum[HT][4]; + const int head = blockIdx.x, tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int col = wave * 16 + (lane & 15), half = lane >> 4, r0 = half * (S / 2); // this lane's rows r0 .. r0 + 63 + const int qh = head % HK; + float s[S / 2]; + { + const float* base = state + (size_t) head * S + col; +#pragma unroll + for (int r = 0; r < S / 2; ++r) s[r] = base[(size_t) (r0 + r) * HV * S]; + } + float4 pf[HPF]; + float pv[HT], pgb = 0.0f; + // chunk c's inputs into registers: q/k rows (float4 i of the chunk's [token][q|k][row] block), the column's v (the + // lower lane of the pair), and gate (threads 0..HT-1) / beta (HT..2HT-1) of token `tid % HT` + auto fetch = [&](int64_t c) { + const int64_t t0 = c * HT; +#pragma unroll + for (int u = 0; u < HPF; ++u) { + const int i = tid + u * HTH; + const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4); + const int64_t t = t0 + tt; + pf[u] = t < T ? *reinterpret_cast(h + t * C + part * HK * S + qh * S + r4 * 4) + : make_float4(0.f, 0.f, 0.f, 0.f); + } + if (half == 0) { +#pragma unroll + for (int tt = 0; tt < HT; ++tt) { + const int64_t t = t0 + tt; + pv[tt] = t < T ? h[t * C + 2 * HK * S + head * S + col] : 0.0f; + } + } + if (tid < 2 * HT) { + const int64_t t = t0 + (tid % HT); + pgb = t < T ? (tid < HT ? gate : beta)[t * HV + head] : 0.0f; + } + }; + const float rs_s = rsqrtf((float) S); + const int64_t nch = (T + HT - 1) / HT; + if (nch > 0) fetch(0); + for (int64_t c = 0; c < nch; ++c) { + const int b = (int) (c & 1); + if (half == 0) { +#pragma unroll + for (int tt = 0; tt < HT; ++tt) sv[b][tt][col] = pv[tt]; + } +#pragma unroll + for (int u = 0; u < HPF; ++u) { + const int i = tid + u * HTH; + const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4); + *reinterpret_cast(&sqk[b][tt][part][hrow(r4 * 4)]) = pf[u]; + } + if (tid < 2 * HT) sgb[b][tid / HT][tid % HT] = pgb; + __syncthreads(); // chunk c staged (buffer b was last read two chunks ago) + if (c + 1 < nch) fetch(c + 1); + const int64_t t0 = c * HT; + const int nt = (int) (T - t0 < HT ? T - t0 : HT); + for (int tt = 0; tt < nt; ++tt) { + const float* sq = &sqk[b][tt][0][hrow(r0)]; + const float* sk = &sqk[b][tt][1][hrow(r0)]; + const float g = __expf(sgb[b][0][tt]); + float kva, kvb; // this lane's two 32-row groups + { + float kv = 0.0f; +#pragma unroll + for (int r = 0; r < 32; ++r) kv = fmaf(s[r], sk[r], kv); + kva = kv; + kv = 0.0f; +#pragma unroll + for (int r = 32; r < 64; ++r) kv = fmaf(s[r], sk[r], kv); + kvb = kv; + } + asm volatile("" ::: "memory"); // re-read the k row below rather than hold it in VGPRs + // groups 0, 1 in the lower lane, 2, 3 in the upper: ((g0 + g1) + g2) + g3 in both + const float oa = __shfl_xor_sync(0xffffffffu, kva, 16), ob = __shfl_xor_sync(0xffffffffu, kvb, 16); + const float kv_col = half == 0 ? kva + kvb + oa + ob : oa + ob + kva + kvb; + const float cvt = sv[b][tt][col], cbt = sgb[b][1][tt]; + const float delta = (cvt - g * kv_col) * cbt; + float opa = 0.0f, opb = 0.0f; +#pragma unroll + for (int r = 0; r < 32; ++r) { + s[r] = fmaf(g, s[r], sk[r] * delta); + opa = fmaf(s[r], sq[r], opa); + } +#pragma unroll + for (int r = 32; r < 64; ++r) { + s[r] = fmaf(g, s[r], sk[r] * delta); + opb = fmaf(s[r], sq[r], opb); + } + const float pa = __shfl_xor_sync(0xffffffffu, opa, 16), pb = __shfl_xor_sync(0xffffffffu, opb, 16); + if (half == 0) soc[tt][col] = (opa + opb + pa + pb) * rs_s; + } + __syncthreads(); // the chunk's outputs + if (tid < S) { // the norm: thread = column, warps of 32 columns as before + const int nc = tid, nl = tid & 31, nw = tid >> 5; + for (int tt = 0; tt < nt; ++tt) { + const float sp = warp_sum(soc[tt][nc] * soc[tt][nc]); + if (nl == 0) swsum[tt][nw] = sp; + } + } + __syncthreads(); + if (tid < S) { + const int nc = tid; + const float g_col = gamma[nc]; + float cz[HT]; +#pragma unroll + for (int tt = 0; tt < HT; ++tt) cz[tt] = tt < nt ? z[(t0 + tt) * HV * S + head * S + nc] : 0.0f; +#pragma unroll + for (int tt = 0; tt < HT; ++tt) { + if (tt >= nt) break; + const float oc = soc[tt][nc]; + const float ss = swsum[tt][0] + swsum[tt][1] + swsum[tt][2] + swsum[tt][3]; + const float v = oc * rsqrtf(ss / (float) S + eps) * g_col * sigm(cz[tt]); + const size_t at = (size_t) (t0 + tt) * HV * S + (size_t) head * S + nc; + y[at] = v; + y16[at] = hf(v); + } + } + } + { + float* base = state + (size_t) head * S + col; +#pragma unroll + for (int r = 0; r < S / 2; ++r) base[(size_t) (r0 + r) * HV * S] = s[r]; + } +} __global__ void __launch_bounds__(S) gdn_out_norm_kernel(const float* __restrict__ z, const float* __restrict__ gamma, float eps, float* __restrict__ y, uint16_t* __restrict__ y16) { __shared__ float wsum[4]; @@ -741,10 +887,17 @@ void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, i gdn_l2_kernel<<>>(h, eps); check("gdn_conv"); } -void gdn_recurrence(float* state, const float* h, const float* gate, const float* beta, const float* z, - const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream) { +void gdn_recurrence_variant(int variant, float* state, const float* h, const float* gate, const float* beta, + const float* z, const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, + void* stream) { + if (variant == 1) { + if (T > 0) + gdn_rec_head_kernel<<>>(state, h, gate, beta, z, gamma, eps, y, y16, T); + check("gdn_recurrence (head)"); + return; + } static const bool serial = std::getenv("STRATA_GDN_REC_HEADS") != nullptr; // the one-block-per-head kernel (A/B) - if (serial || T <= 0) { + if (serial || T <= 0 || variant == 2) { gdn_rec_kernel<<>>(state, h, gate, beta, z, gamma, eps, y, y16, T); } else { static const bool pipe = [] { const char* v = std::getenv("STRATA_GDN_PIPELINE"); return v == nullptr || std::atoi(v) != 0; }(); @@ -756,6 +909,14 @@ void gdn_recurrence(float* state, const float* h, const float* gate, const float } check("gdn_recurrence"); } +void gdn_recurrence(float* state, const float* h, const float* gate, const float* beta, const float* z, + const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream) { + // Aurora (S23): the per-head kernel with the norm fused, the same bits (tests/hip/gdn_rec_head.cpp); + // STRATA_GDN_HEAD=0 (or STRATA_GDN_REC_HEADS) keeps the earlier kernels + static const bool head = [] { const char* v = std::getenv("STRATA_GDN_HEAD"); return v == nullptr || std::atoi(v) != 0; }(); + static const bool serial = std::getenv("STRATA_GDN_REC_HEADS") != nullptr; + gdn_recurrence_variant(head && !serial ? 1 : 0, state, h, gate, beta, z, gamma, eps, y, y16, T, stream); +} void route(const float* logits, int32_t* ids, float* weights, int64_t T, int64_t n_expert, void* stream) { if (n_expert == 512) route_kernel<16><<<(unsigned) ((T + 7) / 8), 256, 0, (cudaStream_t) stream>>>(logits, ids, weights, T); diff --git a/tests/hip/gdn_rec_head.cpp b/tests/hip/gdn_rec_head.cpp new file mode 100644 index 00000000..7e19e6fd --- /dev/null +++ b/tests/hip/gdn_rec_head.cpp @@ -0,0 +1,116 @@ +// tests/hip/gdn_rec_head.cpp - the prompt GDN recurrence's per-head kernel (gdn_recurrence_variant 1, the norm fused) +// against the column-split kernels + the norm kernel (variant 0, the default before it): +// y, its FP16 bits and the final state must be BITWISE equal, over chunk lengths around the 8-token staging and a +// long one, from a nonzero state. Synthetic inputs in the model's ranges (unit q/k rows, log-decay gates < 0). +#include "strata/prefill/kernels.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +namespace { +constexpr int S = 128, HK = 16, HV = 48, C = 10240; +void ck(cudaError_t e, const char* w) { + if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); } +} +template T* dev(const std::vector& h) { + T* d = nullptr; + ck(cudaMalloc(&d, h.size() * sizeof(T)), "malloc"); + ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload"); + return d; +} +template std::vector host(const T* d, size_t n) { + std::vector h(n); + ck(cudaMemcpy(h.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost), "download"); + return h; +} +} // namespace + +int main() { + std::mt19937 rng(11); + std::normal_distribution nd(0.f, 1.f); + std::uniform_real_distribution ud(0.f, 1.f); + int failures = 0; + const int64_t lens[] = {1, 7, 8, 9, 17, 100, 2048, 2051}; + for (const int64_t T : lens) { + std::vector h((size_t) T * C), gate((size_t) T * HV), beta((size_t) T * HV), z((size_t) T * HV * S), + gamma(S), state((size_t) S * HV * S); + for (int64_t t = 0; t < T; ++t) { + float* ht = h.data() + t * C; + for (int i = 0; i < C; ++i) ht[i] = nd(rng); + for (int hh = 0; hh < 2 * HK; ++hh) { // q and k heads: unit rows, as after gdn_conv's L2 norm + double ss = 0; + for (int d = 0; d < S; ++d) ss += (double) ht[hh * S + d] * ht[hh * S + d]; + for (int d = 0; d < S; ++d) ht[hh * S + d] = (float) (ht[hh * S + d] / std::sqrt(ss + 1e-6)); + } + } + for (auto& x : gate) x = -2.0f * ud(rng); + for (auto& x : beta) x = ud(rng); + for (auto& x : z) x = nd(rng); + for (auto& x : gamma) x = 0.5f + ud(rng); + for (auto& x : state) x = 0.1f * nd(rng); + const float* dh = dev(h); + const float* dg = dev(gate); + const float* db = dev(beta); + const float* dz = dev(z); + const float* dgm = dev(gamma); + std::vector y_ref, st_ref; + std::vector y16_ref; + for (int variant : {0, 1}) { + float* dst = dev(state); + float* dy = nullptr; + uint16_t* dy16 = nullptr; + ck(cudaMalloc(&dy, (size_t) T * HV * S * 4), "malloc"); + ck(cudaMalloc(&dy16, (size_t) T * HV * S * 2), "malloc"); + strata::prefill::gdn_recurrence_variant(variant, dst, dh, dg, db, dz, dgm, 1e-6f, dy, dy16, T, nullptr); + ck(cudaDeviceSynchronize(), "run"); + auto y = host(dy, (size_t) T * HV * S); + auto y16 = host(dy16, (size_t) T * HV * S); + auto st = host(dst, state.size()); + if (variant == 0) { + y_ref = y; y16_ref = y16; st_ref = st; + } else { + size_t dy_n = 0, d16 = 0, dsn = 0; + for (size_t i = 0; i < y.size(); ++i) dy_n += std::memcmp(&y[i], &y_ref[i], 4) != 0; + for (size_t i = 0; i < y16.size(); ++i) d16 += y16[i] != y16_ref[i]; + for (size_t i = 0; i < st.size(); ++i) dsn += std::memcmp(&st[i], &st_ref[i], 4) != 0; + const bool ok = dy_n == 0 && d16 == 0 && dsn == 0; + failures += !ok; + std::printf("%s T %lld variant %d vs 0: y %zu, y16 %zu, state %zu values differ\n", ok ? "PASS" : "FAIL", + (long long) T, variant, dy_n, d16, dsn); + } + cudaFree(dst); cudaFree(dy); cudaFree(dy16); + } + // timing at the long lengths: variant 0 vs 1 + if (T >= 2048) { + float* dst = dev(state); + float* dy = nullptr; + uint16_t* dy16 = nullptr; + ck(cudaMalloc(&dy, (size_t) T * HV * S * 4), "malloc"); + ck(cudaMalloc(&dy16, (size_t) T * HV * S * 2), "malloc"); + for (int variant : {0, 1}) { + cudaEvent_t a, b; + cudaEventCreate(&a); cudaEventCreate(&b); + strata::prefill::gdn_recurrence_variant(variant, dst, dh, dg, db, dz, dgm, 1e-6f, dy, dy16, T, nullptr); + cudaEventRecord(a); + for (int r = 0; r < 3; ++r) + strata::prefill::gdn_recurrence_variant(variant, dst, dh, dg, db, dz, dgm, 1e-6f, dy, dy16, T, nullptr); + cudaEventRecord(b); + ck(cudaEventSynchronize(b), "time"); + float ms = 0; + cudaEventElapsedTime(&ms, a, b); + std::printf(" T %lld variant %d: %.3f ms per call (%.2f us per token)\n", (long long) T, variant, ms / 3, + ms / 3 * 1000 / (double) T); + } + cudaFree(dst); cudaFree(dy); cudaFree(dy16); + } + cudaFree((void*) dh); cudaFree((void*) dg); cudaFree((void*) db); cudaFree((void*) dz); cudaFree((void*) dgm); + } + std::printf("FAILURES: %d\n", failures); + return failures ? 1 : 0; +} From a138f630674f581f0c0e5145bc15900b4c623d9b Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 2 Oct 2026 20:30:36 +0200 Subject: [PATCH 07/55] prefill: the GDN recurrence with four lanes per column (no barrier per token) + a grid-stride norm Replaces the per-head kernel of the previous commit (VGPR-bound, spilled). Same column-split grid as gdn_rec_cols_pipe_kernel (4 x 32-column blocks per head), but lane g of a column's four holds exactly the old thread's row group g; kv / o partials meet through wave shuffles and are added in the old order, so no __syncthreads per token; q/k/v/gate/beta staged 4 tokens at a time (~10 KB LDS: all 192 blocks resident). The output norm runs the old kernel's body over a grid-stride walk (T x 48 blocks of 128 threads before). tests/hip/gdn_rec_head.cpp: y, y16 and state bitwise equal to the old kernels for T 1..2051 (variant 3 = new recurrence + old norm, a diagnostic); 2048 tokens 9.8 -> 4.1 ms on gfx1151 at the test's 600-880 MHz. --- include/strata/prefill/kernels.hpp | 2 +- src/prefill/kernels.cu | 197 +++++++++++++++-------------- tests/hip/gdn_rec_head.cpp | 4 +- 3 files changed, 103 insertions(+), 100 deletions(-) diff --git a/include/strata/prefill/kernels.hpp b/include/strata/prefill/kernels.hpp index 16e24697..e10d8ba1 100644 --- a/include/strata/prefill/kernels.hpp +++ b/include/strata/prefill/kernels.hpp @@ -48,7 +48,7 @@ void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, i void gdn_recurrence(float* state, const float* h, const float* gate, const float* beta, const float* z, const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream); /// The kernels behind gdn_recurrence, for the parity test: 0 = the column-split kernels + the norm kernel (or the -/// one-block-per-head kernel under STRATA_GDN_REC_HEADS), 1 = the per-head kernel with the norm fused, 2 = the +/// one-block-per-head kernel under STRATA_GDN_REC_HEADS), 1 = four lanes per column (no barrier per token) + the grid-stride norm, 2 = the /// one-block-per-head kernel (its fused norm rounds differently). 0 and 1 give the same bits. void gdn_recurrence_variant(int variant, float* state, const float* h, const float* gate, const float* beta, const float* z, const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 3f5d6ecd..6f1ec519 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -6,6 +6,7 @@ #include #include +#include #include #include #include @@ -433,53 +434,52 @@ __global__ void __launch_bounds__(CB * RG) gdn_rec_cols_pipe_kernel(float* __res #pragma unroll for (int r = 0; r < RPG; ++r) base[r * rs] = s[r]; } -// Aurora (S23): the recurrence with ONE block per value head, a lane pair per value column (the two halves of the -// column's 128 state rows in the two lanes' registers, lanes l and l + 16 of one wave), and the output norm fused in. -// The same arithmetic in the same order as gdn_rec_cols_pipe_kernel + gdn_out_norm_kernel - the kv / o partials of -// the four 32-row groups are kept apart and added as red[0] + red[1] + red[2] + red[3] (the two lanes swap theirs -// within the wave); the norm's warp sums run over the same 32-column warps - so the same bits -// (tests/hip/gdn_rec_head.cpp). What changes is the schedule: no __syncthreads per token, one pair every HT tokens -// (the chunk's q/k rows staged in LDS, the next chunk's loaded into registers while this one computes), instead of -// four per token. STRATA_GDN_HEAD=0: the old kernels. -constexpr int HT = 8; // tokens per staged chunk -constexpr int HTH = 2 * S; // threads per head block -constexpr int HRS = S + 8; // staged q/k row stride: [rows 0..63, 4 pad, rows 64..127, 4 pad] -constexpr int HPF = HT * 2 * S / 4 / HTH; // float4 of q/k each thread prefetches per chunk (4) -__device__ __forceinline__ int hrow(int r) { return r + (r >= S / 2 ? 4 : 0); } -__global__ void __launch_bounds__(HTH) gdn_rec_head_kernel(float* __restrict__ state, const float* __restrict__ h, +// Aurora (S23): the recurrence with the column-split grid of gdn_rec_cols_pipe_kernel (four 32-column blocks per value +// head) but FOUR LANES per column, lane g holding the column's state rows 32g .. 32g + 31 in registers - exactly the +// row group the old kernel's thread (col, rg = g) held - so a token needs no __syncthreads: the four kv / o partials +// meet through wave shuffles and are added in the old order red[0] + red[1] + red[2] + red[3] (the same bits; +// tests/hip/gdn_rec_head.cpp). The q/k rows, v, gate and beta are staged in LDS HT tokens at a time, the next chunk +// loaded into registers while this one computes, and a token's k and q rows are read into registers before its +// products (one LDS latency per token, not one per load). The old kernels took ~4 barriers per token and ~3.5 us +// per token and layer on the Radeon 8060S; the output norm runs after it in gdn_out_norm_warp_kernel. +// STRATA_GDN_HEAD=0: the old kernels. +constexpr int HT = 4; // tokens per staged chunk (LDS ~10 KB: all 192 blocks resident) +constexpr int QCB = 32; // columns per block +constexpr int QTH = QCB * 4; // threads per block: 4 lanes per column +constexpr int QRS = 36; // staged row-group stride (32 rows + 4 pad: the 4 groups' reads + // land in different LDS banks) +constexpr int QPF = HT * 2 * S / 4 / QTH; // float4 of q/k each thread prefetches per chunk (2) +__global__ void __launch_bounds__(QTH) gdn_rec_quad_kernel(float* __restrict__ state, const float* __restrict__ h, const float* __restrict__ gate, const float* __restrict__ beta, - const float* __restrict__ z, const float* __restrict__ gamma, - float eps, float* __restrict__ y, uint16_t* __restrict__ y16, - int64_t T) { - __shared__ __align__(16) float sqk[2][HT][2][HRS]; // [buffer][token][q | k][row (padded)] - __shared__ float sgb[2][2][HT]; // [buffer][gate | beta][token] - __shared__ float sv[2][HT][S]; // [buffer][token][column] v - __shared__ float soc[HT][S]; - __shared__ float swsum[HT][4]; - const int head = blockIdx.x, tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; - const int col = wave * 16 + (lane & 15), half = lane >> 4, r0 = half * (S / 2); // this lane's rows r0 .. r0 + 63 + float* __restrict__ oc_out, int64_t T) { + __shared__ __align__(16) float sqk[2][HT][2][4 * QRS]; // [buffer][token][q | k][group][row (padded)] + __shared__ float sgb[2][2][HT]; // [buffer][gate | beta][token] + __shared__ float sv[2][HT][QCB]; // [buffer][token][column] v + const int head = blockIdx.x / (S / QCB), cb = blockIdx.x % (S / QCB); + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int g = lane >> 3, cl = wave * 8 + (lane & 7), col = cb * QCB + cl; // row group, column in block / head const int qh = head % HK; - float s[S / 2]; + float s[32]; { - const float* base = state + (size_t) head * S + col; + const float* base = state + ((size_t) (g * 32) * HV + head) * S + col; #pragma unroll - for (int r = 0; r < S / 2; ++r) s[r] = base[(size_t) (r0 + r) * HV * S]; + for (int r = 0; r < 32; ++r) s[r] = base[(size_t) r * HV * S]; } - float4 pf[HPF]; + float4 pf[QPF]; float pv[HT], pgb = 0.0f; - // chunk c's inputs into registers: q/k rows (float4 i of the chunk's [token][q|k][row] block), the column's v (the - // lower lane of the pair), and gate (threads 0..HT-1) / beta (HT..2HT-1) of token `tid % HT` + // chunk c's inputs into registers: q/k (float4 i of the chunk's [token][q|k][S/4] block), the column's v (lanes of + // group 0) and gate (threads 0..HT-1) / beta (HT..2HT-1) of token `tid % HT` auto fetch = [&](int64_t c) { const int64_t t0 = c * HT; #pragma unroll - for (int u = 0; u < HPF; ++u) { - const int i = tid + u * HTH; + for (int u = 0; u < QPF; ++u) { + const int i = tid + u * QTH; const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4); const int64_t t = t0 + tt; pf[u] = t < T ? *reinterpret_cast(h + t * C + part * HK * S + qh * S + r4 * 4) : make_float4(0.f, 0.f, 0.f, 0.f); } - if (half == 0) { + if (g == 0) { #pragma unroll for (int tt = 0; tt < HT; ++tt) { const int64_t t = t0 + tt; @@ -492,19 +492,21 @@ __global__ void __launch_bounds__(HTH) gdn_rec_head_kernel(float* __restrict__ s } }; const float rs_s = rsqrtf((float) S); + const int src0 = lane & 7; // lane of group 0 for this column; group j is src0 + 8 j const int64_t nch = (T + HT - 1) / HT; if (nch > 0) fetch(0); for (int64_t c = 0; c < nch; ++c) { const int b = (int) (c & 1); - if (half == 0) { + if (g == 0) { #pragma unroll - for (int tt = 0; tt < HT; ++tt) sv[b][tt][col] = pv[tt]; + for (int tt = 0; tt < HT; ++tt) sv[b][tt][cl] = pv[tt]; } #pragma unroll - for (int u = 0; u < HPF; ++u) { - const int i = tid + u * HTH; + for (int u = 0; u < QPF; ++u) { + const int i = tid + u * QTH; const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4); - *reinterpret_cast(&sqk[b][tt][part][hrow(r4 * 4)]) = pf[u]; + const int row = r4 * 4; + *reinterpret_cast(&sqk[b][tt][part][(row >> 5) * QRS + (row & 31)]) = pf[u]; } if (tid < 2 * HT) sgb[b][tid / HT][tid % HT] = pgb; __syncthreads(); // chunk c staged (buffer b was last read two chunks ago) @@ -512,71 +514,62 @@ __global__ void __launch_bounds__(HTH) gdn_rec_head_kernel(float* __restrict__ s const int64_t t0 = c * HT; const int nt = (int) (T - t0 < HT ? T - t0 : HT); for (int tt = 0; tt < nt; ++tt) { - const float* sq = &sqk[b][tt][0][hrow(r0)]; - const float* sk = &sqk[b][tt][1][hrow(r0)]; - const float g = __expf(sgb[b][0][tt]); - float kva, kvb; // this lane's two 32-row groups + float k[32], q[32]; { - float kv = 0.0f; + const float4* k4 = reinterpret_cast(&sqk[b][tt][1][g * QRS]); + const float4* q4 = reinterpret_cast(&sqk[b][tt][0][g * QRS]); #pragma unroll - for (int r = 0; r < 32; ++r) kv = fmaf(s[r], sk[r], kv); - kva = kv; - kv = 0.0f; -#pragma unroll - for (int r = 32; r < 64; ++r) kv = fmaf(s[r], sk[r], kv); - kvb = kv; + for (int j = 0; j < 8; ++j) { + const float4 kk = k4[j], qq = q4[j]; + k[4 * j] = kk.x; k[4 * j + 1] = kk.y; k[4 * j + 2] = kk.z; k[4 * j + 3] = kk.w; + q[4 * j] = qq.x; q[4 * j + 1] = qq.y; q[4 * j + 2] = qq.z; q[4 * j + 3] = qq.w; + } } - asm volatile("" ::: "memory"); // re-read the k row below rather than hold it in VGPRs - // groups 0, 1 in the lower lane, 2, 3 in the upper: ((g0 + g1) + g2) + g3 in both - const float oa = __shfl_xor_sync(0xffffffffu, kva, 16), ob = __shfl_xor_sync(0xffffffffu, kvb, 16); - const float kv_col = half == 0 ? kva + kvb + oa + ob : oa + ob + kva + kvb; - const float cvt = sv[b][tt][col], cbt = sgb[b][1][tt]; - const float delta = (cvt - g * kv_col) * cbt; - float opa = 0.0f, opb = 0.0f; + const float g_exp = __expf(sgb[b][0][tt]); + float kv = 0.0f; +#pragma unroll + for (int r = 0; r < 32; ++r) kv = fmaf(s[r], k[r], kv); + const float p0 = __shfl_sync(0xffffffffu, kv, src0), p1 = __shfl_sync(0xffffffffu, kv, src0 + 8), + p2 = __shfl_sync(0xffffffffu, kv, src0 + 16), p3 = __shfl_sync(0xffffffffu, kv, src0 + 24); + const float kv_col = p0 + p1 + p2 + p3; + const float cvt = sv[b][tt][cl], cbt = sgb[b][1][tt]; + const float delta = (cvt - g_exp * kv_col) * cbt; + float o = 0.0f; #pragma unroll for (int r = 0; r < 32; ++r) { - s[r] = fmaf(g, s[r], sk[r] * delta); - opa = fmaf(s[r], sq[r], opa); - } -#pragma unroll - for (int r = 32; r < 64; ++r) { - s[r] = fmaf(g, s[r], sk[r] * delta); - opb = fmaf(s[r], sq[r], opb); - } - const float pa = __shfl_xor_sync(0xffffffffu, opa, 16), pb = __shfl_xor_sync(0xffffffffu, opb, 16); - if (half == 0) soc[tt][col] = (opa + opb + pa + pb) * rs_s; - } - __syncthreads(); // the chunk's outputs - if (tid < S) { // the norm: thread = column, warps of 32 columns as before - const int nc = tid, nl = tid & 31, nw = tid >> 5; - for (int tt = 0; tt < nt; ++tt) { - const float sp = warp_sum(soc[tt][nc] * soc[tt][nc]); - if (nl == 0) swsum[tt][nw] = sp; - } - } - __syncthreads(); - if (tid < S) { - const int nc = tid; - const float g_col = gamma[nc]; - float cz[HT]; -#pragma unroll - for (int tt = 0; tt < HT; ++tt) cz[tt] = tt < nt ? z[(t0 + tt) * HV * S + head * S + nc] : 0.0f; -#pragma unroll - for (int tt = 0; tt < HT; ++tt) { - if (tt >= nt) break; - const float oc = soc[tt][nc]; - const float ss = swsum[tt][0] + swsum[tt][1] + swsum[tt][2] + swsum[tt][3]; - const float v = oc * rsqrtf(ss / (float) S + eps) * g_col * sigm(cz[tt]); - const size_t at = (size_t) (t0 + tt) * HV * S + (size_t) head * S + nc; - y[at] = v; - y16[at] = hf(v); + s[r] = fmaf(g_exp, s[r], k[r] * delta); + o = fmaf(s[r], q[r], o); } + const float o0 = __shfl_sync(0xffffffffu, o, src0), o1 = __shfl_sync(0xffffffffu, o, src0 + 8), + o2 = __shfl_sync(0xffffffffu, o, src0 + 16), o3 = __shfl_sync(0xffffffffu, o, src0 + 24); + if (g == 0) oc_out[(t0 + tt) * HV * S + head * S + col] = (o0 + o1 + o2 + o3) * rs_s; } } { - float* base = state + (size_t) head * S + col; + float* base = state + ((size_t) (g * 32) * HV + head) * S + col; #pragma unroll - for (int r = 0; r < S / 2; ++r) base[(size_t) (r0 + r) * HV * S] = s[r]; + for (int r = 0; r < 32; ++r) base[(size_t) r * HV * S] = s[r]; + } +} +// gdn_out_norm_kernel's body over a grid-stride walk of the (token, head) rows: the old kernel launched a 128-thread +// block per row (T * 48 blocks; ~45 GB/s on the 8060S). The same code per row (the same compiled arithmetic: a wave +// per row with four values per lane rounded differently in its first xor step). +__global__ void __launch_bounds__(S) gdn_out_norm_loop_kernel(const float* __restrict__ z, const float* __restrict__ gamma, + float eps, float* __restrict__ y, uint16_t* __restrict__ y16, + int64_t rows) { + __shared__ float wsum[4]; + const int col = threadIdx.x; + for (int64_t row = blockIdx.x; row < rows; row += gridDim.x) { + const size_t at = (size_t) row * S + col; + const float oc = y[at]; + float sp = warp_sum(oc * oc); + __syncthreads(); // the previous row's sums are read + if ((col & 31) == 0) wsum[col >> 5] = sp; + __syncthreads(); + const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3]; + const float v = oc * rsqrtf(ss / (float) S + eps) * gamma[col] * sigm(z[at]); + y[at] = v; + y16[at] = hf(v); } } __global__ void __launch_bounds__(S) gdn_out_norm_kernel(const float* __restrict__ z, const float* __restrict__ gamma, @@ -890,10 +883,20 @@ void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, i void gdn_recurrence_variant(int variant, float* state, const float* h, const float* gate, const float* beta, const float* z, const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream) { + if (variant == 3) { // diagnostics: the quad recurrence + the old norm kernel + if (T > 0) { + gdn_rec_quad_kernel<<>>(state, h, gate, beta, y, T); + gdn_out_norm_kernel<<>>(z, gamma, eps, y, y16); + } + return; + } if (variant == 1) { - if (T > 0) - gdn_rec_head_kernel<<>>(state, h, gate, beta, z, gamma, eps, y, y16, T); - check("gdn_recurrence (head)"); + if (T > 0) { + gdn_rec_quad_kernel<<>>(state, h, gate, beta, y, T); + gdn_out_norm_loop_kernel<<<(unsigned) std::min(T * HV, 4096), S, 0, (cudaStream_t) stream>>>( + z, gamma, eps, y, y16, T * HV); + } + check("gdn_recurrence (quad)"); return; } static const bool serial = std::getenv("STRATA_GDN_REC_HEADS") != nullptr; // the one-block-per-head kernel (A/B) @@ -911,7 +914,7 @@ void gdn_recurrence_variant(int variant, float* state, const float* h, const flo } void gdn_recurrence(float* state, const float* h, const float* gate, const float* beta, const float* z, const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream) { - // Aurora (S23): the per-head kernel with the norm fused, the same bits (tests/hip/gdn_rec_head.cpp); + // Aurora (S23): four lanes per column + the grid-stride norm, the same bits (tests/hip/gdn_rec_head.cpp); // STRATA_GDN_HEAD=0 (or STRATA_GDN_REC_HEADS) keeps the earlier kernels static const bool head = [] { const char* v = std::getenv("STRATA_GDN_HEAD"); return v == nullptr || std::atoi(v) != 0; }(); static const bool serial = std::getenv("STRATA_GDN_REC_HEADS") != nullptr; diff --git a/tests/hip/gdn_rec_head.cpp b/tests/hip/gdn_rec_head.cpp index 7e19e6fd..80ed5fe2 100644 --- a/tests/hip/gdn_rec_head.cpp +++ b/tests/hip/gdn_rec_head.cpp @@ -1,4 +1,4 @@ -// tests/hip/gdn_rec_head.cpp - the prompt GDN recurrence's per-head kernel (gdn_recurrence_variant 1, the norm fused) +// tests/hip/gdn_rec_head.cpp - the prompt GDN recurrence's four-lanes-per-column kernel + norm (gdn_recurrence_variant 1) // against the column-split kernels + the norm kernel (variant 0, the default before it): // y, its FP16 bits and the final state must be BITWISE equal, over chunk lengths around the 8-token staging and a // long one, from a nonzero state. Synthetic inputs in the model's ranges (unit q/k rows, log-decay gates < 0). @@ -61,7 +61,7 @@ int main() { const float* dgm = dev(gamma); std::vector y_ref, st_ref; std::vector y16_ref; - for (int variant : {0, 1}) { + for (int variant : {0, 3, 1}) { float* dst = dev(state); float* dy = nullptr; uint16_t* dy16 = nullptr; From 5b8c84e7dadc326ff063554babfb033c76077cc7 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 2 Oct 2026 20:46:04 +0200 Subject: [PATCH 08/55] HIP: the fused Q2_0 prompt experts on gfx11 matrix cores (opt-in STRATA_PF_FUSED=1) expert_w11_kernel: moe_fused.cu's design (GPU grouping, experts read in place, gate/up + SwiGLU + int8 H, then down) on v_wmma_i32_16x16x16_iu8. A work item = 128 weight rows x a 64-row tile, 8 waves of 2x2 16x16 tiles; operands straight from global one block ahead, weight scales in LDS. The activations take gfx11's K order (act_pos); per 32-value half the integer dot is exact and the epilogue is the CUDA kernel's. hip_prefill_fused_moe (tests/cuda/prefill_fused_moe_test.cpp) on gfx1151: vs FP32 reference rel RMS 1.070e-2 (= MMQ's), vs MMQ 3.0e-5; one 2048-token layer 23.2 ms (MMQ path) -> 11.3 ms. The native packs' fused kernels stay CUDA-only (stubs on HIP). --- CMakeLists.txt | 14 ++- src/prefill/moe_fused.cu | 254 ++++++++++++++++++++++++++++++++++++++- src/prefill/prefill.cpp | 8 ++ 3 files changed, 273 insertions(+), 3 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index c64cf4d1..27a3b6b0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -949,14 +949,19 @@ if(STRATA_NATIVE_EXPERTS) if(NOT EXISTS "${_strata_mmq}/common.cuh" OR NOT EXISTS "${_strata_mmq}/quantize.cu") message(FATAL_ERROR "The selected GGML source is missing the ggml-cuda MMQ sources: ${_strata_mmq}") endif() + # Aurora: moe_fused.cu's gfx11 WMMA kernels for the Q2_0 pack's prompt experts (opt-in STRATA_PF_FUSED=1); the + # native packs' fused kernels (moe_fused_iq.cu) stay CUDA-only set(_strata_mmq_sources src/prefill/moe_mmq.cu + src/prefill/moe_fused.cu src/prefill/ggml_cuda_host.cu "${_strata_mmq}/quantize.cu") foreach(_t IN LISTS _strata_mmq_types) list(APPEND _strata_mmq_sources "${_strata_mmq}/template-instances/mmq-instance-${_t}.cu") endforeach() set_source_files_properties(${_strata_mmq_sources} PROPERTIES LANGUAGE HIP) + # moe_fused.cu is Strata's own CUDA-shaped source: it takes the HIP compat headers, ggml's MMQ sources do not + set_source_files_properties(src/prefill/moe_fused.cu PROPERTIES INCLUDE_DIRECTORIES "${STRATA_HIP_COMPAT_INCLUDE_DIR}") add_library(strata_mmq STATIC ${_strata_mmq_sources}) target_include_directories(strata_mmq PRIVATE "${_strata_gg}/include" "${_strata_gg}/src" "${_strata_mmq}" @@ -967,7 +972,14 @@ if(STRATA_NATIVE_EXPERTS) endif() target_link_libraries(strata_mmq PUBLIC ggml-base hip::host roc::hipblas) target_link_libraries(strata_prefill PUBLIC strata_mmq) - target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_MMQ=1) + target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_MMQ=1 STRATA_PREFILL_FUSED=1 STRATA_PREFILL_FUSED_HIP=1) + # Aurora: the gfx11 fused experts against the FP64 reference and MMQ (tests/cuda's test; exit 77 off gfx11) + add_executable(hip_prefill_fused_moe tests/cuda/prefill_fused_moe_test.cpp) + target_include_directories(hip_prefill_fused_moe PRIVATE "${_strata_gg}/include") + target_link_libraries(hip_prefill_fused_moe PRIVATE strata_mmq ggml-base strata_hip_runtime) + add_test(NAME hip_prefill_fused_moe COMMAND hip_prefill_fused_moe) + set_tests_properties(hip_prefill_fused_moe PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300) + list(APPEND _strata_hip_tests hip_prefill_fused_moe) # Numerical diagnostic: synthetic layouts by default, optional first-expert IQ3_XXS/IQ4_NL check with a pack. add_executable(hip_prefill_mmq_parity tests/hip/prefill_mmq_parity.cpp) diff --git a/src/prefill/moe_fused.cu b/src/prefill/moe_fused.cu index b5f9a1c8..6b9a68cb 100644 --- a/src/prefill/moe_fused.cu +++ b/src/prefill/moe_fused.cu @@ -25,6 +25,7 @@ #include #include #include +#include #include namespace strata::prefill::fused { @@ -55,6 +56,15 @@ constexpr size_t smem_bytes(bool gu) { // the stored position of value k of a 32-value half-block (see "The K order") __host__ __device__ __forceinline__ int perm32(int k) { return 8 * (k & 3) + 4 * (k >> 4) + ((k & 15) >> 2); } +// where value k of a 32-value half-block is stored: perm32 for the CUDA kernel; on HIP the gfx11 WMMA kernel's order +// (value 4b + t of a 16-value word at 4t + b: see expert_w11_kernel) +__host__ __device__ __forceinline__ int act_pos(int k) { +#if defined(__HIPCC__) + return (k & 16) | ((k & 3) << 2) | ((k >> 2) & 3); +#else + return perm32(k); +#endif +} struct Tables { int32_t *cnt, *off, *fill, *ts; // per expert: rows, first row (E + 1), placement cursor, first tile (E + 1) @@ -88,8 +98,8 @@ __global__ void quant_act_kernel(const float* __restrict__ x, int64_t nblk, uint s1 += __shfl_xor_sync(0xffffffffu, s1, o); } uint8_t* out = xa + w * AB; - out[perm32(lane)] = (uint8_t) (int8_t) q0; - out[32 + perm32(lane)] = (uint8_t) (int8_t) q1; + out[act_pos(lane)] = (uint8_t) (int8_t) q0; + out[32 + act_pos(lane)] = (uint8_t) (int8_t) q1; if (lane == 0) *(float4*) (out + 64) = make_float4(a0 / 127.0f, -(MAGICF + (float) s0), a1 / 127.0f, -(MAGICF + (float) s1)); } @@ -348,6 +358,216 @@ expert_kernel(const Batch b, const Tables tb, const uint8_t* __restrict__ act, c #endif } +#if defined(__HIPCC__) +// ---- Aurora (S23): the same products on gfx11 (RDNA3 / RDNA3.5) matrix cores, v_wmma_i32_16x16x16_iu8 (wave32). +// Fragments (gfx11): A lane l holds the 16 k of row l % 16 (lanes 16..31 repeat lanes 0..15), B lane l the 16 k of +// column l % 16, C/D lane l holds D[2i + l / 16][l % 16], i = 0..7. A = 16 weight rows, B = 16 tile rows (tokens): +// a lane's eight results are eight weight rows of ONE tile row, whose activation scales it already holds. +// The K order of a 16-weight word (one k-step): A register t = (word >> 2t) & 0x03030303 holds weights t, t+4, t+8, +// t+12, so k index p = 4t + b stands for weight 4b + t; the activations are stored in that order (act_pos). The +// integer dot of each 32-value half (two k-steps) is exact and the epilogue is the CUDA kernel's, so the numbers are +// those of expert_kernel (another K order inside exact integer sums). +// No LDS staging: a wave reads its weight rows (16 B per row and 64-weight block) and its tile rows' activation +// blocks (80 B) straight from global memory (L2: an expert's rows are read by every tile, a token's by every weight +// block), one block ahead in registers; the work item's weight scales go to LDS once. +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__) +#define STRATA_FUSED_W11 1 +#else +#define STRATA_FUSED_W11 0 +#endif +typedef int w11_i4 __attribute__((ext_vector_type(4))); +typedef int w11_i8 __attribute__((ext_vector_type(8))); +constexpr int W_ROWS = 128; // weight rows per work item (GU: 64 features = one H block) +constexpr int W_THREADS = 256; // 8 waves: 4 along the weight rows (32 each) x 2 along the tile (32) + +__device__ __forceinline__ w11_i8 wmma_iu8(w11_i4 a, w11_i4 b, w11_i8 c) { +#if STRATA_FUSED_W11 + return __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32(false, a, true, b, c, false); +#else + __builtin_trap(); + return c; +#endif +} + +template +__global__ void __launch_bounds__(W_THREADS) +expert_w11_kernel(const Batch b, const Tables tb, const uint8_t* __restrict__ act, const int32_t* __restrict__ src, + uint8_t* __restrict__ out, float* __restrict__ dm) { +#if STRATA_FUSED_W11 + constexpr int NKB = GU ? 40 : 10; // 64-weight blocks along K + constexpr int NFB = (GU ? 1280 : 2560) / W_ROWS; // work items per tile + constexpr int CODE_LD = GU ? 640 : 160; // code bytes per weight row + constexpr size_t O_CODES = GU ? O_GU_CODES : O_D_CODES, O_SC = GU ? O_GU_SC : O_D_SC; + constexpr int ACT_LD = NKB * AB; // bytes per activation row + constexpr unsigned M2 = 0x03030303u; + __shared__ __align__(16) uint16_t wsc[W_ROWS * NKB]; // the item's weight scales (fp16), [row][kb] + __shared__ int srow[kTileRows]; + __shared__ float hs[GU ? kTileRows : 1][GU ? 65 : 1]; // GU: H of the item's 64 features, [tile row][feature] + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int wm = wave & 3, wn = wave >> 2, l16 = lane & 15, hi = lane >> 4; + const int t0 = tb.ts[b.e0], nwork = (tb.ts[b.e1] - t0) * NFB; + for (int w = blockIdx.x; w < nwork; w += gridDim.x) { + const int2 tl = tb.tiles[t0 + w / NFB]; + const int fb = w % NFB, e = tl.x, row0 = tl.y, nrows = min(kTileRows, tb.off[e + 1] - row0); + const uint8_t* blob = b.blob[e - b.e0]; + const int rbase = fb * W_ROWS; + __syncthreads(); // the previous item is done with srow / wsc / hs + if (tid < kTileRows) { + const int r = row0 + min(tid, nrows - 1); // rows past the tile's end repeat its last one + srow[tid] = GU ? src[r] : r; + } + { + const uint4* s4 = reinterpret_cast(blob + O_SC + (size_t) rbase * NKB * 2); + for (int i = tid; i < W_ROWS * NKB / 8; i += W_THREADS) reinterpret_cast(wsc)[i] = s4[i]; + } + __syncthreads(); + const bool on = 32 * wn < nrows; // a wave past the tile's rows only stages + float acc[2][2][8]; +#pragma unroll + for (int mt = 0; mt < 2; ++mt) +#pragma unroll + for (int nt = 0; nt < 2; ++nt) +#pragma unroll + for (int i = 0; i < 8; ++i) acc[mt][nt][i] = 0.0f; + if (on) { + const uint8_t* arow[2]; + const uint8_t* brow[2]; +#pragma unroll + for (int mt = 0; mt < 2; ++mt) arow[mt] = blob + O_CODES + (size_t) (rbase + 32 * wm + 16 * mt + l16) * CODE_LD; +#pragma unroll + for (int nt = 0; nt < 2; ++nt) brow[nt] = act + (size_t) srow[32 * wn + 16 * nt + l16] * ACT_LD; + uint4 ac[2], bq[2][4]; + float4 bs[2]; + auto fetch = [&](int kb, uint4 (&a)[2], uint4 (&q)[2][4], float4 (&s)[2]) { +#pragma unroll + for (int mt = 0; mt < 2; ++mt) a[mt] = *reinterpret_cast(arow[mt] + kb * 16); +#pragma unroll + for (int nt = 0; nt < 2; ++nt) { + const uint4* p = reinterpret_cast(brow[nt] + kb * AB); + q[nt][0] = p[0]; q[nt][1] = p[1]; q[nt][2] = p[2]; q[nt][3] = p[3]; + s[nt] = *reinterpret_cast(brow[nt] + kb * AB + 64); + } + }; + fetch(0, ac, bq, bs); + for (int kb = 0; kb < NKB; ++kb) { + uint4 nac[2], nbq[2][4]; + float4 nbs[2]; + if (kb + 1 < NKB) fetch(kb + 1, nac, nbq, nbs); + w11_i8 c[2][2][2]; // [half][mt][nt] +#pragma unroll + for (int h = 0; h < 2; ++h) +#pragma unroll + for (int mt = 0; mt < 2; ++mt) +#pragma unroll + for (int nt = 0; nt < 2; ++nt) c[h][mt][nt] = w11_i8{0, 0, 0, 0, 0, 0, 0, 0}; +#pragma unroll + for (int ks = 0; ks < 4; ++ks) { // k-step = 16-weight word ks of the block + w11_i4 A[2]; +#pragma unroll + for (int mt = 0; mt < 2; ++mt) { + const unsigned wd = ks == 0 ? ac[mt].x : ks == 1 ? ac[mt].y : ks == 2 ? ac[mt].z : ac[mt].w; + A[mt] = w11_i4{(int) (wd & M2), (int) ((wd >> 2) & M2), (int) ((wd >> 4) & M2), + (int) ((wd >> 6) & M2)}; + } +#pragma unroll + for (int nt = 0; nt < 2; ++nt) { + const uint4 q = bq[nt][ks]; + const w11_i4 B = w11_i4{(int) q.x, (int) q.y, (int) q.z, (int) q.w}; +#pragma unroll + for (int mt = 0; mt < 2; ++mt) c[ks >> 1][mt][nt] = wmma_iu8(A[mt], B, c[ks >> 1][mt][nt]); + } + } + // the epilogue: per 64-weight block acc += d_w * (d_x0 * (dot0 - sum0) + d_x1 * (dot1 - sum1)) +#pragma unroll + for (int mt = 0; mt < 2; ++mt) { + float dw[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int m = 32 * wm + 16 * mt + 2 * i + hi; + dw[i] = __half2float(__ushort_as_half(wsc[m * NKB + kb])); + } +#pragma unroll + for (int nt = 0; nt < 2; ++nt) { + const float4 z = bs[nt]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float u0 = __int_as_float(MAGIC + c[0][mt][nt][i]) + z.y; + const float u1 = __int_as_float(MAGIC + c[1][mt][nt][i]) + z.w; + acc[mt][nt][i] = fmaf(dw[i], fmaf(z.z, u1, z.x * u0), acc[mt][nt][i]); + } + } + } + if (kb + 1 < NKB) { +#pragma unroll + for (int mt = 0; mt < 2; ++mt) ac[mt] = nac[mt]; +#pragma unroll + for (int nt = 0; nt < 2; ++nt) { + bs[nt] = nbs[nt]; +#pragma unroll + for (int j = 0; j < 4; ++j) bq[nt][j] = nbq[nt][j]; + } + } + } + } + if constexpr (GU) { + // SwiGLU: row 2f is feature f's gate (lanes 0..15), 2f + 1 its up (lanes 16..31) - the same (mt, i) + if (on) { +#pragma unroll + for (int mt = 0; mt < 2; ++mt) +#pragma unroll + for (int nt = 0; nt < 2; ++nt) +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float up = __shfl_xor_sync(0xffffffffu, acc[mt][nt][i], 16); + const float gt = acc[mt][nt][i]; + if (hi == 0) hs[32 * wn + 16 * nt + l16][16 * wm + 8 * mt + i] = gt / (1.0f + __expf(-gt)) * up; + } + } + __syncthreads(); + // H block fb (features 64 fb .. 64 fb + 63) to int8: a thread per (tile row, half) + if (tid < 2 * kTileRows) { + const int r = tid >> 1, hh = tid & 1; + if (r < nrows) { + float am = 0.0f; +#pragma unroll 8 + for (int j = 0; j < 32; ++j) am = fmaxf(am, fabsf(hs[r][32 * hh + j])); + const float inv = am > 0.0f ? 127.0f / am : 0.0f; + uint8_t* o = out + (size_t) (row0 + r) * (10 * AB) + (size_t) fb * AB; + int sum = 0; + uint32_t wd[8] = {}; +#pragma unroll + for (int j = 0; j < 32; ++j) { + const int qv = __float2int_rn(hs[r][32 * hh + j] * inv); + sum += qv; + const int p = act_pos(j); + wd[p >> 2] |= (uint32_t) (uint8_t) (int8_t) qv << (8 * (p & 3)); + } + uint4* o4 = reinterpret_cast(o + 32 * hh); + o4[0] = make_uint4(wd[0], wd[1], wd[2], wd[3]); + o4[1] = make_uint4(wd[4], wd[5], wd[6], wd[7]); + *reinterpret_cast(o + 64 + 8 * hh) = make_float2(am / 127.0f, -(MAGICF + (float) sum)); + } + } + } else if (on) { +#pragma unroll + for (int mt = 0; mt < 2; ++mt) +#pragma unroll + for (int nt = 0; nt < 2; ++nt) { + const int r = 32 * wn + 16 * nt + l16; + if (r < nrows) { + float* d = dm + (size_t) (row0 + r) * 2560 + rbase + 32 * wm + 16 * mt + hi; +#pragma unroll + for (int i = 0; i < 8; ++i) d[2 * i] = acc[mt][nt][i]; + } + } + } + } +#else + __builtin_trap(); +#endif +} +#endif // __HIPCC__ + unsigned blocks(int64_t n, int per) { return (unsigned) ((n + per - 1) / per); } struct DevInfo { @@ -364,6 +584,24 @@ const DevInfo& dev_info() { DevInfo& d = g_dev[dev & 31]; if (d.done) return d; d.done = true; +#if defined(__HIPCC__) + { // gfx11 (RDNA3 / RDNA3.5) with this build's code for it: the WMMA kernels + cudaDeviceProp prop; + cudaDeviceGetAttribute(&d.sms, cudaDevAttrMultiProcessorCount, dev); + hipFuncAttributes fa{}; + if (cudaGetDeviceProperties(&prop, dev) != cudaSuccess || std::strncmp(prop.gcnArchName, "gfx11", 5) != 0 || + hipFuncGetAttributes(&fa, reinterpret_cast(expert_w11_kernel)) != hipSuccess) { + cudaGetLastError(); + return d; + } + if (hipOccupancyMaxActiveBlocksPerMultiprocessor(&d.occ_gu, expert_w11_kernel, W_THREADS, 0) != hipSuccess || + hipOccupancyMaxActiveBlocksPerMultiprocessor(&d.occ_d, expert_w11_kernel, W_THREADS, 0) != hipSuccess) + d.occ_gu = d.occ_d = 0; + d.cc = d.occ_gu >= 1 && d.occ_d >= 1 ? 80 : 0; + cudaGetLastError(); + return d; + } +#else int major = 0, minor = 0; cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev); cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev); @@ -386,6 +624,7 @@ const DevInfo& dev_info() { if (d.occ_gu < 1 || d.occ_d < 1) d.cc = 0; // does not fit this card: the MMQ path cudaGetLastError(); return d; +#endif } } // namespace @@ -398,7 +637,11 @@ bool available() { return dev_info().cc >= 80; } bool enabled() { static const bool env = [] { const char* v = std::getenv("STRATA_PF_FUSED"); +#if defined(__HIPCC__) + return v != nullptr && v[0] == '1'; // Aurora: the gfx11 WMMA kernels are opt-in (STRATA_PF_FUSED=1) +#else return v == nullptr || v[0] != '0'; +#endif }(); return env && available(); } @@ -448,11 +691,18 @@ void experts(const Batch& b, int n_expert, int64_t n, const void* scratch, const const Tables tb = tables(const_cast(scratch), n_expert); // the most tiles the batch can have: every row in it, plus a partial tile per expert const int64_t tiles = (n + kTileRows - 1) / kTileRows + (b.e1 - b.e0); +#if defined(__HIPCC__) + const unsigned g_gu = (unsigned) std::min(tiles * (1280 / W_ROWS), (int64_t) d.sms * d.occ_gu); + const unsigned g_d = (unsigned) std::min(tiles * (2560 / W_ROWS), (int64_t) d.sms * d.occ_d); + expert_w11_kernel<<>>(b, tb, (const uint8_t*) xa, src, (uint8_t*) ha, nullptr); + expert_w11_kernel<<>>(b, tb, (const uint8_t*) ha, src, nullptr, dm); +#else const unsigned g_gu = (unsigned) std::min(tiles * 5, (int64_t) d.sms * d.occ_gu); const unsigned g_d = (unsigned) std::min(tiles * 10, (int64_t) d.sms * d.occ_d); expert_kernel<<>>(b, tb, (const uint8_t*) xa, src, (uint8_t*) ha, nullptr); expert_kernel<<>>(b, tb, (const uint8_t*) ha, src, nullptr, dm); +#endif ck(cudaGetLastError(), "experts"); } diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 83ff730b..ffc816bc 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -79,6 +79,14 @@ void quantize_act_native(const float*, int64_t, int64_t, void*, void*) {} void experts_native(const Batch&, const NativeGeom&, int, int64_t, const void*, const void*, const int32_t*, void*, float*, void*) {} } // namespace strata::prefill::fused +#elif defined(STRATA_PREFILL_FUSED_HIP) +// HIP: moe_fused.cu's gfx11 kernels (the Q2_0 pack) are built, the native packs' (moe_fused_iq.cu) are not +namespace strata::prefill::fused { +bool native_supported(int, int) { return false; } +void quantize_act_native(const float*, int64_t, int64_t, void*, void*) {} +void experts_native(const Batch&, const NativeGeom&, int, int64_t, const void*, const void*, const int32_t*, void*, + float*, void*) {} +} // namespace strata::prefill::fused #endif namespace strata::prefill { From 4cca9043e075e31534a1f4edd05cfc27276a90d4 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 2 Oct 2026 21:39:49 +0200 Subject: [PATCH 09/55] HIP: the native packs' fused prompt experts on gfx11 matrix cores (opt-in STRATA_PF_FUSED=1) native_w11_kernel: moe_fused_iq.cu's decode (load_unit / convert: IQ2_XXS IQ2_XS IQ2_S IQ3_XXS IQ3_S IQ4_XS gate/up, Q2_0 IQ4_NL down) into double-buffered LDS, v_wmma_i32_16x16x16_iu8 from a MAGIC C operand (the CUDA kernel's arithmetic), 128 weight rows x 64-row tile per item, 8 waves of 2x2 tiles. hip_prefill_fused_iq (tests/cuda/prefill_fused_iq_test.cpp) on gfx1151: every pair passes against the FP32 reference (= MMQ's error) and MMQ (rel RMS 3e-5..3e-4); one layer, IQ3_XXS / IQ4_NL: 2048 tokens 31.1 -> 22.6 ms, 8192 tokens 67.2 -> 62.0 ms (MMQ path -> fused). --- CMakeLists.txt | 15 +- src/prefill/moe_fused_iq.cu | 273 ++++++++++++++++++++++++++++++++++++ src/prefill/prefill.cpp | 8 -- 3 files changed, 284 insertions(+), 12 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 27a3b6b0..258c21ae 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -949,11 +949,11 @@ if(STRATA_NATIVE_EXPERTS) if(NOT EXISTS "${_strata_mmq}/common.cuh" OR NOT EXISTS "${_strata_mmq}/quantize.cu") message(FATAL_ERROR "The selected GGML source is missing the ggml-cuda MMQ sources: ${_strata_mmq}") endif() - # Aurora: moe_fused.cu's gfx11 WMMA kernels for the Q2_0 pack's prompt experts (opt-in STRATA_PF_FUSED=1); the - # native packs' fused kernels (moe_fused_iq.cu) stay CUDA-only + # Aurora: moe_fused.cu's and moe_fused_iq.cu's gfx11 WMMA kernels for the prompt experts (opt-in STRATA_PF_FUSED=1) set(_strata_mmq_sources src/prefill/moe_mmq.cu src/prefill/moe_fused.cu + src/prefill/moe_fused_iq.cu src/prefill/ggml_cuda_host.cu "${_strata_mmq}/quantize.cu") foreach(_t IN LISTS _strata_mmq_types) @@ -961,7 +961,8 @@ if(STRATA_NATIVE_EXPERTS) endforeach() set_source_files_properties(${_strata_mmq_sources} PROPERTIES LANGUAGE HIP) # moe_fused.cu is Strata's own CUDA-shaped source: it takes the HIP compat headers, ggml's MMQ sources do not - set_source_files_properties(src/prefill/moe_fused.cu PROPERTIES INCLUDE_DIRECTORIES "${STRATA_HIP_COMPAT_INCLUDE_DIR}") + set_source_files_properties(src/prefill/moe_fused.cu src/prefill/moe_fused_iq.cu + PROPERTIES INCLUDE_DIRECTORIES "${STRATA_HIP_COMPAT_INCLUDE_DIR}") add_library(strata_mmq STATIC ${_strata_mmq_sources}) target_include_directories(strata_mmq PRIVATE "${_strata_gg}/include" "${_strata_gg}/src" "${_strata_mmq}" @@ -972,7 +973,7 @@ if(STRATA_NATIVE_EXPERTS) endif() target_link_libraries(strata_mmq PUBLIC ggml-base hip::host roc::hipblas) target_link_libraries(strata_prefill PUBLIC strata_mmq) - target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_MMQ=1 STRATA_PREFILL_FUSED=1 STRATA_PREFILL_FUSED_HIP=1) + target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_MMQ=1 STRATA_PREFILL_FUSED=1) # Aurora: the gfx11 fused experts against the FP64 reference and MMQ (tests/cuda's test; exit 77 off gfx11) add_executable(hip_prefill_fused_moe tests/cuda/prefill_fused_moe_test.cpp) target_include_directories(hip_prefill_fused_moe PRIVATE "${_strata_gg}/include") @@ -980,6 +981,12 @@ if(STRATA_NATIVE_EXPERTS) add_test(NAME hip_prefill_fused_moe COMMAND hip_prefill_fused_moe) set_tests_properties(hip_prefill_fused_moe PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300) list(APPEND _strata_hip_tests hip_prefill_fused_moe) + add_executable(hip_prefill_fused_iq tests/cuda/prefill_fused_iq_test.cpp) + target_include_directories(hip_prefill_fused_iq PRIVATE "${_strata_gg}/include") + target_link_libraries(hip_prefill_fused_iq PRIVATE strata_mmq ggml-base strata_hip_runtime) + add_test(NAME hip_prefill_fused_iq COMMAND hip_prefill_fused_iq) + set_tests_properties(hip_prefill_fused_iq PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600) + list(APPEND _strata_hip_tests hip_prefill_fused_iq) # Numerical diagnostic: synthetic layouts by default, optional first-expert IQ3_XXS/IQ4_NL check with a pack. add_executable(hip_prefill_mmq_parity tests/hip/prefill_mmq_parity.cpp) diff --git a/src/prefill/moe_fused_iq.cu b/src/prefill/moe_fused_iq.cu index 52476c87..14b02ec8 100644 --- a/src/prefill/moe_fused_iq.cu +++ b/src/prefill/moe_fused_iq.cu @@ -33,6 +33,7 @@ #include #include #include +#include #include namespace strata::prefill::fused { @@ -142,6 +143,11 @@ __device__ __forceinline__ void ldsm4(uint32_t (&r)[4], const void* p) { : "memory"); } +#endif +#if (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800) || defined(__HIPCC__) +#if defined(__HIPCC__) +__device__ __forceinline__ float dotf(int d) { return __int_as_float(d) - MAGICF; } +#endif // ---- the load stage: a 32-value sub-block's bytes into registers, then int8 and scales __device__ __forceinline__ uint32_t ld16(const uint8_t* p) { return *(const uint16_t*) p; } __device__ __forceinline__ uint32_t ld32(const uint8_t* p) { return ld16(p) | (ld16(p + 2) << 16); } @@ -506,6 +512,228 @@ native_kernel(const Batch b, const NativeGeom geo, const Tables tb, const uint8_ #endif } +#if defined(__HIPCC__) +// ---- Aurora (S23): the native packs' fused experts on gfx11 (RDNA3 / RDNA3.5) matrix cores, v_wmma_i32_16x16x16_iu8 +// (wave32). The CUDA kernel's arithmetic: a 32-value sub-block decoded to int8 (load_unit / convert above) and its +// scales; per 32 values the int32 dot starts from MAGIC (the C operand), so as_float(d) - 1.5 * 2^23 is the dot; the +// formats with a scale per 16 values take each 16-value k-step's dot alone. Fragments (gfx11): A lane l holds the 16 +// k of row l % 16 (lanes 16..31 repeat lanes 0..15), B lane l the 16 k of column l % 16, C/D lane l holds +// D[2i + l / 16][l % 16]. Both operands are in natural order: the decoded weights (LDS, double-buffered) and the +// activations (quant_act_nat_kernel; read by each lane from global/L2, a stage ahead). +// A work item = NW_ROWS weight rows x a 64-row tile; 8 waves: 4 along the weight rows (32 each) x 2 along the tile +// (32 each), each 2 x 2 WMMA tiles. Gate/up: local row r is feature r / 2, its gate (r even) or up (r odd) row, so a +// lane pair l, l + 16 holds gate and up of one feature. +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__) +#define STRATA_NAT_W11 1 +#else +#define STRATA_NAT_W11 0 +#endif +typedef int nw_i4 __attribute__((ext_vector_type(4))); +typedef int nw_i8 __attribute__((ext_vector_type(8))); +constexpr int NW_ROWS = 128; +constexpr int NW_THREADS = 256; + +__device__ __forceinline__ nw_i8 nw_wmma(nw_i4 a, nw_i4 b, nw_i8 c) { +#if STRATA_NAT_W11 + return __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32(true, a, true, b, c, false); +#else + __builtin_trap(); + return c; +#endif +} +__device__ __forceinline__ nw_i4 nw_u4(uint4 v) { return nw_i4{(int) v.x, (int) v.y, (int) v.z, (int) v.w}; } + +template +__global__ void __launch_bounds__(NW_THREADS) +native_w11_kernel(const Batch b, const NativeGeom geo, const Tables tb, const uint8_t* __restrict__ act, + const int32_t* __restrict__ src, uint8_t* __restrict__ out, float* __restrict__ dm) { +#if STRATA_NAT_W11 + constexpr int NS = (GU ? GU_ROWS_K : D_ROWS_K) / 64; // 64-value stages along K + constexpr int NFB = (GU ? 1280 : 2560) / NW_ROWS; // work items per tile + constexpr int ACT_LD = NS * AB; + constexpr int BS = block_bytes(WT); + constexpr bool K16 = per16(WT); + constexpr int GB = grid_bytes(WT) > 0 ? grid_bytes(WT) : 16; + __shared__ __align__(16) uint8_t wt[2][NW_ROWS][WLD]; // decoded int8 weights of a stage (64 + 16 pad) + __shared__ __align__(16) float ws[2][NW_ROWS][4]; // their scales per 16 values + __shared__ __align__(16) uint8_t sgrid[GB]; + __shared__ int srow[kTileRows]; + __shared__ float hs[GU ? kTileRows : 1][GU ? 65 : 1]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int wm = wave & 3, wn = wave >> 2, l16 = lane & 15, hi = lane >> 4; + if constexpr (grid_bytes(WT) > 0) { + const uint32_t* gs = (const uint32_t*) grid_src(); + for (int i = tid; i < grid_bytes(WT) / 4; i += NW_THREADS) ((uint32_t*) sgrid)[i] = gs[i]; + } + uint32_t kv[4] = {0, 0, 0, 0}; + if constexpr (WT == T_IQ4_XS || WT == T_IQ4_NL) { +#pragma unroll + for (int k = 0; k < 16; ++k) kv[k >> 2] |= (uint32_t) (uint8_t) kvalues_iq4nl[k] << (8 * (k & 3)); + } + const int ur = tid >> 1, uj = tid & 1; // this thread's decode unit: row ur, sub-block uj + const int t0 = tb.ts[b.e0], nwork = (tb.ts[b.e1] - t0) * NFB; + for (int w = blockIdx.x; w < nwork; w += gridDim.x) { + const int2 tl = tb.tiles[t0 + w / NFB]; + const int fb = w % NFB, e = tl.x, row0 = tl.y, nrows = min(kTileRows, tb.off[e + 1] - row0); + const uint8_t* blob = b.blob[e - b.e0]; + const int rbase = fb * NW_ROWS; + const uint8_t* wrow = GU ? blob + ((ur & 1) ? geo.up_off : 0) + (size_t) (fb * (NW_ROWS / 2) + (ur >> 1)) * geo.gu_row + : blob + geo.down_off + (size_t) (rbase + ur) * geo.d_row; + auto unit = [&](int s) -> const uint8_t* { + if (GU) return wrow + (s >> 2) * BS; + return WT == T_IQ4_NL ? wrow + (2 * s + uj) * BS : wrow + s * BS; + }; + auto sub = [&](int s) { return GU ? 2 * (s & 3) + uj : uj; }; + auto put = [&](const uint32_t (&raw)[5], int buf) { + uint32_t q[8]; + float s0, s1; + convert(raw, sgrid, kv, q, s0, s1); + uint4* d = (uint4*) &wt[buf][ur][32 * uj]; + d[0] = make_uint4(q[0], q[1], q[2], q[3]); + d[1] = make_uint4(q[4], q[5], q[6], q[7]); + *(float2*) &ws[buf][ur][2 * uj] = make_float2(s0, s1); + }; + __syncthreads(); // the previous item is done with the buffers + if (tid < kTileRows) { + const int r = row0 + min(tid, nrows - 1); // rows past the tile's end repeat its last one + srow[tid] = GU ? src[r] : r; + } + uint32_t raw[5] = {0, 0, 0, 0, 0}; + load_unit(unit(0), sub(0), raw); + put(raw, 0); + if (NS > 1) load_unit(unit(1), sub(1), raw); + __syncthreads(); // srow + const bool on = 32 * wn < nrows; + const uint8_t* brow[2]; +#pragma unroll + for (int nt = 0; nt < 2; ++nt) brow[nt] = act + (size_t) srow[32 * wn + 16 * nt + l16] * ACT_LD; + float acc[2][2][8]; +#pragma unroll + for (int mt = 0; mt < 2; ++mt) +#pragma unroll + for (int nt = 0; nt < 2; ++nt) +#pragma unroll + for (int i = 0; i < 8; ++i) acc[mt][nt][i] = 0.0f; + uint4 bq[2][4]; + float2 bx[2]; + auto fetch_b = [&](int s, uint4 (&q)[2][4], float2 (&x)[2]) { +#pragma unroll + for (int nt = 0; nt < 2; ++nt) { + const uint4* p = reinterpret_cast(brow[nt] + s * AB); + q[nt][0] = p[0]; q[nt][1] = p[1]; q[nt][2] = p[2]; q[nt][3] = p[3]; + x[nt] = *reinterpret_cast(brow[nt] + s * AB + 64); + } + }; + if (on) fetch_b(0, bq, bx); + for (int s = 0; s < NS; ++s) { + __syncthreads(); // stage s's weights are in buffer s & 1 + uint4 nbq[2][4]; + float2 nbx[2]; + if (on && s + 1 < NS) fetch_b(s + 1, nbq, nbx); + if (on) { + const int bf = s & 1; +#pragma unroll + for (int h = 0; h < 2; ++h) { +#pragma unroll + for (int mt = 0; mt < 2; ++mt) { + const int rb = 32 * wm + 16 * mt; + const uint4* ap = reinterpret_cast(&wt[bf][rb + l16][32 * h]); + const nw_i4 A0 = nw_u4(ap[0]), A1 = nw_u4(ap[1]); + float w0[8], w1[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float2 sw = *reinterpret_cast(&ws[bf][rb + 2 * i + hi][2 * h]); + w0[i] = sw.x; w1[i] = sw.y; + } +#pragma unroll + for (int nt = 0; nt < 2; ++nt) { + const float dx = h ? bx[nt].y : bx[nt].x; + const nw_i4 B0 = nw_u4(bq[nt][2 * h]), B1 = nw_u4(bq[nt][2 * h + 1]); + const nw_i8 m = nw_i8{MAGIC, MAGIC, MAGIC, MAGIC, MAGIC, MAGIC, MAGIC, MAGIC}; + if constexpr (K16) { + const nw_i8 d0 = nw_wmma(A0, B0, m), d1 = nw_wmma(A1, B1, m); +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float v = fmaf(w1[i], dotf(d1[i]), w0[i] * dotf(d0[i])); + acc[mt][nt][i] = fmaf(dx, v, acc[mt][nt][i]); + } + } else { + const nw_i8 d = nw_wmma(A1, B1, nw_wmma(A0, B0, m)); +#pragma unroll + for (int i = 0; i < 8; ++i) acc[mt][nt][i] = fmaf(w0[i] * dx, dotf(d[i]), acc[mt][nt][i]); + } + } + } + } + } + if (s + 1 < NS) { + put(raw, (s + 1) & 1); // the other buffer: its readers passed this barrier + if (s + 2 < NS) load_unit(unit(s + 2), sub(s + 2), raw); + if (on) { +#pragma unroll + for (int nt = 0; nt < 2; ++nt) { + bx[nt] = nbx[nt]; +#pragma unroll + for (int j = 0; j < 4; ++j) bq[nt][j] = nbq[nt][j]; + } + } + } + } + if constexpr (GU) { + if (on) { +#pragma unroll + for (int mt = 0; mt < 2; ++mt) +#pragma unroll + for (int nt = 0; nt < 2; ++nt) +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float up = __shfl_xor_sync(0xffffffffu, acc[mt][nt][i], 16); + const float gt = acc[mt][nt][i]; + if (hi == 0) hs[32 * wn + 16 * nt + l16][16 * wm + 8 * mt + i] = gt / (1.0f + __expf(-gt)) * up; + } + } + __syncthreads(); + // H block fb (features 64 fb ..) to int8 per 32, natural order: a thread per (tile row, half) + if (tid < 2 * kTileRows) { + const int r = tid >> 1, hh = tid & 1; + if (r < nrows) { + float am = 0.0f; +#pragma unroll 8 + for (int j = 0; j < 32; ++j) am = fmaxf(am, fabsf(hs[r][32 * hh + j])); + const float inv = am > 0.0f ? 127.0f / am : 0.0f; + uint8_t* o = out + (size_t) (row0 + r) * (10 * AB) + (size_t) fb * AB; + uint32_t wd[8] = {}; +#pragma unroll + for (int j = 0; j < 32; ++j) + wd[j >> 2] |= (uint32_t) (uint8_t) (int8_t) __float2int_rn(hs[r][32 * hh + j] * inv) << (8 * (j & 3)); + uint4* o4 = reinterpret_cast(o + 32 * hh); + o4[0] = make_uint4(wd[0], wd[1], wd[2], wd[3]); + o4[1] = make_uint4(wd[4], wd[5], wd[6], wd[7]); + *reinterpret_cast(o + 64 + 4 * hh) = am / 127.0f; + } + } + } else { + if (on) { +#pragma unroll + for (int mt = 0; mt < 2; ++mt) +#pragma unroll + for (int nt = 0; nt < 2; ++nt) { + const int r = 32 * wn + 16 * nt + l16; + if (r < nrows) { + float* d = dm + (size_t) (row0 + r) * 2560 + rbase + 32 * wm + 16 * mt + hi; +#pragma unroll + for (int i = 0; i < 8; ++i) d[2 * i] = acc[mt][nt][i]; + } + } + } + } + } +#else + __builtin_trap(); +#endif +} +#endif // __HIPCC__ + unsigned blocks(int64_t n, int per) { return (unsigned) ((n + per - 1) / per); } // per device: whether every kernel here runs (sm_80+, device code in this build, fits), and their occupancy @@ -516,6 +744,7 @@ struct DevInfo { std::mutex g_mu; DevInfo g_dev[32]; +#if !defined(__HIPCC__) template bool setup_ww(int& occ) { cudaFuncAttributes fa{}; if (cudaFuncGetAttributes(&fa, native_kernel) != cudaSuccess || fa.ptxVersion < 80) return false; @@ -530,6 +759,7 @@ template bool setup_ww(int& occ) { return true; } template bool setup_one(int& occ) { return setup_ww(occ) && setup_ww(occ); } +#endif const DevInfo& dev_info() { int dev = 0; @@ -538,6 +768,25 @@ const DevInfo& dev_info() { DevInfo& d = g_dev[dev & 31]; if (d.done) return d; d.done = true; +#if defined(__HIPCC__) + { // gfx11 with this build's code: the WMMA kernels (one occupancy for all: the same shape and LDS budget) + cudaDeviceGetAttribute(&d.sms, cudaDevAttrMultiProcessorCount, dev); + cudaDeviceProp prop; + hipFuncAttributes fa{}; + if (cudaGetDeviceProperties(&prop, dev) != cudaSuccess || std::strncmp(prop.gcnArchName, "gfx11", 5) != 0 || + hipFuncGetAttributes(&fa, reinterpret_cast(native_w11_kernel)) != hipSuccess) { + cudaGetLastError(); + return d; + } + int o = 0; + if (hipOccupancyMaxActiveBlocksPerMultiprocessor(&o, native_w11_kernel, NW_THREADS, 0) != hipSuccess) + o = 0; + d.ok = o >= 1; + d.occ = d.ok ? o : 1; + cudaGetLastError(); + return d; + } +#else int major = 0; cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev); cudaDeviceGetAttribute(&d.sms, cudaDevAttrMultiProcessorCount, dev); @@ -549,6 +798,7 @@ const DevInfo& dev_info() { d.occ = d.ok ? occ : 1; cudaGetLastError(); return d; +#endif } bool gu_covered(int t) { @@ -608,6 +858,29 @@ void experts_native(const Batch& b, const NativeGeom& g, int n_expert, int64_t n } const cudaStream_t s = (cudaStream_t) stream; const Tables tb = tables(const_cast(scratch), n_expert); +#if defined(__HIPCC__) + { + const int64_t tiles = (n + kTileRows - 1) / kTileRows + (b.e1 - b.e0); + const unsigned g_gu = (unsigned) std::min(tiles * (1280 / NW_ROWS), (int64_t) d.sms * d.occ); + const unsigned g_d = (unsigned) std::min(tiles * (2560 / NW_ROWS), (int64_t) d.sms * d.occ); + const uint8_t* xa8 = (const uint8_t*) xa; + uint8_t* ha8 = (uint8_t*) ha; +#define STRATA_NW_GU(T) native_w11_kernel<<>>(b, g, tb, xa8, src, ha8, nullptr) + switch (g.gu_type) { + case T_IQ2_XXS: STRATA_NW_GU(T_IQ2_XXS); break; + case T_IQ2_XS: STRATA_NW_GU(T_IQ2_XS); break; + case T_IQ2_S: STRATA_NW_GU(T_IQ2_S); break; + case T_IQ3_XXS: STRATA_NW_GU(T_IQ3_XXS); break; + case T_IQ3_S: STRATA_NW_GU(T_IQ3_S); break; + default: STRATA_NW_GU(T_IQ4_XS); break; + } +#undef STRATA_NW_GU + if (g.d_type == T_Q2_0) native_w11_kernel<<>>(b, g, tb, ha8, src, nullptr, dm); + else native_w11_kernel<<>>(b, g, tb, ha8, src, nullptr, dm); + ck(cudaGetLastError(), "experts_native"); + return; + } +#endif const int ww = pick_ww(n, n_expert); // the most 64-row tiles the batch can have (every row in it, plus a partial tile per expert) - the items of the // ones inside a larger item end at once diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index ffc816bc..83ff730b 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -79,14 +79,6 @@ void quantize_act_native(const float*, int64_t, int64_t, void*, void*) {} void experts_native(const Batch&, const NativeGeom&, int, int64_t, const void*, const void*, const int32_t*, void*, float*, void*) {} } // namespace strata::prefill::fused -#elif defined(STRATA_PREFILL_FUSED_HIP) -// HIP: moe_fused.cu's gfx11 kernels (the Q2_0 pack) are built, the native packs' (moe_fused_iq.cu) are not -namespace strata::prefill::fused { -bool native_supported(int, int) { return false; } -void quantize_act_native(const float*, int64_t, int64_t, void*, void*) {} -void experts_native(const Batch&, const NativeGeom&, int, int64_t, const void*, const void*, const int32_t*, void*, - float*, void*) {} -} // namespace strata::prefill::fused #endif namespace strata::prefill { From b3096357c1508e421b1b68a267aa0684b3d0bd6a Mon Sep 17 00:00:00 2001 From: sergiywith Date: Thu, 1 Oct 2026 17:08:22 +0300 Subject: [PATCH 10/55] Prompt path: an MMQ group's experts gathered in one launch, after one wait, released by one event In the streamed walk every expert put a cross-stream wait (its copy) and an event record (its ring slot back) on the compute stream around a ~3 us gather. Under WDDM each pair left ~10 us of GPU idle even when the copy had long landed: an nsys trace of a 32K prompt showed 226 ms of idle between back-to-back gathers while the host was 3-11 ms ahead of the GPU. Now a group of 16 is gathered by one launch (copy16_group_kernel) after one wait on its last streamed copy - the copy stream is in order - and one event releases all of its ring slots: the issuer waits on used[used_of[slot]]. A ring entry the routing skipped inside an open group first gathers what the group holds so far, so no more than a group's entries are ever held back from the issuer. The same bytes in the same group slots. STRATA_PREFILL_GROUP_GATHER=0: one at a time, as before. IQ2_XS, RTX 5090, 262K context: 32K prompt -8.6%, 8K -10%, 2K -12.6%; first-token logits bit-identical at 2K, 8K, 16K and 32K and with a 96-slot ring. --- include/strata/prefill/moe_mmq.hpp | 10 ++++ src/prefill/moe_mmq.cu | 35 ++++++++++++ src/prefill/prefill.cpp | 85 +++++++++++++++++++++++++----- 3 files changed, 118 insertions(+), 12 deletions(-) diff --git a/include/strata/prefill/moe_mmq.hpp b/include/strata/prefill/moe_mmq.hpp index d9f0eba6..0859dca3 100644 --- a/include/strata/prefill/moe_mmq.hpp +++ b/include/strata/prefill/moe_mmq.hpp @@ -64,6 +64,16 @@ private: /// slot: gate rows then up rows at `gu_dst`, down at `d_dst`. void gather_native(const void* gate, const void* up, size_t gu_half_bytes, const void* down, size_t d_bytes, void* gu_dst, void* d_dst, void* stream); +/// gather_native for an MMQ group's experts [first, n) in ONE launch: expert q's blob (`blob[q]`; gate at +0, up at +/// +up_off, down at +down_off) to gu_dst + q * gu_stride and d_dst + q * d_stride - the same bytes as one gather_native +/// each. Every pointer, offset and size 16-byte aligned (false otherwise: nothing launched, gather one at a time). +constexpr int kGatherGroupMax = 16; +struct GatherGroup { + const uint8_t* blob[kGatherGroupMax] = {}; + int first = 0, n = 0; +}; +bool gather_native_group(const GatherGroup& g, size_t up_off, size_t gu_half_bytes, size_t down_off, size_t d_bytes, + void* gu_dst, size_t gu_stride, void* d_dst, size_t d_stride, void* stream); /// A Strata-pack Q2_0 expert blob (codes and fp16 scales in separate planes, gate/up rows interleaved) into GGUF /// Q2_0 blocks: gate/up [1280, 2560] at `gu_dst` (rows stay interleaved), down [2560, 640] at `d_dst`. Same values. void gather_strata_q2(const uint8_t* blob, void* gu_dst, void* d_dst, void* stream); diff --git a/src/prefill/moe_mmq.cu b/src/prefill/moe_mmq.cu index 1f0221c7..c61e707a 100644 --- a/src/prefill/moe_mmq.cu +++ b/src/prefill/moe_mmq.cu @@ -29,6 +29,22 @@ __global__ void copy16_kernel(const uint4* __restrict__ a, int64_t na, const uin else if (i < na + nb) ab_dst[i] = b[i - na]; else if (i < na + nb + nc) c_dst[i - na - nb] = c[i - na - nb]; } +// copy16_kernel for an MMQ group: blockIdx.y is the expert (first + y) +struct GroupArgs { + const uint8_t* blob[kGatherGroupMax]; + int64_t up_off, down_off, gu_stride, d_stride; // in uint4 +}; +__global__ void copy16_group_kernel(GroupArgs ga, int first, int64_t na, int64_t nc, uint4* __restrict__ gu_dst, + uint4* __restrict__ d_dst) { + const int q = first + (int) blockIdx.y; + const uint4* src = (const uint4*) ga.blob[q]; + uint4* ab = gu_dst + (int64_t) q * ga.gu_stride; + uint4* cd = d_dst + (int64_t) q * ga.d_stride; + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i < na) ab[i] = src[i]; + else if (i < 2 * na) ab[i] = src[ga.up_off + (i - na)]; + else if (i < 2 * na + nc) cd[i - 2 * na] = src[ga.down_off + (i - 2 * na)]; +} __global__ void copy1_kernel(const uint8_t* __restrict__ a, int64_t na, const uint8_t* __restrict__ b, int64_t nb, uint8_t* __restrict__ ab_dst, const uint8_t* __restrict__ c, int64_t nc, uint8_t* __restrict__ c_dst) { const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; @@ -210,6 +226,25 @@ void gather_native(const void* gate, const void* up, size_t gu_half_bytes, const ck(cudaGetLastError(), "gather_native"); } +bool gather_native_group(const GatherGroup& g, size_t up_off, size_t gu_half_bytes, size_t down_off, size_t d_bytes, + void* gu_dst, size_t gu_stride, void* d_dst, size_t d_stride, void* stream) { + if (g.first < 0 || g.n <= g.first || g.n > kGatherGroupMax) return false; + uintptr_t a = (uintptr_t) gu_dst | (uintptr_t) d_dst | up_off | gu_half_bytes | down_off | d_bytes | gu_stride | d_stride; + for (int q = g.first; q < g.n; ++q) a |= (uintptr_t) g.blob[q]; + if (a % 16 != 0) return false; + GroupArgs ga{}; + for (int q = g.first; q < g.n; ++q) ga.blob[q] = g.blob[q]; + ga.up_off = (int64_t) up_off / 16; + ga.down_off = (int64_t) down_off / 16; + ga.gu_stride = (int64_t) gu_stride / 16; + ga.d_stride = (int64_t) d_stride / 16; + const int64_t na = (int64_t) gu_half_bytes / 16, nc = (int64_t) d_bytes / 16; + copy16_group_kernel<<>>( + ga, g.first, na, nc, (uint4*) gu_dst, (uint4*) d_dst); + ck(cudaGetLastError(), "gather_native_group"); + return true; +} + void gather_strata_q2(const uint8_t* blob, void* gu_dst, void* d_dst, void* stream) { strata_q2_kernel<<>>(blob, (uint16_t*) gu_dst, (uint16_t*) d_dst); diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 83ff730b..bf7d82e3 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -57,6 +57,7 @@ Context::Context() {} Context::~Context() {} void Context::run(const Product&, void*) {} void gather_native(const void*, const void*, size_t, const void*, size_t, void*, void*, void*) {} +bool gather_native_group(const GatherGroup&, size_t, size_t, size_t, size_t, void*, size_t, void*, size_t, void*) { return false; } void gather_strata_q2(const uint8_t*, void*, void*, void*) {} void swiglu(const float*, float*, int64_t, int64_t, bool, void*) {} void iota(int32_t*, int64_t, void*) {} @@ -390,6 +391,9 @@ struct Prefill::Impl { std::unique_ptr stager; // the unpinned experts' host copies (step 4) cudaEvent_t copied[RING_MAX] = {}, used[RING_MAX] = {}; bool stage_live[RING_MAX] = {}; + // the event that releases each ring slot: its own `used`, or - when an MMQ group is gathered in one launch - the + // `used` of the last slot gathered with it, recorded once for all of them (a later record only waits longer) + int used_of[RING_MAX] = {}; // PLE float* ple_emb = nullptr; std::vector ple_pageable[2]; // the fallback when no more RAM can be pinned @@ -766,6 +770,7 @@ bool Prefill::carve(size_t T, void* alloc) { for (int i = 0; i < m.ring; ++i) { m.stage_dev[i] = o.take((size_t) MAXBLOB(), ok); m.stage_live[i] = false; // a new buffer: nothing of an earlier layout to wait for + m.used_of[i] = i; } m.ple_emb = o.take(T * N, ok); m.ple_norm = o.take((size_t) strata::kernels::NG_HC_DIM, ok); @@ -1250,7 +1255,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e const int sl = (int) (issued % (size_t) m.ring); const auto th = Clock::now(); const size_t bytes = (size_t) lay0.blob_bytes(en.l); - if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[sl], 0); + if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[m.used_of[sl]], 0); if (en.job < 0) { cudaMemcpyAsync(m.stage_dev[sl], en.blob, bytes, cudaMemcpyHostToDevice, m.copy); ++stats_.experts_dma; @@ -1297,7 +1302,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e const int sl = (int) (idx % (size_t) m.ring); const auto th = Clock::now(); const size_t bytes = (size_t) lay0.blob_bytes(en.l); - if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[sl], 0); + if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[m.used_of[sl]], 0); if (en.job < 0) { cudaMemcpyAsync(m.stage_dev[sl], en.blob, bytes, cudaMemcpyHostToDevice, m.copy); ++iss_dma; @@ -1709,7 +1714,10 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e } else { fused::experts(b, (int) m.g->n_expert, T * K, m.GU, m.Xq, m.src_dev, m.H, m.Dm, m.cs); } - for (size_t kk = k0; kk < k; ++kk) cudaEventRecord(m.used[kk % (size_t) m.ring], m.cs); + for (size_t kk = k0; kk < k; ++kk) { + cudaEventRecord(m.used[kk % (size_t) m.ring], m.cs); + m.used_of[kk % (size_t) m.ring] = (int) (kk % (size_t) m.ring); + } if (k > k0) { consumed = k; give_back(consumed); @@ -1824,13 +1832,13 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e if (pinned && !b) { err = "prefill: expert source has no blob"; return false; } if (pinned) { // DMA straight from the page-locked arena: the copy stream only waits for the slot - if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[sl], 0); + if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[m.used_of[sl]], 0); cudaMemcpyAsync(m.stage_dev[sl], b, (size_t) lay.blob_bytes(l), cudaMemcpyHostToDevice, m.copy); ++stats_.experts_dma; } else { // copied to a pinned buffer by the stager (waits only if it is behind), then DMA const uint8_t* hb = m.stager->wait(job_of[j]); - if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[sl], 0); + if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[m.used_of[sl]], 0); cudaMemcpyAsync(m.stage_dev[sl], hb, (size_t) lay.blob_bytes(l), cudaMemcpyHostToDevice, m.copy); m.stager->issued_one(job_of[j], m.copy); } @@ -1841,6 +1849,46 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e ++stats_.experts_streamed; return true; }; + // In the streamed walk an MMQ group is gathered in ONE launch, after ONE wait on its last + // streamed copy (the copy stream is in order), and its ring slots are released by ONE event. A + // wait and a record per expert put ~10 us of GPU bubble each on the compute stream under WDDM + // (226 ms of a 32K prompt on an NVFP4 pack). The same bytes into the same group slots. A ring + // entry the routing skipped inside an open group first gathers what the group holds so far + // (`flush`), so no more than a group's entries are ever held back from the issuer. + // STRATA_PREFILL_GROUP_GATHER=0: one gather, one wait and one record per expert. + static const bool group_env = [] { + const char* v = std::getenv("STRATA_PREFILL_GROUP_GATHER"); + return v == nullptr || std::atoi(v) != 0; + }(); + const bool group_gather = group_env && stream_all && use_mmq && lay.native && + MMQ_GROUP <= mmq::kGatherGroupMax; + mmq::GatherGroup gg; + int gg_slots[MMQ_GROUP]; + int gg_nslots = 0; // ring slots gathered by the next flush + auto flush = [&]() { + if (gg.n <= gg.first) return; + const auto& f = lay.fmt[(size_t) l]; + if (gg_nslots > 0) { // the copies land in order: the last one covers the others + pt.mark(kPfWaitCopy, cs); + cudaStreamWaitEvent(m.cs, m.copied[gg_slots[gg_nslots - 1]], 0); + pt.mark(kPfDequant, cs); + } + if (!mmq::gather_native_group(gg, f.up_off, mmq_gub / 2, f.down_off, mmq_db, m.grp_gu, mmq_gub, + m.grp_d, mmq_db, m.cs)) { + for (int i = gg.first; i < gg.n; ++i) { // not 16-byte aligned: one at a time + const uint8_t* b = gg.blob[i]; + mmq::gather_native(b, b + f.up_off, mmq_gub / 2, b + f.down_off, mmq_db, + m.grp_gu + i * mmq_gub, m.grp_d + i * mmq_db, m.cs); + } + } + if (gg_nslots > 0) { + const int rel = gg_slots[gg_nslots - 1]; + cudaEventRecord(m.used[rel], m.cs); + for (int i = 0; i < gg_nslots; ++i) m.used_of[gg_slots[i]] = rel; + } + gg_nslots = 0; + gg.first = gg.n; + }; // one expert's products from its blob on the device; `slot` (a ring slot, or -1 for a resident // expert) is released once the blob is read auto compute = [&](size_t j, const uint8_t* blob_dev, int slot) -> bool { @@ -1849,14 +1897,21 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e if (use_mmq) { // gather the expert into its group slot (GGUF blocks, unchanged or converted) const size_t q = j % MMQ_GROUP; - if (lay.native) { + if (group_gather) { + gg.blob[q] = blob_dev; + gg.n = (int) q + 1; + if (slot >= 0) gg_slots[gg_nslots++] = slot; + if (q + 1 < MMQ_GROUP && j + 1 < order.size()) return true; + flush(); + gg = mmq::GatherGroup{}; + } else if (lay.native) { const auto& f = lay.fmt[(size_t) l]; mmq::gather_native(blob_dev, blob_dev + f.up_off, mmq_gub / 2, blob_dev + f.down_off, mmq_db, m.grp_gu + q * mmq_gub, m.grp_d + q * mmq_db, m.cs); } else { mmq::gather_strata_q2(blob_dev, m.grp_gu + q * mmq_gub, m.grp_d + q * mmq_db, m.cs); } - if (slot >= 0) cudaEventRecord(m.used[slot], m.cs); + if (slot >= 0 && !group_gather) { cudaEventRecord(m.used[slot], m.cs); m.used_of[slot] = slot; } if (q + 1 < MMQ_GROUP && j + 1 < order.size()) return true; // the group's products: gate/up, swiglu, the group's H to q8_1, down const size_t j0 = j - q, g = j0 / MMQ_GROUP, n = order.size(); @@ -1894,7 +1949,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e } else { blob_dequant_f16(blob_dev, m.dq_gu[q], m.dq_d[q], m.cs); } - if (slot >= 0) cudaEventRecord(m.used[slot], m.cs); + if (slot >= 0) { cudaEventRecord(m.used[slot], m.cs); m.used_of[slot] = slot; } const int64_t o0 = m.off[(size_t) e], ne = m.cnt[(size_t) e]; pt.mark(kPfGemmGU, cs); m.gemm.f16(m.Xs + o0 * N, m.dq_gu[q], m.GU + o0 * 1280, ne, 1280, N); @@ -1928,7 +1983,10 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e const size_t kend = seq_start[(size_t) l + 1]; auto release_to = [&](int32_t e_stop) { while (k < kend && seq[k].e < e_stop) { - cudaEventRecord(m.used[k % (size_t) m.ring], m.cs); + if (gg_nslots > 0) flush(); // the open group's slots get their event first + const int sl = (int) (k % (size_t) m.ring); + cudaEventRecord(m.used[sl], m.cs); + m.used_of[sl] = sl; consumed = ++k; give_back(consumed); } @@ -1938,15 +1996,18 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e release_to(e); if (k < kend && seq[k].e == e) { const int sl = (int) (k % (size_t) m.ring); - pt.mark(kPfWaitCopy, cs); wait_issued(k); - cudaStreamWaitEvent(m.cs, m.copied[sl], 0); + if (!group_gather) { + pt.mark(kPfWaitCopy, cs); + cudaStreamWaitEvent(m.cs, m.copied[sl], 0); + } if (!compute(j, m.stage_dev[sl], sl)) return false; consumed = ++k; - give_back(consumed); + if (!group_gather || gg_nslots == 0) give_back(consumed); // its group was gathered } else { ++stats_.experts_resident; if (!compute(j, m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]), -1)) return false; + if (group_gather && gg_nslots == 0) give_back(consumed); } } release_to(m.g->n_expert); From 41c89b170811dad96060ad3467c5ccea5816e44d Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 2 Oct 2026 20:12:38 +0000 Subject: [PATCH 11/55] prefill: #313 RDNA3 WMMA dense GEMMs (opt-in STRATA_WMMA_GEMM=1), its GEMM part, on gfx1151 too From PR #313 (1e42cf3): src/prefill/wmma_gemm.cu/.h, the Gemm::f16/bf16 hooks before hipBLASLt, the build macro STRATA_WMMA_GFX11 and its parity test; not its prompt attention (STRATA_HIP_WMMA covers it). Fix: the intrinsics guard named only gfx1100/1101/1102 while the runtime gate takes any gfx11, so on gfx1150/gfx1151 mma() compiled to "return c" (silently wrong); it now names gfx1150/gfx1151 too. hip_prefill_wmma_gemm_parity on gfx1151: 3520 cases pass (f16 max_abs 2.4e-7, bf16 0). --- CMakeLists.txt | 8 +- cmake/hip_backend.cmake | 5 + src/prefill/gemm.cu | 22 ++ src/prefill/wmma_gemm.cu | 298 +++++++++++++++++ src/prefill/wmma_gemm.h | 22 ++ tests/hip/prefill_wmma_gemm_parity.cpp | 441 +++++++++++++++++++++++++ 6 files changed, 795 insertions(+), 1 deletion(-) create mode 100644 src/prefill/wmma_gemm.cu create mode 100644 src/prefill/wmma_gemm.h create mode 100644 tests/hip/prefill_wmma_gemm_parity.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 258c21ae..40db3c68 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -400,7 +400,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) # what composes them into a token. No tokenizer - the prompt arrives as ids - because Gate C1 compares logits # against llama.cpp on the SAME ids and a tokenizer on one side of that comparison is a second variable. # plan v0.3 P5: batched prompt processing (tensor-core GEMMs through cuBLAS). - add_library(strata_prefill STATIC src/prefill/gemm.cu src/prefill/kernels.cu src/prefill/prefill.cpp) + add_library(strata_prefill STATIC src/prefill/gemm.cu src/prefill/wmma_gemm.cu src/prefill/kernels.cu src/prefill/prefill.cpp) target_include_directories(strata_prefill PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories}) target_link_libraries(strata_prefill PUBLIC strata_engine ${_strata_gpu_blas_target} ${_strata_gpu_runtime_target}) if(STRATA_ENABLE_HIP AND STRATA_HIPBLASLT_AVAILABLE) @@ -460,6 +460,12 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(hip_gdn_rec_head PRIVATE strata_prefill strata_hip_runtime) add_test(NAME hip_gdn_rec_head COMMAND hip_gdn_rec_head) list(APPEND _strata_hip_tests hip_gdn_rec_head) + # #313: the RDNA3 / RDNA3.5 WMMA dense GEMMs (opt-in STRATA_WMMA_GEMM=1) against a reference + add_executable(hip_prefill_wmma_gemm_parity tests/hip/prefill_wmma_gemm_parity.cpp) + target_include_directories(hip_prefill_wmma_gemm_parity PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src/prefill") + target_link_libraries(hip_prefill_wmma_gemm_parity PRIVATE strata_prefill strata_hip_runtime) + add_test(NAME hip_prefill_wmma_gemm_parity COMMAND hip_prefill_wmma_gemm_parity) + list(APPEND _strata_hip_tests hip_prefill_wmma_gemm_parity) # S6: the AMD fast router against the portable kernel, bitwise add_executable(hip_router_fast tests/hip/router_fast.cpp) target_link_libraries(hip_router_fast PRIVATE strata_kernels strata_hip_runtime) diff --git a/cmake/hip_backend.cmake b/cmake/hip_backend.cmake index 51765606..7fb62ecd 100644 --- a/cmake/hip_backend.cmake +++ b/cmake/hip_backend.cmake @@ -68,6 +68,11 @@ add_library(strata_hip_runtime INTERFACE) target_include_directories(strata_hip_runtime BEFORE INTERFACE "${STRATA_HIP_COMPAT_INCLUDE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/include") target_compile_definitions(strata_hip_runtime INTERFACE STRATA_USE_HIP=1 "STRATA_HIP_ARCHS=\"${STRATA_HIP_ARCHS}\"") +# #313: the RDNA3 WMMA GEMM's intrinsics only compile for gfx11 targets and the host pass does not define +# __gfx11xx__, so the build supplies the macro for gfx11 configs (the kernels also gate on the device at runtime) +if(CMAKE_HIP_ARCHITECTURES MATCHES "gfx11") + target_compile_definitions(strata_hip_runtime INTERFACE STRATA_WMMA_GFX11=1) +endif() target_link_libraries(strata_hip_runtime INTERFACE hip::host) # The shim renames the CUDA runtime to HIP, force-included into every host and device source. On Windows the host # compiler is ROCm's clang++ too (tools/hip/build_windows.bat: CMake refuses to mix cl.exe with Clang HIP), which takes diff --git a/src/prefill/gemm.cu b/src/prefill/gemm.cu index bb6ef045..2cfd6de5 100644 --- a/src/prefill/gemm.cu +++ b/src/prefill/gemm.cu @@ -2,6 +2,10 @@ #include "strata/prefill/gemm.hpp" #include "strata/kernels/dequant_bf16.hpp" +#ifdef STRATA_USE_HIP +#include "wmma_gemm.h" +#endif + #include #include @@ -376,6 +380,16 @@ void Gemm::bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64 float beta) { if (T <= 0 || N <= 0) return; if (ldy <= 0) ldy = N; +#ifdef STRATA_USE_HIP + // #313 (opt-in STRATA_WMMA_GEMM=1; STRATA_WMMA_BF16=0 excludes bf16): RDNA3 / RDNA3.5 WMMA dense GEMM, before + // hipBLASLt; it returns false for shapes it does not take (and off gfx11) and this falls through + static const bool wmma_on = [] { const char* v = std::getenv("STRATA_WMMA_GEMM"); return v && v[0] != 0 && v[0] != '0'; }(); + static const bool bf16_on = [] { const char* v = std::getenv("STRATA_WMMA_BF16"); return !v || (v[0] != 0 && v[0] != '0'); }(); + if (wmma_on && bf16_on && T >= 16 && (beta == 0.0f || beta == 1.0f) && + strata_wmma_gemm_bf16(X, W, Y, T, N, K, ldy, beta, stream_)) { + return; + } +#endif const float alpha = 1.0f; #if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) if (try_hipblaslt(hipblaslt_state_, strata::prefill::hipblaslt::InputType::bf16, X, W, Y, T, N, K, ldy, @@ -396,6 +410,14 @@ void Gemm::f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_ float beta) { if (T <= 0 || N <= 0) return; if (ldy <= 0) ldy = N; +#ifdef STRATA_USE_HIP + // #313 (opt-in STRATA_WMMA_GEMM=1): RDNA3 / RDNA3.5 WMMA dense GEMM, before hipBLASLt (falls through when false) + static const bool wmma_on = [] { const char* v = std::getenv("STRATA_WMMA_GEMM"); return v && v[0] != 0 && v[0] != '0'; }(); + if (wmma_on && T >= 16 && (beta == 0.0f || beta == 1.0f) && + strata_wmma_gemm_f16(X, W, Y, T, N, K, ldy, beta, stream_)) { + return; + } +#endif const float alpha = 1.0f; #if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) if (try_hipblaslt(hipblaslt_state_, strata::prefill::hipblaslt::InputType::f16, X, W, Y, T, N, K, ldy, diff --git a/src/prefill/wmma_gemm.cu b/src/prefill/wmma_gemm.cu new file mode 100644 index 00000000..95af0828 --- /dev/null +++ b/src/prefill/wmma_gemm.cu @@ -0,0 +1,298 @@ +// src/prefill/wmma_gemm.cu - RDNA3 WMMA FP16 & BF16 GEMM for Strata prefill (gfx1100). +// +// Computes Y[t, n] = beta * Y[t, n] + sum_k W[n, k] * X[t, k] using RDNA3 WMMA intrinsics: +// * X is T x K row-major (leading dim K), fp16 or bf16 +// * W is N x K row-major (leading dim K), fp16 or bf16 +// * Y is T x N row-major with leading dimension ldy >= N, fp32 +// +// Hardware: AMD RDNA3 (gfx1100, e.g. RX 7900 XTX) +// * v_wmma_f32_16x16x16_f16_w32 intrinsic (__builtin_amdgcn_wmma_f32_16x16x16_f16_w32) +// * v_wmma_f32_16x16x16_bf16_w32 intrinsic (__builtin_amdgcn_wmma_f32_16x16x16_bf16_w32) +// * Wave32 doubled input fragment: lane t (lane_lo = t & 15) holds row lane_lo of A (16 elements along K) +// and column lane_lo of B (16 elements along K). Lanes 16..31 duplicate lanes 0..15. +// * Wave32 C output mapping: lane t holds column lane_lo of 16x16 output tile, +// with 8 elements alternating rows: row m = 2*i + lane_hi (lane_hi = t >> 4). +// * Tile variants: +// 1. gemm_wmma_64x64_4w: 4 waves (128 threads), 64T x 64N x 16K tile, double-buffered LDS for W. +// 2. gemm_wmma_16x16_1w: 1 wave (32 threads), 16T x 16N x 16K tile, zero LDS/barriers, for small T/N. + +#include "wmma_gemm.h" + +#include +#include +#include + +#include + +// STRATA_WMMA_GFX11 is defined by the BUILD (CMakeLists.txt, from CMAKE_HIP_ARCHITECTURES), not inferred +// from compiler macros: measured on this toolchain the HOST pass of a HIP compile does not define +// __gfx1100__ but does define __HIP_DEVICE_COMPILE__, so a compiler-macro guard here silently selected the +// "return false" stub at the bottom of this file for the very symbol the engine links - the WMMA path then +// never ran, while the same file compiled with hipcc (as the probes do) took the real branch. One +// build-defined macro is uniform across the host and device passes. +#if defined(STRATA_WMMA_GFX11) + +using v8fp32 = float __attribute__((ext_vector_type(8))); + +template +struct WmmaTraits; + +template <> +struct WmmaTraits<_Float16> { + using vec_t = _Float16 __attribute__((ext_vector_type(16))); + __device__ static inline v8fp32 mma(vec_t a, vec_t b, v8fp32 c) { +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__) + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c); +#else + (void) a; (void) b; return c; // not a gfx11 device pass: never launched (runtime gate) +#endif + } +}; + +template <> +struct WmmaTraits<__bf16> { + using vec_t = __bf16 __attribute__((ext_vector_type(16))); + __device__ static inline v8fp32 mma(vec_t a, vec_t b, v8fp32 c) { +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__) + return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a, b, c); +#else + (void) a; (void) b; return c; // not a gfx11 device pass: never launched (runtime gate) +#endif + } +}; + +// =========================================================================== +// Variant 1: 16x16_1w - Single-wave kernel for small T / N. +// Zero LDS, zero barrier synchronization, full register residency. +// =========================================================================== +template +__global__ void gemm_wmma_16x16_1w( + const uint16_t* __restrict__ X, + const uint16_t* __restrict__ W, + float* __restrict__ Y, + int64_t T, int64_t N, int64_t K, int64_t ldy, float beta) { + + using vec_t = typename WmmaTraits::vec_t; + const int m_tile = blockIdx.y * 16; + const int n_tile = blockIdx.x * 16; + if (m_tile >= T || n_tile >= N) return; + + const int lane = threadIdx.x; // 0..31 + const int lane_lo = lane & 15; // 0..15 + const int lane_hi = lane >> 4; // 0 or 1 + + v8fp32 c_acc = {0, 0, 0, 0, 0, 0, 0, 0}; + + const int m_row = m_tile + lane_lo; + const int n_row = n_tile + lane_lo; + + for (int k_tile = 0; k_tile < K; k_tile += 16) { + vec_t a_frag, b_frag; + + if (m_row < T) { + __builtin_memcpy(&a_frag, X + (int64_t)m_row * K + k_tile, sizeof(a_frag)); + } else { + #pragma unroll + for (int i = 0; i < 16; ++i) a_frag[i] = 0; + } + + if (n_row < N) { + __builtin_memcpy(&b_frag, W + (int64_t)n_row * K + k_tile, sizeof(b_frag)); + } else { + #pragma unroll + for (int i = 0; i < 16; ++i) b_frag[i] = 0; + } + + c_acc = WmmaTraits::mma(a_frag, b_frag, c_acc); + } + + const int out_n = n_tile + lane_lo; + if (out_n < N) { + #pragma unroll + for (int i = 0; i < 8; ++i) { + const int out_m = m_tile + 2 * i + lane_hi; + if (out_m < T) { + float* dst = Y + (int64_t)out_m * ldy + out_n; + if (beta == 0.0f) { + *dst = c_acc[i]; + } else { + *dst = beta * (*dst) + c_acc[i]; + } + } + } + } +} + +// =========================================================================== +// Variant 2: 64x64_4w - 4 waves per block (128 threads), 64T x 64N tile. +// Double-buffered LDS tile for W (4 KB LDS total), cooperative 128-bit global loads. +// =========================================================================== +template +__global__ void gemm_wmma_64x64_4w( + const uint16_t* __restrict__ X, + const uint16_t* __restrict__ W, + float* __restrict__ Y, + int64_t T, int64_t N, int64_t K, int64_t ldy, float beta) { + + using vec_t = typename WmmaTraits::vec_t; + const int m_tile = blockIdx.y * 64; + const int n_tile = blockIdx.x * 64; + if (m_tile >= T || n_tile >= N) return; + + const int tid = threadIdx.x; // 0..127 + const int wave_id = tid >> 5; // 0..3 + const int lane = tid & 31; // 0..31 + const int lane_lo = lane & 15; // 0..15 + const int lane_hi = lane >> 4; // 0 or 1 + + // 4 accumulators per wave covering 4 x 16 N-subtiles + v8fp32 c_acc0 = {0, 0, 0, 0, 0, 0, 0, 0}; + v8fp32 c_acc1 = {0, 0, 0, 0, 0, 0, 0, 0}; + v8fp32 c_acc2 = {0, 0, 0, 0, 0, 0, 0, 0}; + v8fp32 c_acc3 = {0, 0, 0, 0, 0, 0, 0, 0}; + + // Double-buffered LDS tile: 64 rows of N x 16 elements of K (2 KB per buffer) + alignas(16) __shared__ ElemT b_lds[2][64][16]; + + // Thread mapping for cooperative loading of W into LDS (128 threads load 64x16 elements) + // Each thread loads 8 halfs (16 bytes = uint4) + const int row_in_tile = tid >> 1; // 0..63 + const int k_sub = (tid & 1) << 3; // 0 or 8 + const int actual_n = n_tile + row_in_tile; + + auto load_w_into_lds = [&](int buf, int k_tile) { + const int actual_k = k_tile + k_sub; + uint4 val = {0, 0, 0, 0}; + if (actual_n < N && actual_k < K) { + const void* ptr = reinterpret_cast(W + (int64_t)actual_n * K + actual_k); + val = *reinterpret_cast(ptr); + } + *reinterpret_cast(&b_lds[buf][row_in_tile][k_sub]) = val; + }; + + // Pre-fill buffer 0 + load_w_into_lds(0, 0); + __syncthreads(); + + const int m_row = m_tile + wave_id * 16 + lane_lo; + int cur_buf = 0; + + for (int k_tile = 0; k_tile < K; k_tile += 16) { + const int next_buf = 1 - cur_buf; + const int k_next = k_tile + 16; + + // Prefetch next K-tile of W into LDS + if (k_next < K) { + load_w_into_lds(next_buf, k_next); + } + + // Load A fragment from X for current wave's 16 M-rows + vec_t a_frag; + if (m_row < T) { + __builtin_memcpy(&a_frag, X + (int64_t)m_row * K + k_tile, sizeof(a_frag)); + } else { + #pragma unroll + for (int i = 0; i < 16; ++i) a_frag[i] = 0; + } + + // Read B fragments from LDS and compute WMMA + vec_t b_frag0, b_frag1, b_frag2, b_frag3; + __builtin_memcpy(&b_frag0, &b_lds[cur_buf][0 + lane_lo][0], sizeof(vec_t)); + __builtin_memcpy(&b_frag1, &b_lds[cur_buf][16 + lane_lo][0], sizeof(vec_t)); + __builtin_memcpy(&b_frag2, &b_lds[cur_buf][32 + lane_lo][0], sizeof(vec_t)); + __builtin_memcpy(&b_frag3, &b_lds[cur_buf][48 + lane_lo][0], sizeof(vec_t)); + + c_acc0 = WmmaTraits::mma(a_frag, b_frag0, c_acc0); + c_acc1 = WmmaTraits::mma(a_frag, b_frag1, c_acc1); + c_acc2 = WmmaTraits::mma(a_frag, b_frag2, c_acc2); + c_acc3 = WmmaTraits::mma(a_frag, b_frag3, c_acc3); + + __syncthreads(); + cur_buf = next_buf; + } + + // Store C to Y (coalesced 64-byte writes per wave half) + const int m_tile_wave = m_tile + wave_id * 16; + auto store_acc = [&](const v8fp32& acc, int n_base) { + const int out_n = n_base + lane_lo; + if (out_n < N) { + #pragma unroll + for (int i = 0; i < 8; ++i) { + const int out_m = m_tile_wave + 2 * i + lane_hi; + if (out_m < T) { + float* dst = Y + (int64_t)out_m * ldy + out_n; + if (beta == 0.0f) { + *dst = acc[i]; + } else { + *dst = beta * (*dst) + acc[i]; + } + } + } + } + }; + + store_acc(c_acc0, n_tile + 0); + store_acc(c_acc1, n_tile + 16); + store_acc(c_acc2, n_tile + 32); + store_acc(c_acc3, n_tile + 48); +} + +template +static inline bool strata_wmma_gemm_dispatch(const uint16_t* X, const uint16_t* W, float* Y, + int64_t T, int64_t N, int64_t K, int64_t ldy, float beta, + void* stream) { + if (!X || !W || !Y) return false; + if (T <= 0 || N <= 0 || K <= 0) return false; + // Runtime gate (review): run only on gfx11 devices, whatever this build compiled for. The build-time + // STRATA_WMMA_GFX11 macro controls whether the intrinsics compile; this check controls whether they run. + { + int dev = 0; + hipDeviceProp_t prop{}; + if (hipGetDevice(&dev) != hipSuccess || hipGetDeviceProperties(&prop, dev) != hipSuccess) return false; + if (std::strncmp(prop.gcnArchName, "gfx11", 5) != 0) return false; + } + if (K % 16 != 0) return false; + if (beta != 0.0f && beta != 1.0f) return false; + if (ldy <= 0) ldy = N; + if (ldy < N) return false; + + hipStream_t s = static_cast(stream); + + if (T >= 32 && N >= 32) { + dim3 block(128); + dim3 grid((uint32_t)((N + 63) / 64), (uint32_t)((T + 63) / 64), 1); + gemm_wmma_64x64_4w<<>>(X, W, Y, T, N, K, ldy, beta); + } else { + dim3 block(32); + dim3 grid((uint32_t)((N + 15) / 16), (uint32_t)((T + 15) / 16), 1); + gemm_wmma_16x16_1w<<>>(X, W, Y, T, N, K, ldy, beta); + } + return true; +} + +bool strata_wmma_gemm_f16(const uint16_t* X, const uint16_t* W, float* Y, + int64_t T, int64_t N, int64_t K, int64_t ldy, float beta, + void* stream) { + return strata_wmma_gemm_dispatch<_Float16>(X, W, Y, T, N, K, ldy, beta, stream); +} + +bool strata_wmma_gemm_bf16(const uint16_t* X, const uint16_t* W, float* Y, + int64_t T, int64_t N, int64_t K, int64_t ldy, float beta, + void* stream) { + return strata_wmma_gemm_dispatch<__bf16>(X, W, Y, T, N, K, ldy, beta, stream); +} + +#else +// Non-HIP / Non-GFX11 compilation fallback +bool strata_wmma_gemm_f16(const uint16_t*, const uint16_t*, float*, + int64_t, int64_t, int64_t, int64_t, float, + void*) { + return false; +} + +bool strata_wmma_gemm_bf16(const uint16_t*, const uint16_t*, float*, + int64_t, int64_t, int64_t, int64_t, float, + void*) { + return false; +} +#endif diff --git a/src/prefill/wmma_gemm.h b/src/prefill/wmma_gemm.h new file mode 100644 index 00000000..49474dfd --- /dev/null +++ b/src/prefill/wmma_gemm.h @@ -0,0 +1,22 @@ +// src/prefill/wmma_gemm.h - RDNA3 WMMA FP16 & BF16 GEMM for Strata prefill. +#pragma once + +#include + +/// Compute Y[t, n] = beta * Y[t, n] + sum_k W[n, k] * X[t, k] using RDNA3 WMMA instructions. +/// X: T x K row-major (leading dim K), fp16 (uint16_t) +/// W: N x K row-major (leading dim K), fp16 (uint16_t) +/// Y: T x N row-major with leading dimension ldy >= N, fp32 (float) +/// Returns true if executed on WMMA, false if unsupported shape/parameters (fall back to hipblas). +bool strata_wmma_gemm_f16(const uint16_t* X, const uint16_t* W, float* Y, + int64_t T, int64_t N, int64_t K, int64_t ldy, float beta, + void* stream = nullptr); + +/// Compute Y[t, n] = beta * Y[t, n] + sum_k W[n, k] * X[t, k] using RDNA3 WMMA instructions. +/// X: T x K row-major (leading dim K), bf16 (uint16_t) +/// W: N x K row-major (leading dim K), bf16 (uint16_t) +/// Y: T x N row-major with leading dimension ldy >= N, fp32 (float) +/// Returns true if executed on WMMA, false if unsupported shape/parameters (fall back to hipblas). +bool strata_wmma_gemm_bf16(const uint16_t* X, const uint16_t* W, float* Y, + int64_t T, int64_t N, int64_t K, int64_t ldy, float beta, + void* stream = nullptr); diff --git a/tests/hip/prefill_wmma_gemm_parity.cpp b/tests/hip/prefill_wmma_gemm_parity.cpp new file mode 100644 index 00000000..bb7c1591 --- /dev/null +++ b/tests/hip/prefill_wmma_gemm_parity.cpp @@ -0,0 +1,441 @@ +// tests/hip/prefill_wmma_gemm_parity.cpp - Numerical parity test for RDNA3 WMMA GEMM kernels. +#include +#include +#include + +#include "wmma_gemm.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// ============================================================================ +// Exact Representability & Parity Rationale: +// +// Inputs (X, W, and initial Y for beta=1) are chosen from discrete binary fractions +// k / 16.0f with integer k in [-8, 8]. +// +// In IEEE 754 half-precision (fp16, 10-bit explicit mantissa) and bfloat16 +// (7-bit explicit mantissa), every such value k * 2^-4 requires at most 4 bits +// of significand and is therefore EXACTLY representable without rounding. +// +// The product of any two such values is an exact integer multiple of 2^-8: +// (a * 2^-4) * (b * 2^-4) = (a * b) * 2^-8 +// with (a * b) in [-64, 64]. +// +// For K <= 80, the sum of K products: +// sum_k (W[n, k] * X[t, k]) = (sum_k a_k * b_k) * 2^-8 +// has a maximum absolute magnitude of 80 * (0.5 * 0.5) = 20.0, and the integer +// numerator cannot exceed 80 * 64 = 5120 (< 2^13). +// +// In IEEE 754 single-precision (fp32, 23-bit explicit mantissa, 24 bits total), +// any integer multiple of 2^-8 up to 20.0 requires at most 13 bits of significand. +// Because the RDNA3 hardware instructions (v_wmma_f32_16x16x16_f16_w32 and +// v_wmma_f32_16x16x16_bf16_w32) accumulate in native FP32 registers, every +// intermediate product and addition has ZERO truncation or rounding error. +// +// Furthermore, floating-point addition of exact binary fractions whose sum fits +// within the mantissa is strictly associative and exact. Consequently, the GPU +// WMMA pipeline and the CPU reference compute identical bitwise results, making +// an exact assertion (max_abs == 0.0f) mathematically legitimate. +// ============================================================================ + +#define HIP_CHECK(call) do { \ + const hipError_t status_ = (call); \ + if (status_ != hipSuccess) { \ + std::fprintf(stderr, "HIP failure at %s:%d: %s: %s\n", __FILE__, __LINE__, #call, hipGetErrorString(status_)); \ + std::exit(2); \ + } \ +} while (0) + +namespace { + +constexpr float kSentinel = -999.5f; + +struct DeviceBuffer { + void* p = nullptr; + explicit DeviceBuffer(size_t bytes) { if (bytes) HIP_CHECK(hipMalloc(&p, bytes)); } + ~DeviceBuffer() { if (p) (void) hipFree(p); } + DeviceBuffer(const DeviceBuffer&) = delete; + DeviceBuffer& operator=(const DeviceBuffer&) = delete; +}; + +uint16_t encode(float value, bool bf16) { + if (bf16) return hip_bfloat16(value).data; + const __half half = __float2half_rn(value); + return static_cast<__half_raw>(half).x; +} + +float decode(uint16_t bits, bool bf16) { + if (bf16) { + const uint32_t u = static_cast(bits) << 16; + float f = 0.0f; + std::memcpy(&f, &u, sizeof(f)); + return f; + } + const __half_raw raw{bits}; + return __half2float(__half(raw)); +} + +struct MismatchRecord { + const char* dtype = ""; + int64_t T = 0, N = 0, K = 0, ldy = 0; + float beta = 0.0f; + int64_t row = 0, col = 0; + float got = 0.0f, ref = 0.0f; + double delta = 0.0; + bool is_padding = false; +}; + +// Independent host CPU reference computed in double precision. +void gemm_reference(const uint16_t* X, const uint16_t* W, const float* initial_Y, float* ref_Y, + int64_t T, int64_t N, int64_t K, int64_t ldy, float beta, bool is_bf16) { + std::vector x_dec((size_t) T * K); + std::vector w_dec((size_t) N * K); + for (size_t i = 0; i < x_dec.size(); ++i) x_dec[i] = decode(X[i], is_bf16); + for (size_t i = 0; i < w_dec.size(); ++i) w_dec[i] = decode(W[i], is_bf16); + + for (int64_t t = 0; t < T; ++t) { + const double* x_row = x_dec.data() + t * K; + for (int64_t n = 0; n < N; ++n) { + const double* w_row = w_dec.data() + n * K; + double sum = 0.0; + for (int64_t k = 0; k < K; ++k) { + sum += x_row[k] * w_row[k]; + } + const size_t out_idx = (size_t) t * ldy + n; + const double y_init = (beta == 0.0f) ? 0.0 : static_cast(initial_Y[out_idx]); + ref_Y[out_idx] = static_cast(beta * y_init + sum); + } + } +} + +enum class CaseStatus { + Passed, + Skipped, + Failed +}; + +CaseStatus run_gemm_case(DeviceBuffer& dx, DeviceBuffer& dw, DeviceBuffer& dy, + hipStream_t stream, bool is_bf16, + int64_t T, int64_t N, int64_t K, int64_t ldy, float beta, + uint32_t seed, double& out_max_abs, + MismatchRecord* first_mismatch, size_t& failure_count) { + const char* dtype_str = is_bf16 ? "bf16" : "f16"; + std::mt19937 rng(seed); + std::uniform_int_distribution dist(-8, 8); + + const size_t x_count = (size_t) T * K; + const size_t w_count = (size_t) N * K; + const size_t y_count = (size_t) T * ldy + 16; // 16 guard floats past end of matrix + + std::vector x(x_count); + std::vector w(w_count); + for (size_t i = 0; i < x_count; ++i) x[i] = encode(dist(rng) * 0.0625f, is_bf16); + for (size_t i = 0; i < w_count; ++i) w[i] = encode(dist(rng) * 0.0625f, is_bf16); + + std::vector initial_y(y_count, kSentinel); + for (int64_t t = 0; t < T; ++t) { + for (int64_t n = 0; n < N; ++n) { + if (beta == 0.0f) { + initial_y[(size_t) t * ldy + n] = -888.25f; + } else { + // beta == 1.0f: pre-fill with a known exact pattern to verify accumulation + initial_y[(size_t) t * ldy + n] = static_cast((t * 5 + n * 3) % 17 - 8) * 0.0625f; + } + } + } + + HIP_CHECK(hipMemcpyAsync(dx.p, x.data(), x_count * sizeof(uint16_t), hipMemcpyHostToDevice, stream)); + HIP_CHECK(hipMemcpyAsync(dw.p, w.data(), w_count * sizeof(uint16_t), hipMemcpyHostToDevice, stream)); + HIP_CHECK(hipMemcpyAsync(dy.p, initial_y.data(), y_count * sizeof(float), hipMemcpyHostToDevice, stream)); + + const bool launched = is_bf16 ? strata_wmma_gemm_bf16(static_cast(dx.p), + static_cast(dw.p), + static_cast(dy.p), + T, N, K, ldy, beta, stream) + : strata_wmma_gemm_f16(static_cast(dx.p), + static_cast(dw.p), + static_cast(dy.p), + T, N, K, ldy, beta, stream); + + if (!launched) { + // Declined by kernel: caller falls back to hipBLAS. Test must SKIP rather than fail. + HIP_CHECK(hipStreamSynchronize(stream)); + return CaseStatus::Skipped; + } + + std::vector got_y(y_count); + HIP_CHECK(hipMemcpyAsync(got_y.data(), dy.p, y_count * sizeof(float), hipMemcpyDeviceToHost, stream)); + HIP_CHECK(hipStreamSynchronize(stream)); + + // 1. Verify padding columns and end guards are untouched. + for (int64_t t = 0; t < T; ++t) { + for (int64_t col = N; col < ldy; ++col) { + const size_t idx = (size_t) t * ldy + col; + if (got_y[idx] != kSentinel) { + failure_count++; + if (first_mismatch && first_mismatch->dtype[0] == '\0') { + *first_mismatch = MismatchRecord{dtype_str, T, N, K, ldy, beta, t, col, + got_y[idx], kSentinel, + std::abs((double) got_y[idx] - (double) kSentinel), true}; + } + std::fprintf(stderr, "FAIL: output touched padding column: dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f row=%ld col=%ld got=%.9g expected=%.9g\n", + dtype_str, T, N, K, ldy, beta, t, col, got_y[idx], kSentinel); + return CaseStatus::Failed; + } + } + } + for (size_t g = (size_t) T * ldy; g < y_count; ++g) { + if (got_y[g] != kSentinel) { + failure_count++; + if (first_mismatch && first_mismatch->dtype[0] == '\0') { + *first_mismatch = MismatchRecord{dtype_str, T, N, K, ldy, beta, -1, (int64_t) g, + got_y[g], kSentinel, + std::abs((double) got_y[g] - (double) kSentinel), true}; + } + std::fprintf(stderr, "FAIL: output touched end guard: dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f index=%zu got=%.9g expected=%.9g\n", + dtype_str, T, N, K, ldy, beta, g, got_y[g], kSentinel); + return CaseStatus::Failed; + } + } + + // 2. Compute reference on CPU and verify exact match. + std::vector ref_y(y_count, kSentinel); + gemm_reference(x.data(), w.data(), initial_y.data(), ref_y.data(), T, N, K, ldy, beta, is_bf16); + + double case_max_abs = 0.0; + for (int64_t t = 0; t < T; ++t) { + for (int64_t n = 0; n < N; ++n) { + const size_t idx = (size_t) t * ldy + n; + if (!std::isfinite(got_y[idx])) { + failure_count++; + if (first_mismatch && first_mismatch->dtype[0] == '\0') { + *first_mismatch = MismatchRecord{dtype_str, T, N, K, ldy, beta, t, n, + got_y[idx], ref_y[idx], 1e30, false}; + } + std::fprintf(stderr, "FAIL: non-finite output: dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f at (%ld, %ld): got=%.9g\n", + dtype_str, T, N, K, ldy, beta, t, n, got_y[idx]); + return CaseStatus::Failed; + } + const double delta = std::abs(static_cast(got_y[idx]) - static_cast(ref_y[idx])); + case_max_abs = std::max(case_max_abs, delta); + // The RDNA3 matrix core accumulates in fp32 but rounds toward zero rather than to nearest, while + // this reference sums in double and rounds to nearest, so a correct result may differ by one ULP + // (measured: every mismatch on this hardware is <= 1 ULP and toward zero). Compare against a + // tolerance of 4 ULP - tight enough to stay diagnostic, since a wrong row, column, stride or tile + // boundary differs by O(value) rather than by 1e-7. STRATA_WMMA_PARITY_EXACT=1 demands bit + // equality for anyone who wants to see the raw deltas. + static const bool exact = std::getenv("STRATA_WMMA_PARITY_EXACT") != nullptr; + const double tol = exact ? 0.0 + : 4.0 * (double)std::numeric_limits::epsilon() * + std::max(1.0, std::abs(static_cast(ref_y[idx]))); + if (delta > tol) { + failure_count++; + if (first_mismatch && first_mismatch->dtype[0] == '\0') { + *first_mismatch = MismatchRecord{dtype_str, T, N, K, ldy, beta, t, n, + got_y[idx], ref_y[idx], delta, false}; + } + std::fprintf(stderr, "FAIL: mismatch: dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f at (%ld, %ld): got=%.9g ref=%.9g delta=%.9g\n", + dtype_str, T, N, K, ldy, beta, t, n, got_y[idx], ref_y[idx], delta); + return CaseStatus::Failed; + } + } + } + + out_max_abs = std::max(out_max_abs, case_max_abs); + return CaseStatus::Passed; +} + +struct DeclinedShape { + int64_t T, N, K, ldy; + float beta; + const char* reason; +}; + +} // namespace + +int main() { + int device = 0; + HIP_CHECK(hipGetDevice(&device)); + hipDeviceProp_t properties{}; + HIP_CHECK(hipGetDeviceProperties(&properties, device)); + std::printf("Device %d: %s (arch %s, warpSize %d)\n", + device, properties.name, properties.gcnArchName, properties.warpSize); + + hipStream_t stream = nullptr; + HIP_CHECK(hipStreamCreateWithFlags(&stream, hipStreamNonBlocking)); + + // Allocate reusable device buffers sized for the maximum test dimensions: + // Max T = 127, Max N = 256, Max K = 80, Max ldy = 256 + 16. + constexpr size_t kMaxXBytes = 127 * 80 * sizeof(uint16_t); + constexpr size_t kMaxWBytes = 256 * 80 * sizeof(uint16_t); + constexpr size_t kMaxYBytes = (127 * (256 + 16) + 64) * sizeof(float); + + DeviceBuffer dx(kMaxXBytes); + DeviceBuffer dw(kMaxWBytes); + DeviceBuffer dy(kMaxYBytes); + + const std::vector k_t_values = {1, 15, 16, 17, 31, 32, 33, 63, 64, 65, 127}; + const std::vector k_n_values = {16, 17, 32, 48, 64, 65, 127, 256}; + const std::vector k_k_values = {16, 32, 48, 64, 80}; + + // Test matrix configurations for (beta, ldy): + // Covers beta=0 (overwrite) and beta=1 (accumulate), with ldy == N and ldy > N. + struct Config { + float beta; + int64_t ldy_offset; + }; + const std::vector kConfigs = { + {0.0f, 0}, // beta=0, packed (ldy == N) + {1.0f, 3}, // beta=1, strided (ldy == N + 3), tests accumulation + padding + {0.0f, 7}, // beta=0, strided (ldy == N + 7), tests overwrite + padding + {1.0f, 0}, // beta=1, packed (ldy == N), tests accumulation in packed layout + }; + + const std::vector kDeclinedShapes = { + // K not a multiple of 16 + {1, 16, 15, 16, 0.0f, "K not multiple of 16 (K=15)"}, + {15, 17, 24, 17, 0.0f, "K not multiple of 16 (K=24)"}, + {32, 32, 35, 32, 1.0f, "K not multiple of 16 (K=35)"}, + {64, 64, 47, 67, 1.0f, "K not multiple of 16 (K=47)"}, + {127, 256, 79, 256, 0.0f, "K not multiple of 16 (K=79)"}, + // ldy < N + {16, 32, 16, 16, 0.0f, "ldy < N (ldy=16, N=32)"}, + {32, 48, 32, 40, 1.0f, "ldy < N (ldy=40, N=48)"}, + // beta not 0 or 1 + {16, 16, 16, 16, 0.5f, "beta not 0 or 1 (beta=0.5)"}, + {32, 32, 32, 32, 2.0f, "beta not 0 or 1 (beta=2.0)"}, + // Non-positive sizes + {0, 16, 16, 16, 0.0f, "T <= 0 (T=0)"}, + {16, 0, 16, 16, 0.0f, "N <= 0 (N=0)"}, + {16, 16, 0, 16, 0.0f, "K <= 0 (K=0)"}, + {-1, 16, 16, 16, 0.0f, "T < 0 (T=-1)"}, + }; + + size_t passed_count = 0; + size_t skipped_count = 0; + size_t failure_count = 0; + double global_max_abs = 0.0; + MismatchRecord first_mismatch{}; + uint32_t case_seed = 0x574d4d41u; + + const bool verbose = (std::getenv("STRATA_TEST_VERBOSE") != nullptr); + + for (bool is_bf16 : {false, true}) { + const char* dtype_str = is_bf16 ? "bf16" : "f16"; + std::printf("Testing strata_wmma_gemm_%s across %zu shapes (%zu execution configs)...\n", + dtype_str, k_t_values.size() * k_n_values.size() * k_k_values.size(), kConfigs.size()); + + for (int64_t T : k_t_values) { + double t_max_abs = 0.0; + size_t t_passed = 0; + size_t t_skipped = 0; + + for (int64_t N : k_n_values) { + for (int64_t K : k_k_values) { + for (const auto& cfg : kConfigs) { + const int64_t ldy = N + cfg.ldy_offset; + double case_max_abs = 0.0; + case_seed = case_seed * 1664525u + 1013904223u; + + const CaseStatus status = run_gemm_case( + dx, dw, dy, stream, is_bf16, T, N, K, ldy, cfg.beta, + case_seed, case_max_abs, &first_mismatch, failure_count); + + if (status == CaseStatus::Passed) { + passed_count++; + t_passed++; + t_max_abs = std::max(t_max_abs, case_max_abs); + global_max_abs = std::max(global_max_abs, case_max_abs); + if (verbose) { + std::printf(" case dtype=%s T=%3ld N=%3ld K=%2ld ldy=%3ld beta=%.1f max_abs=%.9g PASS\n", + dtype_str, T, N, K, ldy, cfg.beta, case_max_abs); + } + } else if (status == CaseStatus::Skipped) { + skipped_count++; + t_skipped++; + if (verbose) { + std::printf(" case dtype=%s T=%3ld N=%3ld K=%2ld ldy=%3ld beta=%.1f SKIP (declined)\n", + dtype_str, T, N, K, ldy, cfg.beta); + } + } else { + // Failed: first_mismatch already recorded and reported to stderr + if (verbose) { + std::printf(" case dtype=%s T=%3ld N=%3ld K=%2ld ldy=%3ld beta=%.1f FAIL\n", + dtype_str, T, N, K, ldy, cfg.beta); + } + } + } + } + } + std::printf(" dtype=%s T=%3ld: %zu passed, %zu skipped, max_abs=%.9g %s\n", + dtype_str, T, t_passed, t_skipped, t_max_abs, + (failure_count == 0) ? "PASS" : "FAIL"); + } + + // Test declined shapes: the kernel must return false and be skipped. + for (const auto& decl : kDeclinedShapes) { + const bool launched = is_bf16 + ? strata_wmma_gemm_bf16(static_cast(dx.p), + static_cast(dw.p), + static_cast(dy.p), + decl.T, decl.N, decl.K, decl.ldy, decl.beta, stream) + : strata_wmma_gemm_f16(static_cast(dx.p), + static_cast(dw.p), + static_cast(dy.p), + decl.T, decl.N, decl.K, decl.ldy, decl.beta, stream); + + if (launched) { + failure_count++; + std::fprintf(stderr, "FAIL: expected kernel to decline shape (%s) dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f but it returned true!\n", + decl.reason, dtype_str, decl.T, decl.N, decl.K, decl.ldy, decl.beta); + } else { + skipped_count++; + if (verbose) { + std::printf(" declined shape correctly rejected (%s): dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f SKIP\n", + decl.reason, dtype_str, decl.T, decl.N, decl.K, decl.ldy, decl.beta); + } + } + } + } + + HIP_CHECK(hipStreamDestroy(stream)); + + if (failure_count > 0) { + if (first_mismatch.dtype[0] != '\0') { + if (first_mismatch.is_padding) { + std::fprintf(stderr, "\nSUMMARY: First mismatch was padding/guard corruption:\n" + " dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f at (%ld, %ld): got=%.9g expected=%.9g\n", + first_mismatch.dtype, first_mismatch.T, first_mismatch.N, first_mismatch.K, + first_mismatch.ldy, first_mismatch.beta, first_mismatch.row, first_mismatch.col, + first_mismatch.got, first_mismatch.ref); + } else { + std::fprintf(stderr, "\nSUMMARY: First mismatch occurred at:\n" + " dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f at (%ld, %ld): got=%.9g ref=%.9g delta=%.9g\n", + first_mismatch.dtype, first_mismatch.T, first_mismatch.N, first_mismatch.K, + first_mismatch.ldy, first_mismatch.beta, first_mismatch.row, first_mismatch.col, + first_mismatch.got, first_mismatch.ref, first_mismatch.delta); + } + } + std::fprintf(stderr, "WMMA GEMM parity FAILED: %zu failures detected, max_abs=%.9g\n", + failure_count, global_max_abs); + return 1; + } + + if (passed_count == 0) { + std::fprintf(stderr, "WMMA GEMM parity FAILED: zero test cases passed (all were declined or skipped)\n"); + return 1; + } + + std::printf("\nWMMA GEMM parity OK: %zu test cases passed, %zu declined shapes skipped, max_abs=%.9g\n", + passed_count, skipped_count, global_max_abs); + return 0; +} From 004b15cd4da6cc3e19c9f89350a047d9554dd440 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 2 Oct 2026 20:13:25 +0000 Subject: [PATCH 12/55] core: #409 unified-memory free-memory accounting (device_free_bytes), its integrated-GPU sizing part From PR #409 (af404df), only device_free_bytes(): on an integrated GPU (cudaDevAttrIntegrated, on HIP hipDeviceAttributeIntegrated; the Ryzen AI Max 8060S) the expert cache sizing and checks count /proc/meminfo MemAvailable less STRATA_UMA_HEADROOM_GIB (6) when that is more than cudaMemGetInfo: the page cache of experts read from the GGUF in place gives way to a device allocation. The PR's aarch64 / DGX Spark CPU parts are not taken. --- include/strata/core/expert_cache.hpp | 6 ++++ include/strata/hip_compat/cuda_runtime.h | 1 + src/core/expert_cache.cpp | 39 ++++++++++++++++++++++++ src/program/generate.cpp | 8 ++--- 4 files changed, 50 insertions(+), 4 deletions(-) diff --git a/include/strata/core/expert_cache.hpp b/include/strata/core/expert_cache.hpp index 4a708355..849083a6 100644 --- a/include/strata/core/expert_cache.hpp +++ b/include/strata/core/expert_cache.hpp @@ -73,6 +73,12 @@ std::vector> rank_learned_profile(int64_t n_layers, bool write_expert_profile(const std::string& path, int64_t n_layers, int64_t n_expert, const std::vector>& ranked, std::string& err); +/// Free device memory for the expert cache. On a unified memory system - one memory for the CPU and the GPU, such as +/// the DGX Spark (GB10); CUDA reports it as cudaDevAttrIntegrated - cudaMemGetInfo counts only MemFree, not the page cache - which, with the experts read from the GGUF in place, is mostly those +/// files' clean pages and gives way to a device allocation. There the figure is MemAvailable less 6 GiB for the OS +/// and the engine's host side (STRATA_UMA_HEADROOM_GIB). Elsewhere it is cudaMemGetInfo's. +size_t device_free_bytes(); + class ExpertCache { public: ExpertCache() = default; diff --git a/include/strata/hip_compat/cuda_runtime.h b/include/strata/hip_compat/cuda_runtime.h index 40c1c79c..f6d55196 100644 --- a/include/strata/hip_compat/cuda_runtime.h +++ b/include/strata/hip_compat/cuda_runtime.h @@ -19,6 +19,7 @@ #define cudaDevAttrClockRate hipDeviceAttributeClockRate #define cudaDevAttrComputeCapabilityMajor hipDeviceAttributeComputeCapabilityMajor #define cudaDevAttrComputeCapabilityMinor hipDeviceAttributeComputeCapabilityMinor +#define cudaDevAttrIntegrated hipDeviceAttributeIntegrated #define cudaDeviceGetAttribute hipDeviceGetAttribute #define cudaDeviceProp hipDeviceProp_t #define cudaDeviceSynchronize hipDeviceSynchronize diff --git a/src/core/expert_cache.cpp b/src/core/expert_cache.cpp index dc644436..8cc1c71f 100644 --- a/src/core/expert_cache.cpp +++ b/src/core/expert_cache.cpp @@ -6,11 +6,49 @@ #include #include #include +#include #include #include namespace strata::core { +// See the header. NVIDIA's DGX Spark Porting Guide (section 5.5, "Memory reporting on UMA systems") recommends the same: +// not to rely on cudaMemGetInfo alone but to count the memory the OS can reclaim. Swap is not counted here (unlike +// NVIDIA's reference snippet): an expert cache that pushes the system into swap would be far slower than a smaller one. +size_t device_free_bytes() { + size_t free_b = 0, total_b = 0; + cudaMemGetInfo(&free_b, &total_b); +#if defined(__linux__) + static const bool unified_memory = [] { + int dev = 0, v = 0; + return cudaGetDevice(&dev) == cudaSuccess && cudaDeviceGetAttribute(&v, cudaDevAttrIntegrated, dev) == cudaSuccess && v; + }(); + if (unified_memory) { + if (FILE* m = std::fopen("/proc/meminfo", "r")) { + char line[256]; + unsigned long long kb = 0; + while (std::fgets(line, sizeof line, m)) + if (std::sscanf(line, "MemAvailable: %llu kB", &kb) == 1) break; + std::fclose(m); + // STRATA_UMA_HEADROOM_GIB: a whole number of GiB, 0..1024; anything else keeps the default 6 (said once) + static const long gib = [] { + const char* h = std::getenv("STRATA_UMA_HEADROOM_GIB"); + if (h == nullptr) return 6L; + char* end = nullptr; + const long v = std::strtol(h, &end, 10); + if (end != h && *end == '\0' && v >= 0 && v <= 1024) return v; + std::fprintf(stderr, "strata: STRATA_UMA_HEADROOM_GIB=%s is not a whole number of GiB (0-1024): using 6\n", h); + return 6L; + }(); + const unsigned long long head = (unsigned long long) gib << 30; + const unsigned long long avail = kb << 10; + if (avail > head && avail - head > free_b) free_b = (size_t) (avail - head); + } + } +#endif + return free_b; +} + bool read_expert_profile(const std::string& path, int64_t n_layers, int64_t n_expert, std::vector>& ranked, int64_t& slots, std::string& err) { std::FILE* f = std::fopen(path.c_str(), "rb"); @@ -180,6 +218,7 @@ bool ExpertCache::open(int64_t n_slots, int64_t n_layers, int64_t n_expert, int6 // and the two numbers are named in the refusal. size_t free_b = 0, total_b = 0; if (cudaMemGetInfo(&free_b, &total_b) == cudaSuccess) { + free_b = device_free_bytes(); // unified memory: what the OS can give back counts (see the header) if ((uint64_t) free_b < want) { char buf[320]; std::snprintf(buf, sizeof buf, diff --git a/src/program/generate.cpp b/src/program/generate.cpp index c447dd76..711f2303 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -2688,7 +2688,7 @@ int main(int argc, char** argv) { const bool auto_cache = o.expert_cache < 0; if (o.expert_cache < 0) { size_t free_b = 0, total_b = 0; - cudaMemGetInfo(&free_b, &total_b); + free_b = strata::core::device_free_bytes(); (void) total_b; // Plan v0.3 P5: the batched prompt path's chunk buffers are allocated later, so they are reserved here - // under WDDM an over-subscribed allocation does not fail, it pages to system memory and crawls. // (with borrowing - the default with a profile - the prompt path lends cache slots instead; `pf_borrow` is @@ -2713,7 +2713,7 @@ int main(int argc, char** argv) { // fails with "device buffers ... do not fit" (with borrowing - the default with a profile - the path lends // slots instead and `prefill_mib` is 0, so only the reserve is checked) size_t free_b = 0, total_b = 0; - cudaMemGetInfo(&free_b, &total_b); + free_b = strata::core::device_free_bytes(); (void) total_b; const int64_t prefill_mib = (o.prefill_chunk > 0 && !pf_borrow) ? 160 + (o.prefill_chunk * 680) / 1024 : 0; const int64_t reserve = ((int64_t) o.vram_reserve_mib + prefill_mib) << 20; const int64_t fit = std::max(((int64_t) free_b - reserve) / (int64_t) strata::kernels::cpu::expert_layout().max_blob, 0); @@ -2733,7 +2733,7 @@ int main(int argc, char** argv) { std::vector sized_slots; if (native_pack && o.expert_cache > 0 && !profile.empty() && !o.expert_cache_per_layer) { size_t free_b = 0, total_b = 0; - cudaMemGetInfo(&free_b, &total_b); + free_b = strata::core::device_free_bytes(); (void) total_b; const auto& lay = strata::kernels::cpu::expert_layout(); const uint64_t budget = (uint64_t) o.expert_cache * lay.max_blob; // what the uniform sizing granted uint64_t used = 0; @@ -2819,7 +2819,7 @@ int main(int argc, char** argv) { cudaMemset(xcache.device_slot(0), 0, (size_t) xcache.bytes()); cudaDeviceSynchronize(); size_t free_b = 0, total_b = 0; - cudaMemGetInfo(&free_b, &total_b); + free_b = strata::core::device_free_bytes(); (void) total_b; const int64_t want = (int64_t) o.vram_reserve_mib << 20; if ((int64_t) free_b >= want - (64ll << 20)) break; // short by (want - free); a figure of 0 only says "at least": the first two such reads give back 1 GiB From aa5754fa06e6eaa9826dd69465bf4f126771246a Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 2 Oct 2026 23:20:14 +0200 Subject: [PATCH 13/55] hip: gfx1151 hipBLASLt table - the prompt GEMM shapes at --prefill 16384 too (T 16383 / 16384) 30 more rows from tools/hip/tune_hipblaslt.cpp on Aurora (90 in all). IQ3_XXS, 64K prompt, the gfx11 fused experts: --prefill 16384 with them 849.2 / 847.0 tok/s vs 8192 803.1 / 824.0 / 829.3. --- tools/hip/gfx1151-hipblaslt-100401.txt | 30 ++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/tools/hip/gfx1151-hipblaslt-100401.txt b/tools/hip/gfx1151-hipblaslt-100401.txt index b39be529..260f983e 100644 --- a/tools/hip/gfx1151-hipblaslt-100401.txt +++ b/tools/hip/gfx1151-hipblaslt-100401.txt @@ -60,3 +60,33 @@ f16 2560 640 2560 8192 2390 f16 512 2560 512 8192 2390 f16 6144 2560 6144 8192 2390 f16 640 2560 640 8192 2390 +bf16 10240 320 10240 16383 1177 +bf16 128 2560 128 16383 1176 +bf16 1 2560 1 16383 1175 +bf16 2560 2560 2560 16383 1177 +bf16 320 10240 320 16383 1176 +bf16 48 2560 96 16383 1176 +bf16 4 10240 4 16383 1174 +bf16 512 2560 512 16383 1177 +f16 10240 2560 10240 16383 2390 +f16 12288 2560 12288 16383 2390 +f16 2560 6144 2560 16383 2390 +f16 2560 640 2560 16383 2390 +f16 512 2560 512 16383 2390 +f16 6144 2560 6144 16383 2390 +f16 640 2560 640 16383 2390 +bf16 10240 320 10240 16384 1177 +bf16 128 2560 128 16384 1177 +bf16 1 2560 1 16384 1174 +bf16 2560 2560 2560 16384 1177 +bf16 320 10240 320 16384 1176 +bf16 48 2560 96 16384 1175 +bf16 4 10240 4 16384 1174 +bf16 512 2560 512 16384 1177 +f16 10240 2560 10240 16384 2390 +f16 12288 2560 12288 16384 2390 +f16 2560 6144 2560 16384 2390 +f16 2560 640 2560 16384 2390 +f16 512 2560 512 16384 2390 +f16 6144 2560 6144 16384 2390 +f16 640 2560 640 16384 2390 From 55b9f8346fd187d513df323dc45792d5a44376d7 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 00:16:45 +0200 Subject: [PATCH 14/55] prefill: the fused layout's smaller MoE buffers only when the native kernels cover EVERY layer fused_layout() (STRATA_PF_FUSED=1) shrinks GU / H / Xq to the fused kernels' needs whenever fused_ring() is true, and fused_ring() was true when ANY layer of a native pack was covered. A pack with an uncovered layer - Unsloth UD-IQ4_XS: 5 layers with Q8_0 down projections - then ran MMQ for those layers at the full chunk in buffers sized for stream_all_min() - 1 tokens: on gfx1151 an 8K prompt answered "!!!!..." and a 64K prompt hung (--prefill 2048: an illegal memory access). Such a pack now keeps MMQ's buffers; its covered layers still take the fused kernels. UD-IQ4_XS 8K retrieval after the fix: 3/3 correct, 837.9 prompt tok/s. (The CUDA path shares this code.) --- src/prefill/prefill.cpp | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index bf7d82e3..54c9cb7e 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -122,12 +122,16 @@ inline bool fused_ring() { if (!fused::enabled()) return false; const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout(); if (!lay.native) return true; - static const bool any = [&lay] { + // EVERY layer: fused_layout() shrinks the MoE buffers to the fused path's needs, so a layer the native kernels do + // not cover (Unsloth UD-IQ4_XS's Q8_0 down projections) would run MMQ in them at the full chunk and overflow them + // (garbage, an illegal memory access or a hung prompt on gfx1151). A pack with such a layer keeps MMQ's buffers; + // its covered layers still take the fused kernels. + static const bool all = [&lay] { for (const auto& f : lay.fmt) - if (fused::native_supported(f.gu_type, f.d_type)) return true; - return false; + if (!fused::native_supported(f.gu_type, f.d_type)) return false; + return !lay.fmt.empty(); }(); - return any; + return all; } // the largest ring: 512 slots; 1024 with the Q2_0 pack's fused experts (P3's smaller buffers, measured there) - the // native packs' fused layers were measured at 512 From 7e363dbebbbe145901c73df8e4a5a3df6581d886 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 00:33:19 +0000 Subject: [PATCH 15/55] prefill: the gfx11 fused prompt-expert grids at 2 blocks per WGP HIP counts a gfx11 WGP (two CUs, which the WMMA prompt-expert kernels use as one in the default WGP mode) as one multiprocessor, and the occupancy query answers 1 block for these kernels where 2 run side by side - so every fused launch (native IQ and Q2_0) ran a 20-block grid on gfx1151, 2 waves per SIMD. wgp_blocks() doubles the query's answer (STRATA_PF_OCC=N sets it, an experiment knob). The same work items and arithmetic: parity passes, fused-vs-MMQ rel RMS unchanged, and the engine's outputs are the same tokens. gfx1151, one layer, 8192 tokens x top 10, IQ3_S / IQ4_NL: blocks per WGP 1: 60.7 ms, 2: 44.7, 3: 49.9, 4: 45.2. Q2_0 (2048 tokens): 13.3 -> 11.4 ms. Engine, UD-IQ4_XS (MTP + vision + speed projection): 64K prompt 819.8 / 823.9 -> 892.4 / 878.8 tok/s, 8K 825.5 / 820.8 -> 874.5 (the other 8K run overlapped a download: 758); outputs identical (drafts 292/516 at 64K, 343/468 at 8K); ledger {32,17,130}, 8K retrieval 3/3. --- src/prefill/moe_fused.cu | 18 ++++++++++++++++-- src/prefill/moe_fused_iq.cu | 18 ++++++++++++++++-- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/src/prefill/moe_fused.cu b/src/prefill/moe_fused.cu index 6b9a68cb..0e21cd3d 100644 --- a/src/prefill/moe_fused.cu +++ b/src/prefill/moe_fused.cu @@ -577,6 +577,20 @@ struct DevInfo { std::mutex g_mu; DevInfo g_dev[32]; +#if defined(__HIPCC__) +// Resident blocks per multiprocessor for the gfx11 WMMA prompt-expert kernels' persistent grids. HIP counts a gfx11 +// WGP (two CUs, which these kernels use as one in the default WGP mode) as one multiprocessor, and the occupancy query +// answers 1 block for these kernels where 2 run side by side - so the grid was half the GPU's room. gfx1151 (20 +// WGPs), 8192 tokens x top 10, IQ3_S / IQ4_NL, one layer: 1 block per WGP 60.7 ms, 2 44.7, 3 49.9, 4 45.2 (the same +// work items and arithmetic: the results do not change). STRATA_PF_OCC=N sets the blocks per WGP (an experiment knob). +static int wgp_blocks(int occ) { + static const int env = [] { + const char* v = std::getenv("STRATA_PF_OCC"); + return v != nullptr ? std::atoi(v) : 0; + }(); + return env > 0 ? env : 2 * std::max(occ, 1); +} +#endif const DevInfo& dev_info() { int dev = 0; cudaGetDevice(&dev); @@ -692,8 +706,8 @@ void experts(const Batch& b, int n_expert, int64_t n, const void* scratch, const // the most tiles the batch can have: every row in it, plus a partial tile per expert const int64_t tiles = (n + kTileRows - 1) / kTileRows + (b.e1 - b.e0); #if defined(__HIPCC__) - const unsigned g_gu = (unsigned) std::min(tiles * (1280 / W_ROWS), (int64_t) d.sms * d.occ_gu); - const unsigned g_d = (unsigned) std::min(tiles * (2560 / W_ROWS), (int64_t) d.sms * d.occ_d); + const unsigned g_gu = (unsigned) std::min(tiles * (1280 / W_ROWS), (int64_t) d.sms * wgp_blocks(d.occ_gu)); + const unsigned g_d = (unsigned) std::min(tiles * (2560 / W_ROWS), (int64_t) d.sms * wgp_blocks(d.occ_d)); expert_w11_kernel<<>>(b, tb, (const uint8_t*) xa, src, (uint8_t*) ha, nullptr); expert_w11_kernel<<>>(b, tb, (const uint8_t*) ha, src, nullptr, dm); #else diff --git a/src/prefill/moe_fused_iq.cu b/src/prefill/moe_fused_iq.cu index 14b02ec8..72c278d7 100644 --- a/src/prefill/moe_fused_iq.cu +++ b/src/prefill/moe_fused_iq.cu @@ -761,6 +761,20 @@ template bool setup_ww(int& occ) { template bool setup_one(int& occ) { return setup_ww(occ) && setup_ww(occ); } #endif +#if defined(__HIPCC__) +// Resident blocks per multiprocessor for the gfx11 WMMA prompt-expert kernels' persistent grids. HIP counts a gfx11 +// WGP (two CUs, which these kernels use as one in the default WGP mode) as one multiprocessor, and the occupancy query +// answers 1 block for these kernels where 2 run side by side - so the grid was half the GPU's room. gfx1151 (20 +// WGPs), 8192 tokens x top 10, IQ3_S / IQ4_NL, one layer: 1 block per WGP 60.7 ms, 2 44.7, 3 49.9, 4 45.2 (the same +// work items and arithmetic: the results do not change). STRATA_PF_OCC=N sets the blocks per WGP (an experiment knob). +static int wgp_blocks(int occ) { + static const int env = [] { + const char* v = std::getenv("STRATA_PF_OCC"); + return v != nullptr ? std::atoi(v) : 0; + }(); + return env > 0 ? env : 2 * std::max(occ, 1); +} +#endif const DevInfo& dev_info() { int dev = 0; cudaGetDevice(&dev); @@ -861,8 +875,8 @@ void experts_native(const Batch& b, const NativeGeom& g, int n_expert, int64_t n #if defined(__HIPCC__) { const int64_t tiles = (n + kTileRows - 1) / kTileRows + (b.e1 - b.e0); - const unsigned g_gu = (unsigned) std::min(tiles * (1280 / NW_ROWS), (int64_t) d.sms * d.occ); - const unsigned g_d = (unsigned) std::min(tiles * (2560 / NW_ROWS), (int64_t) d.sms * d.occ); + const unsigned g_gu = (unsigned) std::min(tiles * (1280 / NW_ROWS), (int64_t) d.sms * wgp_blocks(d.occ)); + const unsigned g_d = (unsigned) std::min(tiles * (2560 / NW_ROWS), (int64_t) d.sms * wgp_blocks(d.occ)); const uint8_t* xa8 = (const uint8_t*) xa; uint8_t* ha8 = (uint8_t*) ha; #define STRATA_NW_GU(T) native_w11_kernel<<>>(b, g, tb, xa8, src, ha8, nullptr) From 96f4065aae49813c855eac0a84269df1d2434c5a Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 01:18:21 +0000 Subject: [PATCH 16/55] HIP: the packed Q8_0 decode layout (opt-in STRATA_Q8_PACKED=1), bitwise A lossless load-time repack of the native dense Q8_0 matrices with 1024 <= n_in <= 4096 and n_out >= 2048 (on UD-IQ4_XS: attn_qkv, attn_gate, attn_q; 84 matrices, +1.87 GiB): the same int8 values in a qs plane and the same fp16 scales in a d plane, 34 bytes per 32 values as before. native_q8_0_mmvq finds a registered matrix by its GGUF-layout pointer (that copy stays: the prompt GEMMs read it) and runs native_q8_0_packed_kernel: 640 persistent workgroups; each thread owns the bytes of the exact layout (block tid/4 + 32 i, ints 2 (tid%4) and +1), reads them as one aligned 8-byte run with streaming loads, and accumulates and reduces in the same order, so every output is bitwise equal to native_small_mmvq_kernel / native_mmvq_multi_kernel (exact layout; with the upstream multi-column layout the GGUF kernels run). gfx1151, S26 standalone harness (8 real UD-IQ4_XS layers per shape rotating, paired HIP events, 15 samples, every layer x 1-5 columns memcmp-equal): attn_qkv +10-12%, attn_gate +11-12%, attn_q +10-11% per call. 6144-wide rows (ssm_out, attn_output) and rows < 2048 are not packed (slower in the engine / standalone). Engine (UD-IQ4_XS, S23's c-u4 config, same binary, env only): output ids identical in all 10 runs; steady output 8K 40.06 vs 39.77 tok/s (3 runs each), 64K 30.94 vs 30.34 (2 each). --- include/strata/core/native_dense.hpp | 3 +- include/strata/kernels/native_mmvq.hpp | 10 ++ src/core/native_dense.cpp | 37 ++++++- src/kernels/cuda/native_mmvq.cu | 147 +++++++++++++++++++++++++ 4 files changed, 195 insertions(+), 2 deletions(-) diff --git a/include/strata/core/native_dense.hpp b/include/strata/core/native_dense.hpp index 8330fac5..9f3a8ad9 100644 --- a/include/strata/core/native_dense.hpp +++ b/include/strata/core/native_dense.hpp @@ -30,10 +30,11 @@ public: /// of `skip` and `load` does not upload the GGUF key over it. A quantized row leaves `skip` unchanged. static bool keep_unquantized_ple_key(const std::string& pack_dir, std::set& skip, std::string& err); uint64_t weight_bytes() const { return bytes_; } - size_t tensor_count() const { return weights_.size(); } + size_t tensor_count() const { return weights_.size() - packed_keys_.size(); } private: std::vector weights_; + std::vector packed_keys_; // GGUF-layout pointers registered with STRATA_Q8_PACKED=1 void* scratch_ = nullptr; uint64_t bytes_ = 0; }; diff --git a/include/strata/kernels/native_mmvq.hpp b/include/strata/kernels/native_mmvq.hpp index 9f69dd94..a8894d73 100644 --- a/include/strata/kernels/native_mmvq.hpp +++ b/include/strata/kernels/native_mmvq.hpp @@ -90,6 +90,16 @@ void native_q5_0_f32(const void* weights, const float* x, void* scratch_q8_1, void native_q8_0_mmvq(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream); +/// STRATA_Q8_PACKED=1 (opt-in): a lossless load-time repack of a Q8_0 matrix into a qs plane (n_out x n_in int8) +/// followed by a d plane (n_out x n_in / 32 fp16), the same bytes (34 per 32 values). A registered matrix's +/// native_q8_0_mmvq calls (keyed by its GGUF-layout device pointer, which stays valid for the prompt path) read the +/// packed copy instead; every output is bitwise equal to the GGUF-layout kernels. +bool native_q8_0_packed_enabled(); +bool native_q8_0_packed_eligible(int n_in, int n_out); +void native_q8_0_pack_host(const void* gguf_blocks, void* out, int n_in, int n_out); +void native_q8_0_packed_register(const void* gguf_weights, const void* packed, int n_in, int n_out); +void native_q8_0_packed_unregister(const void* gguf_weights); + void native_q8_0_f32(const void* weights, const float* x, void* scratch_q8_1, float* y, int n_in, int n_out, int ncols, void* stream); diff --git a/src/core/native_dense.cpp b/src/core/native_dense.cpp index 4a86d48c..c5778e02 100644 --- a/src/core/native_dense.cpp +++ b/src/core/native_dense.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -33,6 +34,7 @@ struct Pending { int type; uint64_t bytes; DevicePtr data; + DevicePtr packed; // STRATA_Q8_PACKED=1 copy, or null }; } @@ -64,6 +66,7 @@ bool NativeDense::keep_unquantized_ple_key(const std::string& pack_dir, std::set } NativeDense::~NativeDense() { + for (const void* p : packed_keys_) strata::kernels::native_q8_0_packed_unregister(p); if (scratch_) cudaFree(scratch_); for (void* p : weights_) cudaFree(p); } @@ -168,7 +171,26 @@ bool NativeDense::load(const std::vector& shards, WeightTable& tabl } max_in = (std::max)(max_in, (int) ref.ne0); total += bytes; - pending.push_back(Pending{&ref, (int) tensor.type, bytes, std::move(data)}); + // STRATA_Q8_PACKED=1: a second, packed copy of an eligible Q8_0 matrix for the decode MMVQ (the GGUF + // copy stays: the prompt path's GEMMs read it). + DevicePtr packed; + if (tensor.type == 8 && tensor.name != "blk.1.ple_key.weight" && // the PLE has its own kernel + strata::kernels::native_q8_0_packed_enabled() && + strata::kernels::native_q8_0_packed_eligible((int) ref.ne0, (int) ref.ne1)) { + std::vector host(bytes); + strata::kernels::native_q8_0_pack_host(gguf.tensor_data(tensor), host.data(), (int) ref.ne0, + (int) ref.ne1); + void* packed_allocation = nullptr; + auto packed_status = cudaMalloc(&packed_allocation, bytes); + packed.reset(packed_allocation); + if (packed_status == cudaSuccess) + packed_status = cudaMemcpy(packed.get(), host.data(), bytes, cudaMemcpyHostToDevice); + if (packed_status != cudaSuccess) { + err = "native dense packed upload " + tensor.name + ": " + cudaGetErrorString(packed_status); + return false; + } + } + pending.push_back(Pending{&ref, (int) tensor.type, bytes, std::move(data), std::move(packed)}); } } if (pending.empty()) { err = "native dense: no supported GDN/QSA matrices in supplied shards"; return false; } @@ -178,12 +200,25 @@ bool NativeDense::load(const std::vector& shards, WeightTable& tabl if (status != cudaSuccess) { err = std::string("native dense scratch: ") + cudaGetErrorString(status); return false; } // All checks and allocations finish before publishing any reference. weights_.reserve(pending.size()); + uint64_t packed_bytes = 0; + size_t packed_count = 0; for (auto& item : pending) { item.ref->native_data = item.data.get(); item.ref->native_type = item.type; item.ref->native_q8_1 = scratch.get(); + if (item.packed) { + strata::kernels::native_q8_0_packed_register(item.data.get(), item.packed.get(), (int) item.ref->ne0, + (int) item.ref->ne1); + packed_keys_.push_back(item.data.get()); + packed_bytes += item.bytes; + ++packed_count; + weights_.push_back(item.packed.release()); + } weights_.push_back(item.data.release()); } + if (packed_count) + std::fprintf(stderr, "native dense: STRATA_Q8_PACKED=1 packed %zu Q8_0 matrices for decode (+%.1f MiB)\n", + packed_count, packed_bytes / 1048576.0); scratch_ = scratch.release(); bytes_ = total; return true; diff --git a/src/kernels/cuda/native_mmvq.cu b/src/kernels/cuda/native_mmvq.cu index e0a4c1bd..eac781e4 100644 --- a/src/kernels/cuda/native_mmvq.cu +++ b/src/kernels/cuda/native_mmvq.cu @@ -30,10 +30,14 @@ #include #include +#include #include +#include +#include #include #include #include +#include namespace strata::kernels { namespace { @@ -1139,8 +1143,150 @@ void small_f32(const void* weights, const float* x, void* scratch_q8_1, small_mmvq(weights, scratch_q8_1, y, n_in, n_out, ncols, stream); } +// ============================ STRATA_Q8_PACKED=1: the packed Q8_0 decode layout (opt-in) ============================ +// +// A lossless load-time repack of a Q8_0 matrix: the SAME int8 values in a qs plane (row-major, n_in bytes per row) +// followed by the SAME fp16 scales in a d plane (row-major, n_in / 32 per row) - no requantization, same bytes. +// The GGUF's 34-byte blocks leave every int 2-byte aligned (load_int_b2 = two 16-bit loads); the planes give each +// thread one aligned 8-byte run, read with streaming (non-temporal) loads. Every thread owns exactly the bytes of +// the ncols = 1 / multi-column EXACT layout (block kbx = tid / 4 + 32 i, ints 2 (tid % 4) and +1), accumulates them +// in the same order with the same expression, and the cross-warp sum and XOR tree are the same: every output is +// BITWISE equal to native_small_mmvq_kernel / native_mmvq_multi_kernel, NC, 4, 1>. +// Eligible: 1024 <= n_in <= 4096 and n_out >= 2048, run as 640 persistent workgroups (a grid-stride over rows, two +// partial buffers). Measured on gfx1151 (S26, 8 real UD-IQ4_XS layers per shape, paired, 1-5 columns): 2560 -> +// 6144/10240/12288 +10-12% per call (engine trace: -10.7% on those calls). 6144 -> 2560 (one workgroup per row) +// was +2-4% standalone but -3% in the engine, and rows < 2048 lose: neither is packed. +#if defined(__HIPCC__) +#define STRATA_Q8P_LOAD(p) __builtin_nontemporal_load(p) +#else +#define STRATA_Q8P_LOAD(p) __ldcs(p) +#endif +constexpr int Q8P_PERSIST_GRID = 640; +constexpr int Q8P_PERSIST_MAX_IN = 4096; + +template +__launch_bounds__(WARPS * WARP, 1) +__global__ void native_q8_0_packed_kernel(const int8_t* __restrict__ qs, const half* __restrict__ dpl, + const Q81Block* __restrict__ x, float* __restrict__ y, + int n_in, int n_out, int row_step) { + const int tid = WARP * int(threadIdx.y) + int(threadIdx.x); + const int nb = n_in / 32; + const int kqs = 2 * (tid % 4); + __shared__ float partial[2][WARPS - 1][NCOLS][WARP]; + int buf = 0; + for (int row = int(blockIdx.x); row < n_out; row += row_step, buf ^= 1) { + float tmp[NCOLS] = {}; + for (int kbx = tid / 4; kbx < nb; kbx += 2 * WARPS * WARP / 8) { + const std::size_t block = std::size_t(row) * nb + kbx; + const int* p = reinterpret_cast(qs + block * 32) + kqs; + const int v0 = STRATA_Q8P_LOAD(p); + const int v1 = STRATA_Q8P_LOAD(p + 1); + const float d0 = dpl[block]; +#pragma unroll + for (int j = 0; j < NCOLS; ++j) { + const Q81Block* xb = x + std::size_t(j) * nb + kbx; + const int* u = reinterpret_cast(xb->qs); + int sumi = 0; + sumi = STRATA_DP4A(v0, u[kqs], sumi); + sumi = STRATA_DP4A(v1, u[kqs + 1], sumi); + const float d1 = __low2float(xb->ds); + tmp[j] += d0 * d1 * float(sumi); + } + } + if (threadIdx.y > 0) { +#pragma unroll + for (int j = 0; j < NCOLS; ++j) partial[buf][threadIdx.y - 1][j][threadIdx.x] = tmp[j]; + } + __syncthreads(); + if (threadIdx.y == 0) { +#pragma unroll + for (int j = 0; j < NCOLS; ++j) { +#pragma unroll + for (int l = 0; l < WARPS - 1; ++l) tmp[j] += partial[buf][l][j][threadIdx.x]; + tmp[j] = warp_sum(tmp[j]); + if (threadIdx.x == 0) y[std::size_t(j) * n_out + row] = tmp[j]; + } + } + } +} + +struct Q8Packed { const int8_t* qs; const half* d; int n_in, n_out; }; +std::unordered_map& q8_packed_registry() { + static std::unordered_map registry; + return registry; +} + +template +void q8_packed_launch(const Q8Packed& w, const Q81Block* x, float* y, cudaStream_t s) { + const bool persist = w.n_in <= Q8P_PERSIST_MAX_IN; + const int grid = persist ? (std::min)(w.n_out, Q8P_PERSIST_GRID) : w.n_out; + native_q8_0_packed_kernel<<>>(w.qs, w.d, x, y, w.n_in, w.n_out, + persist ? grid : w.n_out); +} + +bool q8_packed_mmvq(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) { + auto& registry = q8_packed_registry(); + if (registry.empty() || (ncols > 1 && !g_multi_exact)) return false; // packed = the EXACT layout only + const auto found = registry.find(weights); + if (found == registry.end() || found->second.n_in != n_in || found->second.n_out != n_out) return false; + validate_shape(n_in, ncols, 32); + validate_pointer(x_q8_1); + validate_pointer(y); + validate_stream(stream); + const auto* x = static_cast(x_q8_1); + const auto s = static_cast(stream); + switch (ncols) { + case 1: q8_packed_launch<1>(found->second, x, y, s); break; + case 2: q8_packed_launch<2>(found->second, x, y, s); break; + case 3: q8_packed_launch<3>(found->second, x, y, s); break; + case 4: q8_packed_launch<4>(found->second, x, y, s); break; + case 5: q8_packed_launch<5>(found->second, x, y, s); break; + case 6: q8_packed_launch<6>(found->second, x, y, s); break; + case 7: q8_packed_launch<7>(found->second, x, y, s); break; + case 8: q8_packed_launch<8>(found->second, x, y, s); break; + default: throw std::invalid_argument("native MMVQ requires 1 <= ncols <= 8"); + } + launch_check(); + return true; +} + } // namespace +bool native_q8_0_packed_enabled() { + static const bool enabled = [] { + const char* v = std::getenv("STRATA_Q8_PACKED"); + return v && v[0] == '1' && v[1] == '\0'; + }(); + return enabled; +} + +bool native_q8_0_packed_eligible(int n_in, int n_out) { + return n_in > 0 && n_in % 32 == 0 && n_in / 32 >= 2 * WARPS * WARP / 8 && n_in <= Q8P_PERSIST_MAX_IN && + n_out >= 2048; +} + +void native_q8_0_pack_host(const void* gguf_blocks, void* out, int n_in, int n_out) { + const auto* blocks = static_cast(gguf_blocks); + auto* qs = static_cast(out); + auto* d = reinterpret_cast(qs + std::size_t(n_in) * n_out); + const std::size_t count = std::size_t(n_in / 32) * n_out; + for (std::size_t b = 0; b < count; ++b) { + std::memcpy(qs + b * 32, blocks[b].qs, 32); + std::memcpy(d + b, &blocks[b].d, sizeof(half)); + } +} + +void native_q8_0_packed_register(const void* gguf_weights, const void* packed, int n_in, int n_out) { + validate_pointer(gguf_weights); + validate_pointer(packed); + if (!native_q8_0_packed_eligible(n_in, n_out)) throw std::invalid_argument("Q8_0 packed: ineligible shape"); + const auto* qs = static_cast(packed); + q8_packed_registry()[gguf_weights] = + Q8Packed{qs, reinterpret_cast(qs + std::size_t(n_in) * n_out), n_in, n_out}; +} + +void native_q8_0_packed_unregister(const void* gguf_weights) { q8_packed_registry().erase(gguf_weights); } + void native_mmvq_set_multi_exact(bool exact) { g_multi_exact = exact; } bool native_mmvq_multi_exact() { return g_multi_exact; } @@ -1420,6 +1566,7 @@ void native_q5_0_f32(const void* weights, const float* x, void* scratch_q8_1, void native_q8_0_mmvq(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) { + if (q8_packed_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream)) return; // STRATA_Q8_PACKED=1 tensors small_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); } From 2312c83bfd593f49d2bcbc70874549a0556dc19b Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 01:12:24 +0200 Subject: [PATCH 17/55] Speculation: --lookup-chain (prompt lookup chained after the MTP drafts), --mtp-hnorm stream, draft sources All opt-in; with none of them given the engine runs exactly as before. - --lookup-chain K [--lookup-chain-min M]: after the MTP's drafts, the suffix drafter matches the context plus those drafts and appends up to K of the tokens that followed the match to the same verify window (the window grows to at most 8). Greedy verification keeps the output. Own counts: a stderr line per request and five more DONE fields when on. - include/strata/spec/draft_source.hpp: a DraftSource interface (the request's own text is PromptLookupSource; other sources register in extra_draft_sources() and the longest match wins). - --mtp-hnorm stream: the draft layer's pre_fc_norm_hidden as one RMS per hyper-connection stream (llama.cpp's qwen4exp MTP graph) instead of one over all four (vLLM's qwen4_exp MTP, the default). New kernel native_qsa_rms_norm_grouped; the batched prompt K/V pass follows the switch. - Diagnostics: STRATA_MTP_FULL_HEAD=1 drafts over the whole vocabulary; STRATA_MTP_TOP2=1 counts how often the draft layer's runner-up is the token verify picked where a draft was rejected. --- CMakeLists.txt | 3 +- include/strata/core/mtp.hpp | 11 +++ include/strata/kernels/native_qsa.hpp | 5 + include/strata/spec/draft_source.hpp | 62 ++++++++++++ include/strata/spec/suffix_drafter.hpp | 6 ++ src/core/mtp.cpp | 47 ++++++++- src/kernels/cuda/native_qsa.cu | 40 ++++++++ src/prefill/prefill.cpp | 6 +- src/program/generate.cpp | 132 +++++++++++++++++++++++-- src/spec/draft_source.cpp | 36 +++++++ src/spec/suffix_drafter.cpp | 10 ++ src/spec/suffix_drafter_test.cpp | 17 ++++ 12 files changed, 361 insertions(+), 14 deletions(-) create mode 100644 include/strata/spec/draft_source.hpp create mode 100644 src/spec/draft_source.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 40db3c68..db9f88ac 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -774,7 +774,8 @@ endif() # worse opt-out. `cpu_require_expert_support()` therefore refuses at startup on a CPU without the # features, and the fallback exists for tests, exactly as P2.S3 specifies. # Plan v0.3 P6: speculation components that need no GPU. -add_library(strata_spec STATIC src/spec/suffix_drafter.cpp src/spec/controller.cpp src/spec/draft_policy.cpp) +add_library(strata_spec STATIC src/spec/suffix_drafter.cpp src/spec/controller.cpp src/spec/draft_policy.cpp + src/spec/draft_source.cpp) target_include_directories(strata_spec PUBLIC include) if(STRATA_BUILD_TESTS) add_executable(suffix_drafter_test src/spec/suffix_drafter_test.cpp) diff --git a/include/strata/core/mtp.hpp b/include/strata/core/mtp.hpp index e2084f6d..5163b022 100644 --- a/include/strata/core/mtp.hpp +++ b/include/strata/core/mtp.hpp @@ -48,6 +48,13 @@ public: void set_prompt_len(int64_t n) { prompt_len_ = n; } /// At most this many drafts per round (below max_t - 1): a window longer than the MTP's comes from elsewhere. void set_max_drafts(int k) { max_drafts_ = k; } + /// --mtp-hnorm stream (opt-in; before the first draft or prefill): pre_fc_norm_hidden normalizes each + /// hyper-connection stream on its own, as llama.cpp's qwen4exp MTP graph does, instead of one RMS over all four. + void set_hnorm_per_stream(bool on) { hnorm_stream_ = on; } + bool hnorm_per_stream() const { return hnorm_stream_; } + /// STRATA_MTP_TOP2=1 (diagnostic): draft j's runner-up token in the last draft() (-1 = unknown) + static bool top2_env(); + int32_t top2(int j) const { return j >= 0 && j < (int) top2_.size() ? top2_[(size_t) j] : -1; } uint64_t vram_bytes() const { return vram_; } /// The draft layer's K/V state (read-only: --serve's STRATA_STATE_HASH check hashes it) const QsaState& kv_state() const { return st_; } @@ -130,6 +137,10 @@ private: int max_t_ = 0; int device_ = -1; ///< the device `load` ran on: the public calls switch to it (layer split) int max_drafts_ = 1 << 30; + bool hnorm_stream_ = false; + void record_top2(int j); + std::vector top2_, dvocab_host_; + std::vector lg_host_; int64_t n_vocab_ = 0; uint64_t vram_ = 0; cudaStream_t cs_ = nullptr; diff --git a/include/strata/kernels/native_qsa.hpp b/include/strata/kernels/native_qsa.hpp index c56eb4d2..e789fa3e 100644 --- a/include/strata/kernels/native_qsa.hpp +++ b/include/strata/kernels/native_qsa.hpp @@ -21,6 +21,11 @@ bool native_qsa_enabled(); void native_qsa_rms_norm_weighted(const float* input, const float* gamma, float* output, int n_cols, int n_rows, float epsilon, void* stream); +// The same per row with gamma[n_cols * groups]: row r is normalized on its own and scaled by gamma's slice +// r % groups (the MTP's hidden input, one row per hyper-connection stream: --mtp-hnorm stream). +void native_qsa_rms_norm_grouped(const float* input, const float* gamma, float* output, + int n_cols, int groups, int n_rows, float epsilon, void* stream); + // attn/output [head_dim,n_head]; q_full [2*head_dim,n_head], each row is // [query channels, gate channels]. Output is attn*sigmoid(second-half gate). // Exact output==attn is supported; all other spans must be disjoint. diff --git a/include/strata/spec/draft_source.hpp b/include/strata/spec/draft_source.hpp new file mode 100644 index 00000000..109d3c74 --- /dev/null +++ b/include/strata/spec/draft_source.hpp @@ -0,0 +1,62 @@ +// include/strata/spec/draft_source.hpp - a source of draft tokens beside the MTP layer (--lookup-chain). +// +// A source proposes how the context continues; the verify window checks the proposal, so a source can only change +// the speed, never the output. The engine asks its sources after the MTP has drafted: the context it passes ends +// with those MTP drafts (not yet verified), and whatever a source returns is appended to the same window. +// +// The built-in source is the request's own text (PromptLookupSource: the suffix drafter over prompt + output). +// Other sources (a retrieval store over a codebase or earlier conversations) register with +// extra_draft_sources() before the first request; the engine takes the proposal with the longest match. +#pragma once + +#include "strata/spec/suffix_drafter.hpp" + +#include +#include +#include +#include + +namespace strata::spec { + +class DraftSource { +public: + virtual ~DraftSource() = default; + virtual const char* name() const = 0; + /// A new request starts (its prompt follows through append()). + virtual void reset() {} + /// Committed context, in order: the request's prompt, then every token the verify windows accept. + virtual void append(const int32_t* tokens, size_t n) { (void) tokens; (void) n; } + /// Propose up to `max_k` tokens that follow the context. `tail` holds the context's last `n_tail` tokens (at most + /// 64); its last `n_pending` are drafts not yet verified (never passed to append()). Writes `out`, returns how + /// many (0 = nothing to propose) and sets `*match` to the number of trailing context tokens the proposal is based + /// on (its confidence: the engine requires --lookup-chain-min and prefers the longest). + virtual int propose(const int32_t* tail, int n_tail, int n_pending, int max_k, int32_t* out, int* match) = 0; +}; + +/// The request's own text: the suffix drafter (prompt lookup) behind the DraftSource interface. +class PromptLookupSource final : public DraftSource { +public: + explicit PromptLookupSource(SuffixDrafter& d) : d_(d) {} + const char* name() const override { return "prompt-lookup"; } + void reset() override { d_.reset(); } + void append(const int32_t* tokens, size_t n) override { d_.append(tokens, n); } + int propose(const int32_t* tail, int n_tail, int n_pending, int max_k, int32_t* out, int* match) override { + n_pending = n_pending < n_tail ? n_pending : n_tail; + const int k = d_.propose_after(tail + (n_tail - n_pending), n_pending, max_k, out); + *match = k > 0 ? d_.last_match() : 0; + return k; + } + +private: + SuffixDrafter& d_; +}; + +/// Sources besides the request's own text, asked after it (empty unless something registered one at startup). +std::vector>& extra_draft_sources(); + +/// Ask `own` and then every extra source; the proposal with the longest match of at least `min_match` wins +/// (ties keep the earlier source). Returns its length (0 = none); `*match` and `*source` (index: 0 = own) describe it. +int propose_from_sources(DraftSource& own, const int32_t* tail, int n_tail, int n_pending, int max_k, int min_match, + int32_t* out, int* match, int* source); + +} // namespace strata::spec diff --git a/include/strata/spec/suffix_drafter.hpp b/include/strata/spec/suffix_drafter.hpp index 731bbef1..e84593bf 100644 --- a/include/strata/spec/suffix_drafter.hpp +++ b/include/strata/spec/suffix_drafter.hpp @@ -30,9 +30,15 @@ public: /// Write up to `max_k` proposed next tokens to `out`; returns how many (0 = no match of at least min_match). int propose(int max_k, int32_t* out); + /// --lookup-chain: as propose(), for the history followed by `extra` (the draft head's proposal for the next + /// tokens), so the lookup continues where those drafts end. The history itself is unchanged; the extra tokens are + /// only part of the suffix being matched and may be read back as part of a periodic continuation. + int propose_after(const int32_t* extra, int n_extra, int max_k, int32_t* out); + /// Length of the match behind the last proposal (0 if none). int last_match() const { return last_match_; } size_t size() const { return hist_.size(); } + const std::vector& history() const { return hist_; } private: struct Slot { diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp index e2b89b6f..be57de2f 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -301,9 +301,43 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session return true; } +namespace { +// STRATA_MTP_FULL_HEAD=1 (a diagnostic): draft over the whole vocabulary (the main head itself) instead of +// rt/draft_vocab.bin's subset - the reference head, to measure what the subset costs in acceptance +bool full_head_env() { + static const bool on = [] { const char* v = std::getenv("STRATA_MTP_FULL_HEAD"); return v && v[0] == '1'; }(); + return on; +} +} // namespace + +bool MtpDrafter::top2_env() { + static const bool on = [] { const char* v = std::getenv("STRATA_MTP_TOP2"); return v && v[0] == '1'; }(); + return on; +} + +// STRATA_MTP_TOP2=1 (a diagnostic for tree drafts): draft j's runner-up under the draft layer, from the head logits +// the step just wrote (row 0), on the host. Slow; only for measuring what a second branch would have caught. +void MtpDrafter::record_top2(int j) { + const int64_t nv = dhead_ != nullptr ? n_dvocab_ : n_vocab_; + if ((int64_t) lg_host_.size() < nv) lg_host_.resize((size_t) nv); + if ((int) top2_.size() < max_t_) top2_.assign((size_t) max_t_, -1); + if (j < 0 || j >= max_t_) return; + if (cudaMemcpy(lg_host_.data(), head_logits_, (size_t) nv * sizeof(float), cudaMemcpyDeviceToHost) != cudaSuccess) { + top2_[(size_t) j] = -1; + return; + } + int64_t b1 = -1, b2 = -1; + for (int64_t i = 0; i < nv; ++i) { + const float v = lg_host_[(size_t) i]; + if (b1 < 0 || v > lg_host_[(size_t) b1]) { b2 = b1; b1 = i; } + else if (b2 < 0 || v > lg_host_[(size_t) b2]) b2 = i; + } + top2_[(size_t) j] = b2 < 0 ? -1 : dhead_ != nullptr ? dvocab_host_[(size_t) b2] : (int32_t) b2; +} + uint64_t MtpDrafter::bind_bytes(uint64_t head_row_bytes, int64_t n_vocab) const { uint64_t bytes = head_logits_ ? 0 : (uint64_t) max_t_ * (uint64_t) n_vocab * sizeof(float); - if (dhead_ == nullptr) { + if (dhead_ == nullptr && !full_head_env()) { if (FILE* f = std::fopen((rt_dir_ + "/draft_vocab.bin").c_str(), "rb")) { std::fseek(f, 0, SEEK_END); const long size = std::ftell(f); @@ -426,7 +460,7 @@ bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float return false; } // the draft head's token subset, when tools/draft_vocab.py wrote one - if (dhead_ == nullptr) { + if (dhead_ == nullptr && !full_head_env()) { std::vector raw; if (read_file(rt_dir_ + "/draft_vocab.bin", raw) && raw.size() >= 4 && raw.size() % 4 == 0) { n_dvocab_ = (int64_t) (raw.size() / 4); @@ -438,6 +472,8 @@ bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float return false; } cudaMemcpy(dvocab_, raw.data(), raw.size(), cudaMemcpyHostToDevice); + dvocab_host_.resize((size_t) n_dvocab_); + std::memcpy(dvocab_host_.data(), raw.data(), raw.size()); strata::kernels::gather_rows((const uint8_t*) head->weights(), row_bytes, dvocab_, n_dvocab_, dhead_, nullptr); cudaDeviceSynchronize(); vram_ += (uint64_t) (n_dvocab_ * row_bytes) + raw.size(); @@ -479,7 +515,10 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri native_qsa_rms_norm_weighted(emb_, f32("pre_fc_norm_embedding.weight"), en_, (int) N, T, EPS, cs); native_quantize_q8_1(en_, xq_, (int) N, T, cs); native_mmvq(GGML_Q8_0, q8("fc_embedding.weight"), xq_, e2_, (int) N, (int) N, T, cs); - native_qsa_rms_norm_weighted(Rin_, f32("pre_fc_norm_hidden.weight"), hn_, (int) (HC * N), T, EPS, cs); + if (hnorm_stream_) // --mtp-hnorm stream: one RMS per stream, each scaled by its slice of the weight + native_qsa_rms_norm_grouped(Rin_, f32("pre_fc_norm_hidden.weight"), hn_, (int) N, (int) HC, (int) (T * HC), EPS, cs); + else + native_qsa_rms_norm_weighted(Rin_, f32("pre_fc_norm_hidden.weight"), hn_, (int) (HC * N), T, EPS, cs); for (int c0 = 0; c0 < T * HC; c0 += 8) { const int nc = (int) std::min(8, T * HC - c0); native_quantize_q8_1(hn_ + (size_t) c0 * N, xq_, (int) N, nc, cs); @@ -837,6 +876,7 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t* return false; } drafts[0] = ((volatile int32_t*) h_out_)[0]; + if (top2_env()) record_top2(0); float pj = ((volatile float*) h_prob_)[0]; if (probs) probs[0] = pj; int n = 1; @@ -851,6 +891,7 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t* return false; } drafts[j] = ((volatile int32_t*) h_out_)[j]; + if (top2_env()) record_top2(j); pj = ((volatile float*) h_prob_)[j]; if (probs) probs[j] = pj; ++n; diff --git a/src/kernels/cuda/native_qsa.cu b/src/kernels/cuda/native_qsa.cu index 32e2511c..2e2e1e6b 100644 --- a/src/kernels/cuda/native_qsa.cu +++ b/src/kernels/cuda/native_qsa.cu @@ -66,6 +66,31 @@ __global__ void norm(const float* input, const float* __restrict__ gamma, float* for (std::size_t col = tid; col < std::size_t(n_cols); col += BlockSize) output[col] = scale * input[col] * gamma[col]; } +// As norm, with gamma[groups * n_cols]: row r is group r % groups and reads its own slice of gamma. +template +__global__ void norm_grouped(const float* input, const float* __restrict__ gamma, float* output, + int n_cols, int groups, float epsilon) { + const int tid = threadIdx.x; + const std::size_t row_offset = std::size_t(blockIdx.x) * n_cols; + input += row_offset; output += row_offset; + gamma += std::size_t(blockIdx.x % unsigned(groups)) * n_cols; + float partial = 0.0f; + for (std::size_t col = tid; col < std::size_t(n_cols); col += BlockSize) { + const float x = input[col]; + partial += x * x; + } + __shared__ float sums[32]; + partial = warp_sum(partial); + const int lane = tid % 32; + if (lane == 0) sums[tid / 32] = partial; + __syncthreads(); + partial = lane < BlockSize / 32 ? sums[lane] : 0.0f; + partial = warp_sum(partial); + const float mean = partial / n_cols; + const float scale = rsqrtf(mean + epsilon); + for (std::size_t col = tid; col < std::size_t(n_cols); col += BlockSize) + output[col] = scale * input[col] * gamma[col]; +} __global__ void gate(const float* attn, const float* __restrict__ q_full, float* output, int n_head, int head_dim) { const std::size_t i = std::size_t(blockIdx.x) * blockDim.x + threadIdx.x; @@ -117,6 +142,21 @@ void native_qsa_rms_norm_weighted(const float* input, const float* gamma, float* norm<1024><<(stream)>>>(input, gamma, output, n_cols, epsilon); check_launch(); } +void native_qsa_rms_norm_grouped(const float* input, const float* gamma, float* output, + int n_cols, int groups, int n_rows, float epsilon, void* stream) { + if (groups < 1) throw std::invalid_argument("native QSA requires positive bounded dimensions"); + const auto count = elements(n_cols, n_rows); + if (!std::isfinite(epsilon) || epsilon < 0.0f) + throw std::invalid_argument("native QSA requires finite nonnegative epsilon"); + buffers(input, count * 4, gamma, std::size_t(n_cols) * groups * 4, output, stream); + if (n_cols < 1024) + norm_grouped<256><<(stream)>>>(input, gamma, output, n_cols, + groups, epsilon); + else + norm_grouped<1024><<(stream)>>>(input, gamma, output, n_cols, + groups, epsilon); + check_launch(); +} void native_qsa_gate_apply(const float* attn, const float* q_full, float* output, int n_head, int head_dim, void* stream) { const auto count = elements(head_dim, n_head); diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 54c9cb7e..e4ddd1c1 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -7,6 +7,7 @@ #include "strata/core/layout.hpp" #include "strata/kernels/cpu/expert.hpp" +#include "strata/kernels/native_qsa.hpp" #include "strata/kernels/native_qsa_indexer.hpp" #include "strata/kernels/ngram.hpp" #include "strata/kernels/ple.hpp" @@ -923,7 +924,10 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t if (!q8) to_f16(emb, en16, nb * Nn, m.cs); proj(emb, en16, w_fe, e2, nb, Nn, Nn, 0); cudaMemcpyAsync(hn, R_rows + (size_t) b0 * HCN, (size_t) nb * HCN * 4, cudaMemcpyDeviceToDevice, m.cs); - rms_rows(hn, w_nh, nb, HCN, HCN, EPS, m.cs); + if (mtp.hnorm_per_stream()) // --mtp-hnorm stream: as the drafter's own pass (mtp.cpp) + strata::kernels::native_qsa_rms_norm_grouped(hn, w_nh, hn, (int) Nn, (int) g.hc, (int) (nb * g.hc), EPS, m.cs); + else + rms_rows(hn, w_nh, nb, HCN, HCN, EPS, m.cs); if (!q8) to_f16(hn, hn16, nb * HCN, m.cs); proj(hn, hn16, w_fh, h2, nb * g.hc, Nn, Nn, 1); // every stream through fc_hidden strata::kernels::add_streams_broadcast(h2, e2, Rm, Nn, (int) g.hc, (int) nb, m.cs); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 711f2303..6ce42903 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -53,6 +53,7 @@ #include "strata/program/logits_selection.hpp" #include "strata/program/conv_cache.hpp" #include "strata/spec/draft_policy.hpp" +#include "strata/spec/draft_source.hpp" #include "strata/spec/suffix_drafter.hpp" #include "strata/kernels/cvec.hpp" #include "strata/core/progress.hpp" @@ -410,6 +411,14 @@ struct Options { int suffix_draft = 3; /// The MTP's own window cap (0 = --spec): with --spec 6 --mtp-max-t 4 the long windows come from suffix matches. int mtp_max_t = 0; + /// --lookup-chain K (opt-in, 0 = off): prompt lookup CHAINED after the MTP's proposal. The suffix drafter matches + /// the context followed by the MTP's drafts and appends up to K of the tokens that followed that match to the same + /// verify window (the window grows to at most 8). Greedy verification keeps the output; its own counts are kept. + int lookup_chain = 0; + int lookup_chain_min = 3; ///< --lookup-chain-min M: the shortest match (in tokens, drafts included) it extends on + /// --mtp-hnorm stream (opt-in): the draft layer's pre_fc_norm_hidden normalizes each hyper-connection stream on + /// its own (llama.cpp's qwen4exp MTP graph) instead of one RMS over all four (the default, tools/mtp_probe.py). + bool mtp_hnorm_stream = false; /// A control vector on the residual stream (strata/kernels/cvec.hpp), with llama.cpp's flags: the /// `experimental-speed-projection` profile passes `--control-vector-scaled FILE:1.0 --control-vector-layer-range /// 4 44 --cvec-mode project --cvec-dir per-layer`. None by default; --serve switches a loaded one per request. @@ -508,6 +517,11 @@ void usage() { " --suffix-draft N prompt lookup: draft from an earlier repeat of the last N+ tokens of context\n" " when it pays (default 3; 0 = MTP only)\n" " --mtp-max-t M cap the MTP's windows at M tokens (0 = --spec; longer ones come from suffixes)\n" + " --lookup-chain K opt-in: after the MTP's drafts, add up to K prompt-lookup drafts that continue\n" + " them (the window grows to at most 8; default 0 = off)\n" + " --lookup-chain-min M the shortest context match --lookup-chain extends on (default 3)\n" + " --mtp-hnorm pooled|stream the draft layer's hidden-input norm: one RMS over all four streams\n" + " (default) or one per stream (llama.cpp's MTP graph)\n" " --control-vector-scaled FILE:SCALE[,...] a control vector GGUF on the residual stream (llama.cpp's\n" " format; --control-vector FILE = scale 1). --serve: requests switch it (cvec=0|1)\n" " --control-vector-layer-range A B the layers it follows (inclusive; default 1 .. the last)\n" @@ -584,6 +598,23 @@ void usage() { " does not fit. Same answers as --mmap-experts for the same placement.\n"); } +// --lookup-chain: the context's last tokens for the draft sources (at most 64), the MTP's pending drafts last +int chain_tail(const strata::spec::SuffixDrafter& sfx, const int32_t* pending, int n_pending, std::vector& tail) { + const std::vector& h = sfx.history(); + const int keep = std::max(0, std::min((int) h.size(), 64 - n_pending)); + tail.assign(h.end() - keep, h.end()); + tail.insert(tail.end(), pending, pending + n_pending); + return (int) tail.size(); +} + +// --lookup-chain: the registered extra draft sources (strata/spec/draft_source.hpp) see the committed context too +void extra_sources_reset() { + for (auto& src : strata::spec::extra_draft_sources()) src->reset(); +} +void extra_sources_append(const int32_t* t, size_t n) { + for (auto& src : strata::spec::extra_draft_sources()) src->append(t, n); +} + bool parse_i64_list(const char* s, std::vector& out, std::string& err) { out.clear(); std::string text(s); @@ -1176,6 +1207,16 @@ int main(int argc, char** argv) { else if (a == "--short-read") o.short_read = std::max(0LL, std::atoll(next("--short-read"))); else if (a == "--suffix-draft") o.suffix_draft = std::max(0, std::atoi(next("--suffix-draft"))); else if (a == "--mtp-max-t") o.mtp_max_t = std::max(0, std::atoi(next("--mtp-max-t"))); + else if (a == "--lookup-chain") o.lookup_chain = std::clamp(std::atoi(next("--lookup-chain")), 0, 7); + else if (a == "--lookup-chain-min") o.lookup_chain_min = std::max(3, std::atoi(next("--lookup-chain-min"))); + else if (a == "--mtp-hnorm") { + const std::string v = next("--mtp-hnorm"); + if (v != "pooled" && v != "stream") { + std::fprintf(stderr, "strata generate: --mtp-hnorm takes pooled or stream\n"); + return 2; + } + o.mtp_hnorm_stream = v == "stream"; + } else if (a == "--control-vector") o.cvec_files.push_back({next("--control-vector"), 1.0f}); else if (a == "--control-vector-scaled") { // FILE:SCALE, comma-separated; the LAST colon splits, so a Windows path (C:\...) keeps its drive @@ -1506,6 +1547,11 @@ int main(int argc, char** argv) { o.mtp_max_t = o.spec; o.spec = std::min(o.spec + 2, 8); // kVerifyMaxT } + // --lookup-chain (opt-in): the MTP keeps its windows; a lookup chained after its drafts may lengthen one by up to K + if (o.lookup_chain > 0 && o.spec >= 2) { + if (o.mtp_max_t == 0) o.mtp_max_t = o.spec; + o.spec = std::max(o.spec, std::min(o.mtp_max_t + o.lookup_chain, 8)); // kVerifyMaxT + } strata::core::layer_set_shared_early(!o.shared_late); if (!o.native_preset.empty()) { try { @@ -2520,6 +2566,7 @@ int main(int argc, char** argv) { o.mtp.clear(); } if (!o.mtp.empty()) mtp.set_prompt_len((int64_t) o.tokens.size()); + mtp.set_hnorm_per_stream(o.mtp_hnorm_stream); // --mtp-hnorm stream (opt-in), before any capture // the draft layer is the canonical model's MTP head (512 experts) even when the target is pruned, // so it always sees the canonical geometry; `static` because MtpDrafter keeps a reference static const strata::core::ModelGeometry draft_geometry{}; @@ -5409,12 +5456,21 @@ int main(int argc, char** argv) { std::vector drafts((size_t) S, 0), window((size_t) S), outv((size_t) S); std::vector dprob((size_t) S, 0.0f); std::vector sbuf((size_t) S, 0); - if (o.suffix_draft > 0) { + const bool sfx_on = o.suffix_draft > 0 || o.lookup_chain > 0; + if (sfx_on) { sfx.reset(); for (int64_t t : ids) sfx.append((int32_t) t); } + if (o.lookup_chain > 0) { + extra_sources_reset(); + for (int64_t t : ids) { const int32_t t32 = (int32_t) t; extra_sources_append(&t32, 1); } + } bool first_window = true; int64_t produced_n = 0, sfx_windows = 0, sfx_drafts = 0, sfx_ok = 0; + int64_t chain_windows = 0, chain_drafts = 0, chain_ok = 0; // --lookup-chain's own counts + int64_t t2_rej[8] = {}, t2_hit[8] = {}; // STRATA_MTP_TOP2: rejections inside the MTP drafts by depth, runner-up hits + std::vector cbuf((size_t) S, 0), ctail; + strata::spec::PromptLookupSource lookup_src(sfx); int64_t draft_offered = 0, draft_accepted = 0; // what the session holds once this request is done: the prompt read so far, then every committed token std::vector consumed; @@ -5461,11 +5517,23 @@ int main(int argc, char** argv) { if (pk.lookup) { T = pk.t; from_sfx = true; } } } + // --lookup-chain: what followed an earlier occurrence of the context + the MTP's drafts, after them + int chain_n = 0; + if (o.lookup_chain > 0 && !first_window && !from_sfx && T < S) { + int cm = 0, csrc = -1; + const int nt = chain_tail(sfx, drafts.data(), T - 1, ctail); + chain_n = strata::spec::propose_from_sources(lookup_src, ctail.data(), nt, T - 1, + std::min(o.lookup_chain, S - T), o.lookup_chain_min, + cbuf.data(), &cm, &csrc); + } + const int T_mtp = T; + T += chain_n; const bool timed_round = !first_window; const Clock::time_point round0 = Clock::now(); if (p + T > o.max_context) break; window[0] = x; - for (int i = 1; i < T; ++i) window[(size_t) i] = from_sfx ? sbuf[(size_t) i - 1] : drafts[(size_t) i - 1]; + for (int i = 1; i < T_mtp; ++i) window[(size_t) i] = from_sfx ? sbuf[(size_t) i - 1] : drafts[(size_t) i - 1]; + for (int i = 0; i < chain_n; ++i) window[(size_t) (T_mtp + i)] = cbuf[(size_t) i]; drive.d.layers = 0; drive.d.experts = 0; drive.d.failed = false; @@ -5490,6 +5558,11 @@ int main(int argc, char** argv) { int a = 0; while (a < T - 1 && window[(size_t) a + 1] == outv[(size_t) a]) ++a; if (from_sfx) { ++sfx_windows; sfx_drafts += T - 1; sfx_ok += a; } + if (chain_n > 0) { ++chain_windows; chain_drafts += chain_n; chain_ok += std::max(0, a - (T_mtp - 1)); } + if (strata::core::MtpDrafter::top2_env() && !from_sfx && !first_window && a < T_mtp - 1 && a < 8) { + ++t2_rej[a]; + if (mtp.top2(a) == outv[(size_t) a]) ++t2_hit[a]; + } const Clock::time_point tw1 = Clock::now(); std::thread adapt_thr; // the adaptive tier beside the commit and the draft (as in generate) bool adapt_ok = true; @@ -5510,7 +5583,8 @@ int main(int argc, char** argv) { std::printf("T %d\n", (int) outv[(size_t) i]); strata::core::progress_beat(); ++produced_n; - if (o.suffix_draft > 0) sfx.append(outv[(size_t) i]); + if (sfx_on) sfx.append(outv[(size_t) i]); + if (o.lookup_chain > 0) extra_sources_append(&outv[(size_t) i], 1); eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outv[(size_t) i]) != o.eos_ids.end(); } std::fflush(stdout); @@ -5537,7 +5611,7 @@ int main(int argc, char** argv) { std::printf("ERR %s\n", err.c_str()); return 1; } - if (timed_round && !eos) + if (timed_round && !eos && chain_n == 0) // a chained window is neither an MTP nor a lookup window policy.observe(from_sfx, T, a, sfx_match, std::chrono::duration(Clock::now() - round0).count()); if (eos) { finish = "stop"; break; } @@ -5692,11 +5766,17 @@ int main(int argc, char** argv) { // DONE [hits] [lookups] // [RAM blobs] [file blobs] [file MB] (CS-T tiers; appended, so an older server reads the rest) // [prompt tokens read] (#471: fewer than - when a cancel stopped the read) - std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld %lld %lld %.1f %lld\n", (long long) produced_n, + // [lookup-chain accepted] [lookup-chain offered] [suffix accepted] [suffix offered] [windows] + // (only with --lookup-chain) + char chain_txt[128] = ""; + if (o.lookup_chain > 0) + std::snprintf(chain_txt, sizeof(chain_txt), " %lld %lld %lld %lld %lld", (long long) chain_ok, + (long long) chain_drafts, (long long) sfx_ok, (long long) sfx_drafts, (long long) dec_windows); + std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld %lld %lld %.1f %lld%s\n", (long long) produced_n, (long long) n, prompt_ms, decode_ms, finish, (long long) draft_accepted, (long long) draft_offered, (long long) resume, (long long) req_hits, (long long) req_look, (long long) (src.ram_reads() - ram0), (long long) (src.file_reads() - files0), - (double) (src.file_read_bytes() - file_bytes0) / 1e6, (long long) read_n); + (double) (src.file_read_bytes() - file_bytes0) / 1e6, (long long) read_n, chain_txt); std::fflush(stdout); if (drive.routing != nullptr) std::fflush(drive.routing); // the routing trace survives a crash and is watchable mid-session // "12288 of 98179" when cancelled mid-read (#471), the rate from what was read @@ -5759,6 +5839,14 @@ int main(int argc, char** argv) { if (sfx_windows > 0) std::fprintf(stderr, "strata serve: suffix drafts: %lld windows, %lld of %lld drafts accepted\n", (long long) sfx_windows, (long long) sfx_ok, (long long) sfx_drafts); + if (o.lookup_chain > 0) + std::fprintf(stderr, "strata serve: lookup chain: %lld of %lld windows, %lld of %lld chained drafts accepted\n", + (long long) chain_windows, (long long) dec_windows, (long long) chain_ok, (long long) chain_drafts); + if (strata::core::MtpDrafter::top2_env()) + std::fprintf(stderr, "strata serve: mtp top2: rejected/runner-up by depth %lld/%lld %lld/%lld %lld/%lld %lld/%lld " + "of %lld windows\n", (long long) t2_rej[0], (long long) t2_hit[0], (long long) t2_rej[1], + (long long) t2_hit[1], (long long) t2_rej[2], (long long) t2_hit[2], (long long) t2_rej[3], + (long long) t2_hit[3], (long long) dec_windows); for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) std::fprintf(stderr, "strata serve: CUDA%d: %lld expert entries, %lld active layer launches, %.1f MiB returned " "(%.1f MiB with full rows) in this request; host %.0f ms staging+launching, %.0f ms " @@ -6252,10 +6340,19 @@ int main(int argc, char** argv) { strata::spec::DraftPolicy policy(o.spec); // MTP or lookup window (see draft_policy.hpp) std::vector sbuf((size_t) o.spec, 0); int64_t sfx_windows = 0, sfx_drafts = 0, sfx_ok = 0; - if (o.suffix_draft > 0) { + int64_t chain_windows = 0, chain_drafts = 0, chain_ok = 0; // --lookup-chain's own counts + std::vector cbuf((size_t) o.spec, 0), ctail; + strata::spec::PromptLookupSource lookup_src(sfx); + const bool sfx_on = o.suffix_draft > 0 || o.lookup_chain > 0; + if (sfx_on) { for (int64_t t : o.tokens) sfx.append((int32_t) t); for (int64_t t : produced) sfx.append((int32_t) t); } + if (o.lookup_chain > 0) { + extra_sources_reset(); + for (int64_t t : o.tokens) { const int32_t t32 = (int32_t) t; extra_sources_append(&t32, 1); } + for (int64_t t : produced) { const int32_t t32 = (int32_t) t; extra_sources_append(&t32, 1); } + } const double pool_ms0 = drive.cpu_ms; const int64_t misses0 = drive.d.multi_misses, entries0 = drive.d.multi_entries; while ((int64_t) produced.size() < o.max_new) { @@ -6276,6 +6373,17 @@ int main(int argc, char** argv) { if (pk.lookup) { T = pk.t; from_sfx = true; } } } + // --lookup-chain: what followed an earlier occurrence of the context + the MTP's drafts, after them + int chain_n = 0; + if (o.lookup_chain > 0 && use_mtp && !first_window && !from_sfx && T < o.spec) { + int cm = 0, csrc = -1; + const int nt = chain_tail(sfx, drafts.data(), T - 1, ctail); + chain_n = strata::spec::propose_from_sources(lookup_src, ctail.data(), nt, T - 1, + std::min(o.lookup_chain, o.spec - T), o.lookup_chain_min, + cbuf.data(), &cm, &csrc); + } + const int T_mtp = T; + T += chain_n; const bool timed_round = !first_window; ++window_hist[(size_t) T]; if (p + T > o.max_context) { @@ -6287,6 +6395,7 @@ int main(int argc, char** argv) { const size_t at = produced.size() - 1 + (size_t) i; int32_t d = from_sfx ? sbuf[(size_t) i - 1] : use_mtp ? drafts[(size_t) i - 1] : at < oracle.size() ? (int32_t) oracle[at] : 0; + if (i >= T_mtp) d = cbuf[(size_t) (i - T_mtp)]; if (o.spec_corrupt > 0 && (++corrupt_counter % o.spec_corrupt) == 0) d = (d + 1) % (int32_t) n_vocab; window[(size_t) i] = d; } @@ -6336,10 +6445,12 @@ int main(int argc, char** argv) { drafts_ok += a; ++accepted_hist[(size_t) a]; if (from_sfx) { ++sfx_windows; sfx_drafts += T - 1; sfx_ok += a; } + if (chain_n > 0) { ++chain_windows; chain_drafts += chain_n; chain_ok += std::max(0, a - (T_mtp - 1)); } bool eos = false; for (int i = 0; i <= a && (int64_t) produced.size() < o.max_new && !eos; ++i) { produced.push_back(outv[(size_t) i]); - if (o.suffix_draft > 0) sfx.append(outv[(size_t) i]); + if (sfx_on) sfx.append(outv[(size_t) i]); + if (o.lookup_chain > 0) extra_sources_append(&outv[(size_t) i], 1); eos = o.stop_eos && std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outv[(size_t) i]) != o.eos_ids.end(); } if (eos) { @@ -6359,7 +6470,7 @@ int main(int argc, char** argv) { p += a + 1; const double round_ms = std::chrono::duration(Clock::now() - t0).count(); total_ms += round_ms; - if (timed_round) policy.observe(from_sfx, T, a, sfx_match, round_ms); + if (timed_round && chain_n == 0) policy.observe(from_sfx, T, a, sfx_match, round_ms); if (rounds % 64 == 0) std::fprintf(stderr, "strata generate: position %lld, %lld tokens, %lld rounds\n", (long long) p, (long long) produced.size(), (long long) rounds); @@ -6381,6 +6492,9 @@ int main(int argc, char** argv) { if (o.suffix_draft > 0) std::printf("%-24s %lld windows, drafts accepted %lld of %lld\n", "suffix drafts", (long long) sfx_windows, (long long) sfx_ok, (long long) sfx_drafts); + if (o.lookup_chain > 0) + std::printf("%-24s %lld windows, chained drafts accepted %lld of %lld\n", "lookup chain", + (long long) chain_windows, (long long) chain_ok, (long long) chain_drafts); std::printf("%-24s", "accepted per round"); for (size_t i = 0; i < accepted_hist.size(); ++i) std::printf(" %zu:%lld", i, (long long) accepted_hist[i]); std::printf("\n"); diff --git a/src/spec/draft_source.cpp b/src/spec/draft_source.cpp new file mode 100644 index 00000000..2fcbc406 --- /dev/null +++ b/src/spec/draft_source.cpp @@ -0,0 +1,36 @@ +// src/spec/draft_source.cpp - see include/strata/spec/draft_source.hpp. +#include "strata/spec/draft_source.hpp" + +#include + +namespace strata::spec { + +std::vector>& extra_draft_sources() { + static std::vector> sources; + return sources; +} + +int propose_from_sources(DraftSource& own, const int32_t* tail, int n_tail, int n_pending, int max_k, int min_match, + int32_t* out, int* match, int* source) { + *match = 0; + *source = -1; + if (max_k <= 0) return 0; + int best = 0; + std::vector buf((size_t) max_k); + auto ask = [&](DraftSource& s, int index) { + int m = 0; + const int k = s.propose(tail, n_tail, n_pending, max_k, buf.data(), &m); + if (k <= 0 || m < min_match || m <= *match) return; + for (int i = 0; i < k && i < max_k; ++i) out[i] = buf[(size_t) i]; + best = k < max_k ? k : max_k; + *match = m; + *source = index; + }; + ask(own, 0); + int index = 1; + for (auto& s : extra_draft_sources()) + if (s) ask(*s, index++); + return best; +} + +} // namespace strata::spec diff --git a/src/spec/suffix_drafter.cpp b/src/spec/suffix_drafter.cpp index 6f04f76d..86c7da15 100644 --- a/src/spec/suffix_drafter.cpp +++ b/src/spec/suffix_drafter.cpp @@ -85,4 +85,14 @@ int SuffixDrafter::propose(int max_k, int32_t* out) { return k; } +int SuffixDrafter::propose_after(const int32_t* extra, int n_extra, int max_k, int32_t* out) { + if (n_extra <= 0) return propose(max_k, out); + // the index holds the history's trigrams only: appended without indexing, the extra tokens just form the suffix + const size_t n0 = hist_.size(); + hist_.insert(hist_.end(), extra, extra + n_extra); + const int k = propose(max_k, out); + hist_.resize(n0); + return k; +} + } // namespace strata::spec diff --git a/src/spec/suffix_drafter_test.cpp b/src/spec/suffix_drafter_test.cpp index 9fa8611e..79dc1532 100644 --- a/src/spec/suffix_drafter_test.cpp +++ b/src/spec/suffix_drafter_test.cpp @@ -111,6 +111,23 @@ void unit_tests() { int32_t out[4]; check(d.propose(4, out) > 0, "propose after overflow of nominal capacity"); } + { + // --lookup-chain: the match continues from the drafts appended to the history, which stays unchanged + SuffixDrafter d(3, 32, 256); + const int32_t hist[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 50, 51, 52, 1, 2}; + d.append(hist, sizeof(hist) / sizeof(hist[0])); + const int32_t drafts[] = {3, 4}; + int32_t out[8] = {}; + const int k = d.propose_after(drafts, 2, 3, out); + check(k == 3 && out[0] == 5 && out[1] == 6 && out[2] == 7, "propose_after continues after the drafts"); + check(d.last_match() >= 4, "propose_after match length counts the drafts"); + check(d.size() == sizeof(hist) / sizeof(hist[0]), "propose_after leaves the history unchanged"); + const int32_t miss[] = {99, 98, 97}; + check(d.propose_after(miss, 3, 3, out) == 0, "propose_after without a match proposes nothing"); + // the plain proposal is unaffected: the history's own suffix (52, 1, 2) has no earlier occurrence + check(d.propose(3, out) == 0, "propose after propose_after"); + check(d.propose_after(nullptr, 0, 3, out) == d.propose(3, out), "propose_after with no drafts == propose"); + } std::printf("suffix_drafter unit tests: %s\n", g_fail ? "FAILED" : "OK"); } } // namespace From e35a061f1dda425e624d4731d5a162b9e113ea2e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 02:06:12 +0200 Subject: [PATCH 18/55] MTP draft head: --mtp-q4 (4-bit projections and draft head) and --mtp-draft-vocab FILE Both opt-in; drafts only, the verify window decides every token (18/18 prompts identical on IQ3_XXS). - --mtp-q4: the draft layer's ten Q8_0 projections (fc_embedding/fc_hidden, q/k/v/o, the shared expert) and the draft head's subset rows are requantized to Q4_0 at load/bind with ggml's reference quantizer (native-experts builds). The prompt path's batched K/V pass keeps the Q8_0 originals. - --mtp-draft-vocab FILE: the draft head's token subset from FILE instead of /draft_vocab.bin (data/draft_vocab_en.bin: 40,525 tokens instead of 106,299). RTX 5070, IQ3_XXS (head Q5_K), 18 prompts: draft ms per window 2.55 -> 2.23 (q4), 2.13 (en), 1.91 (both); tokens per step 2.64 -> 2.63 / 2.67 / 2.57. --- include/strata/core/mtp.hpp | 17 ++++++ src/core/mtp.cpp | 110 ++++++++++++++++++++++++++++++++---- src/program/generate.cpp | 10 ++++ 3 files changed, 125 insertions(+), 12 deletions(-) diff --git a/include/strata/core/mtp.hpp b/include/strata/core/mtp.hpp index 5163b022..8f290a73 100644 --- a/include/strata/core/mtp.hpp +++ b/include/strata/core/mtp.hpp @@ -52,6 +52,13 @@ public: /// hyper-connection stream on its own, as llama.cpp's qwen4exp MTP graph does, instead of one RMS over all four. void set_hnorm_per_stream(bool on) { hnorm_stream_ = on; } bool hnorm_per_stream() const { return hnorm_stream_; } + /// --mtp-q4 (opt-in; before load): the draft layer's Q8_0 projections and its draft head run from 4-bit (Q4_0) + /// copies made at load/bind - fewer bytes per draft step; drafts only, the verify window decides every token. + /// (The prompt path's batched K/V pass keeps the Q8_0 originals.) + void set_q4(bool on) { q4_ = on; } + /// --mtp-draft-vocab FILE (opt-in; before bind): the draft head's token subset from FILE instead of + /// rt/draft_vocab.bin (e.g. data/draft_vocab_en.bin, 40K tokens) + void set_draft_vocab(const std::string& path) { dvocab_path_ = path; } /// STRATA_MTP_TOP2=1 (diagnostic): draft j's runner-up token in the last draft() (-1 = unknown) static bool top2_env(); int32_t top2(int j) const { return j >= 0 && j < (int) top2_.size() ? top2_[(size_t) j] : -1; } @@ -138,6 +145,16 @@ private: int device_ = -1; ///< the device `load` ran on: the public calls switch to it (layer split) int max_drafts_ = 1 << 30; bool hnorm_stream_ = false; + bool q4_ = false; + uint8_t* dense4_ = nullptr; ///< --mtp-q4: Q4_0 copies of the Q8_0 tensors + std::vector> q4_off_; + int dhead_type_ = -1; ///< the draft head subset's ggml type (the main head's, or Q4_0) + std::string dvocab_path_; + std::string vocab_file() const { return dvocab_path_.empty() ? rt_dir_ + "/draft_vocab.bin" : dvocab_path_; } + /// a projection's weights for the draft layer's own pass: the Q4_0 copy under --mtp-q4, else the Q8_0 original + const void* wq(const char* name, int& type) const; + bool make_q4_dense(const std::vector& blob, std::string& err); + bool make_q4_head(std::string& err); void record_top2(int j); std::vector top2_, dvocab_host_; std::vector lg_host_; diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp index be57de2f..d2f60518 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -36,11 +36,16 @@ #include #include +#ifdef STRATA_NATIVE_EXPERTS +#include "ggml.h" // --mtp-q4: the head rows' and projections' formats, dequantized and requantized at load +#endif + namespace strata::core { namespace { constexpr float EPS = 1e-6f; constexpr int GGML_Q8_0 = 8; +constexpr int GGML_Q4_0 = 2; using Clock = std::chrono::steady_clock; double ms_since(Clock::time_point t) { return std::chrono::duration(Clock::now() - t).count(); } @@ -104,6 +109,7 @@ MtpDrafter::~MtpDrafter() { for (auto& e : prefill_exec_) if (e) cudaGraphExecDestroy(e); for (auto& e : prefill_dev_exec_) if (e) cudaGraphExecDestroy(e); if (pf_dev_) cudaFree(pf_dev_); + if (dense4_) cudaFree(dense4_); for (auto& e : round_exec_) if (e) cudaGraphExecDestroy(e); for (auto& e : step_exec_) if (e) cudaGraphExecDestroy(e); for (auto& e : round_exec_c_) if (e) cudaGraphExecDestroy(e); @@ -138,6 +144,74 @@ const void* MtpDrafter::q8(const char* name) const { for (const auto& t : tensors_) if (t.name == name && t.kind == "q8_0") return dense_ + t.off; return nullptr; } +const void* MtpDrafter::wq(const char* name, int& type) const { + if (dense4_ != nullptr) + for (const auto& e : q4_off_) + if (e.first == name) { type = GGML_Q4_0; return dense4_ + e.second; } + type = GGML_Q8_0; + return q8(name); +} + +// --mtp-q4: every Q8_0 tensor of dense.bin as Q4_0 (ggml's reference quantizer), in one device buffer +bool MtpDrafter::make_q4_dense(const std::vector& blob, std::string& err) { +#ifdef STRATA_NATIVE_EXPERTS + uint64_t total = 0; + std::vector> plan; + for (const auto& t : tensors_) { + if (t.kind != "q8_0" || t.cols % 32 != 0) continue; + plan.push_back({&t, total}); + total += ((uint64_t) t.rows * (uint64_t) (t.cols / 32) * 18 + 255) & ~255ull; + } + std::vector host((size_t) total); + std::vector row; + const auto* q8t = ggml_get_type_traits(GGML_TYPE_Q8_0); + for (const auto& [t, off] : plan) { + row.resize((size_t) t->cols); + const uint64_t in_row = (uint64_t) (t->cols / 32) * 34, out_row = (uint64_t) (t->cols / 32) * 18; + for (int64_t r = 0; r < t->rows; ++r) { + q8t->to_float(blob.data() + t->off + (uint64_t) r * in_row, row.data(), t->cols); + ggml_quantize_chunk(GGML_TYPE_Q4_0, row.data(), host.data() + off + (uint64_t) r * out_row, 0, 1, t->cols, + nullptr); + } + q4_off_.push_back({t->name, off}); + } + if (cudaMalloc((void**) &dense4_, (size_t) total) != cudaSuccess) { err = "mtp: the Q4_0 projections do not fit"; return false; } + cudaMemcpy(dense4_, host.data(), (size_t) total, cudaMemcpyHostToDevice); + vram_ += total; + std::fprintf(stderr, "strata mtp: --mtp-q4: %zu projections as Q4_0 (%.1f MiB)\n", plan.size(), (double) total / 1048576.0); + return true; +#else + (void) blob; + err = "mtp: --mtp-q4 needs a build with native experts (ggml)"; + return false; +#endif +} + +// --mtp-q4: the draft head's subset rows as Q4_0 (dequantized from the main head's format) +bool MtpDrafter::make_q4_head(std::string& err) { +#ifdef STRATA_NATIVE_EXPERTS + const int64_t N = g_->n_embd; + const auto* tt = ggml_get_type_traits((ggml_type) head_->type()); + if (tt == nullptr || tt->to_float == nullptr || N % 32 != 0) { err = "mtp: --mtp-q4 cannot read the head's format"; return false; } + const size_t in_row = head_->row_bytes(), out_row = (size_t) (N / 32) * 18; + std::vector src((size_t) n_dvocab_ * in_row), dst((size_t) n_dvocab_ * out_row); + if (cudaMemcpy(src.data(), dhead_, src.size(), cudaMemcpyDeviceToHost) != cudaSuccess) { err = "mtp: reading the draft head"; return false; } + std::vector row((size_t) N); + for (int64_t r = 0; r < n_dvocab_; ++r) { + tt->to_float(src.data() + (size_t) r * in_row, row.data(), N); + ggml_quantize_chunk(GGML_TYPE_Q4_0, row.data(), dst.data() + (size_t) r * out_row, 0, 1, N, nullptr); + } + // the Q4_0 rows replace the subset in place (they are smaller) + if (cudaMemcpy(dhead_, dst.data(), dst.size(), cudaMemcpyHostToDevice) != cudaSuccess) { err = "mtp: writing the draft head"; return false; } + dhead_type_ = GGML_Q4_0; + std::fprintf(stderr, "strata mtp: --mtp-q4: draft head over %lld tokens as Q4_0 (%.1f MiB read per step, was %.1f)\n", + (long long) n_dvocab_, (double) dst.size() / 1048576.0, (double) src.size() / 1048576.0); + return true; +#else + err = "mtp: --mtp-q4 needs a build with native experts (ggml)"; + return false; +#endif +} bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, SessionState& ss, int max_t, std::string& err, int64_t window) { @@ -176,6 +250,7 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session } cudaMemcpy(dense_, blob.data(), blob.size(), cudaMemcpyHostToDevice); vram_ += blob.size(); + if (q4_ && !make_q4_dense(blob, err)) return false; } // ---- the 512 routed experts, one blob each { @@ -338,7 +413,7 @@ void MtpDrafter::record_top2(int j) { uint64_t MtpDrafter::bind_bytes(uint64_t head_row_bytes, int64_t n_vocab) const { uint64_t bytes = head_logits_ ? 0 : (uint64_t) max_t_ * (uint64_t) n_vocab * sizeof(float); if (dhead_ == nullptr && !full_head_env()) { - if (FILE* f = std::fopen((rt_dir_ + "/draft_vocab.bin").c_str(), "rb")) { + if (FILE* f = std::fopen(vocab_file().c_str(), "rb")) { std::fseek(f, 0, SEEK_END); const long size = std::ftell(f); std::fclose(f); @@ -462,7 +537,7 @@ bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float // the draft head's token subset, when tools/draft_vocab.py wrote one if (dhead_ == nullptr && !full_head_env()) { std::vector raw; - if (read_file(rt_dir_ + "/draft_vocab.bin", raw) && raw.size() >= 4 && raw.size() % 4 == 0) { + if (read_file(vocab_file(), raw) && raw.size() >= 4 && raw.size() % 4 == 0) { n_dvocab_ = (int64_t) (raw.size() / 4); const int64_t row_bytes = (int64_t) head->row_bytes(); // a vocabulary row of the native head if (cudaMalloc((void**) &dvocab_, raw.size()) != cudaSuccess || @@ -479,6 +554,8 @@ bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float vram_ += (uint64_t) (n_dvocab_ * row_bytes) + raw.size(); std::fprintf(stderr, "strata mtp: draft head over %lld tokens (%.1f MiB)\n", (long long) n_dvocab_, (double) (n_dvocab_ * row_bytes) / 1048576.0); + dhead_type_ = head->type(); + if (q4_ && !make_q4_head(err)) return false; } } if (coupled_draft_env() && cparams_ == nullptr && !setup_coupled(err)) return false; @@ -499,6 +576,14 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri const GrShapes gs{g.n_embd, g.hc, g.hc_lr}; const int32_t* step = step_ + row0 * 4; const int32_t* pos = pos_ + row0 * NH; + // --mtp-q4: each projection's format and weights for this pass (Q8_0 unless the Q4_0 copies exist) + int wt_fc_embedding, wt_fc_hidden, wt_k_proj, wt_v_proj, wt_q_proj, wt_o_proj; + const void* wp_fc_embedding = wq("fc_embedding.weight", wt_fc_embedding); + const void* wp_fc_hidden = wq("fc_hidden.weight", wt_fc_hidden); + const void* wp_k_proj = wq("self_attn.k_proj.weight", wt_k_proj); + const void* wp_v_proj = wq("self_attn.v_proj.weight", wt_v_proj); + const void* wp_q_proj = wq("self_attn.q_proj.weight", wt_q_proj); + const void* wp_o_proj = wq("self_attn.o_proj.weight", wt_o_proj); try { // ---- the two input branches const WeightRef* we = wt_->find("token_embd.weight"); @@ -514,7 +599,7 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri } native_qsa_rms_norm_weighted(emb_, f32("pre_fc_norm_embedding.weight"), en_, (int) N, T, EPS, cs); native_quantize_q8_1(en_, xq_, (int) N, T, cs); - native_mmvq(GGML_Q8_0, q8("fc_embedding.weight"), xq_, e2_, (int) N, (int) N, T, cs); + native_mmvq(wt_fc_embedding, wp_fc_embedding, xq_, e2_, (int) N, (int) N, T, cs); if (hnorm_stream_) // --mtp-hnorm stream: one RMS per stream, each scaled by its slice of the weight native_qsa_rms_norm_grouped(Rin_, f32("pre_fc_norm_hidden.weight"), hn_, (int) N, (int) HC, (int) (T * HC), EPS, cs); else @@ -522,7 +607,7 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri for (int c0 = 0; c0 < T * HC; c0 += 8) { const int nc = (int) std::min(8, T * HC - c0); native_quantize_q8_1(hn_ + (size_t) c0 * N, xq_, (int) N, nc, cs); - native_mmvq(GGML_Q8_0, q8("fc_hidden.weight"), xq_, h2_ + (size_t) c0 * N, (int) N, (int) N, nc, cs); + native_mmvq(wt_fc_hidden, wp_fc_hidden, xq_, h2_ + (size_t) c0 * N, (int) N, (int) N, nc, cs); } add_streams_broadcast(h2_, e2_, R_, N, (int) HC, T, cs); // ---- the attention hyper-connection @@ -546,8 +631,8 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st_.cos_tab, st_.sin_tab, p, cs); }; native_quantize_q8_1(mixed_, xq_, (int) N, T, cs); - native_mmvq(GGML_Q8_0, q8("self_attn.k_proj.weight"), xq_, kcur_, (int) N, (int) (NKV * HD), T, cs); - native_mmvq(GGML_Q8_0, q8("self_attn.v_proj.weight"), xq_, vcur_, (int) N, (int) (NKV * HD), T, cs); + native_mmvq(wt_k_proj, wp_k_proj, xq_, kcur_, (int) N, (int) (NKV * HD), T, cs); + native_mmvq(wt_v_proj, wp_v_proj, xq_, vcur_, (int) N, (int) (NKV * HD), T, cs); for (int t = 0; t < T; ++t) { norm_rope(kcur_ + t * NKV * HD, f32("self_attn.k_norm.weight"), (int) NKV, (int) HD, pos + t * NH); if (st_.kv_rot) { // rotated K and V (kv_q4.hpp): Q4_0, and INT8 with STRATA_KV_ROT=1 @@ -566,7 +651,7 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri vcur_ + t * NKV * HD, s, cs, &st_.host); } if (!full) return true; - native_mmvq(GGML_Q8_0, q8("self_attn.q_proj.weight"), xq_, qfull_, (int) N, (int) (NH * 2 * HD), T, cs); + native_mmvq(wt_q_proj, wp_q_proj, xq_, qfull_, (int) N, (int) (NH * 2 * HD), T, cs); for (int t = 0; t < T; ++t) { float* qc = qcur_ + t * NH * HD; if (cudaMemcpy2DAsync(qc, (size_t) HD * 4, qfull_ + t * NH * 2 * HD, (size_t) HD * 2 * 4, (size_t) HD * 4, @@ -584,7 +669,7 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri for (int t = 0; t < T; ++t) native_qsa_gate_apply(attn_ + t * NH * HD, qfull_ + t * NH * 2 * HD, attn32_ + t * NH * HD, (int) NH, (int) HD, cs); native_quantize_q8_1(attn32_, xq_, (int) (NH * HD), T, cs); - native_mmvq(GGML_Q8_0, q8("self_attn.o_proj.weight"), xq_, bo_, (int) (NH * HD), (int) N, T, cs); + native_mmvq(wt_o_proj, wp_o_proj, xq_, bo_, (int) (NH * HD), (int) N, T, cs); // ---- the MLP hyper-connection (the attention write folded in) { FusedGrArgs fa[kFusedGrMaxT]; @@ -612,9 +697,9 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri moe_grouped_s2(grp_ptr_, grp_start_, grp_counts_, hit_dst_, hit_slot_, (int64_t) T * K, (int64_t) T * K, hit_xq_, hit_xs_, hit_scratch_, parts_, cs); NativeSharedWeights nsw; - nsw.gate_type = GGML_Q8_0; nsw.gate_data = q8("mlp.shared_expert.gate_proj.weight"); - nsw.up_type = GGML_Q8_0; nsw.up_data = q8("mlp.shared_expert.up_proj.weight"); - nsw.down_type = GGML_Q8_0; nsw.down_data = q8("mlp.shared_expert.down_proj.weight"); + nsw.gate_data = wq("mlp.shared_expert.gate_proj.weight", nsw.gate_type); + nsw.up_data = wq("mlp.shared_expert.up_proj.weight", nsw.up_type); + nsw.down_data = wq("mlp.shared_expert.down_proj.weight", nsw.down_type); nsw.q8_1 = xq_; const SForm none{}; for (int t = 0; t < T; ++t) { @@ -637,7 +722,8 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri native_quantize_q8_1(sample_, xq_, (int) N, T, cs); const bool sub = dhead_ != nullptr; const int64_t nv = sub ? n_dvocab_ : n_vocab_; - native_mmvq(head_->type(), sub ? dhead_ : head_->weights(), xq_, head_logits_, (int) N, (int) nv, T, cs); + native_mmvq(sub ? dhead_type_ : head_->type(), sub ? dhead_ : head_->weights(), xq_, head_logits_, (int) N, + (int) nv, T, cs); if (coupled_rec_) { // coupled draft sampling: the target's chain and Philox draw for the row that will verify this draft // (counter = this cell + 1, from its step record), penalties over the ring; T == 1 (full layer) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 6ce42903..a47a94f5 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -419,6 +419,10 @@ struct Options { /// --mtp-hnorm stream (opt-in): the draft layer's pre_fc_norm_hidden normalizes each hyper-connection stream on /// its own (llama.cpp's qwen4exp MTP graph) instead of one RMS over all four (the default, tools/mtp_probe.py). bool mtp_hnorm_stream = false; + /// --mtp-q4 (opt-in): the draft layer's projections and draft head from 4-bit copies (fewer bytes per draft step) + bool mtp_q4 = false; + /// --mtp-draft-vocab FILE (opt-in): the draft head's token subset from FILE instead of /draft_vocab.bin + std::string mtp_draft_vocab; /// A control vector on the residual stream (strata/kernels/cvec.hpp), with llama.cpp's flags: the /// `experimental-speed-projection` profile passes `--control-vector-scaled FILE:1.0 --control-vector-layer-range /// 4 44 --cvec-mode project --cvec-dir per-layer`. None by default; --serve switches a loaded one per request. @@ -522,6 +526,8 @@ void usage() { " --lookup-chain-min M the shortest context match --lookup-chain extends on (default 3)\n" " --mtp-hnorm pooled|stream the draft layer's hidden-input norm: one RMS over all four streams\n" " (default) or one per stream (llama.cpp's MTP graph)\n" + " --mtp-q4 opt-in: the draft layer's projections and draft head as 4-bit copies\n" + " --mtp-draft-vocab FILE opt-in: the draft head's token subset (default /draft_vocab.bin)\n" " --control-vector-scaled FILE:SCALE[,...] a control vector GGUF on the residual stream (llama.cpp's\n" " format; --control-vector FILE = scale 1). --serve: requests switch it (cvec=0|1)\n" " --control-vector-layer-range A B the layers it follows (inclusive; default 1 .. the last)\n" @@ -1217,6 +1223,8 @@ int main(int argc, char** argv) { } o.mtp_hnorm_stream = v == "stream"; } + else if (a == "--mtp-q4") o.mtp_q4 = true; + else if (a == "--mtp-draft-vocab") o.mtp_draft_vocab = next("--mtp-draft-vocab"); else if (a == "--control-vector") o.cvec_files.push_back({next("--control-vector"), 1.0f}); else if (a == "--control-vector-scaled") { // FILE:SCALE, comma-separated; the LAST colon splits, so a Windows path (C:\...) keeps its drive @@ -2567,6 +2575,8 @@ int main(int argc, char** argv) { } if (!o.mtp.empty()) mtp.set_prompt_len((int64_t) o.tokens.size()); mtp.set_hnorm_per_stream(o.mtp_hnorm_stream); // --mtp-hnorm stream (opt-in), before any capture + mtp.set_q4(o.mtp_q4); // --mtp-q4 (opt-in), before load + if (!o.mtp_draft_vocab.empty()) mtp.set_draft_vocab(o.mtp_draft_vocab); // the draft layer is the canonical model's MTP head (512 experts) even when the target is pruned, // so it always sees the canonical geometry; `static` because MtpDrafter keeps a reference static const strata::core::ModelGeometry draft_geometry{}; From 5e0c43baccb797870e54b05dc6f1310ab60024d8 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 02:06:51 +0200 Subject: [PATCH 19/55] --lookup-chain: the draft policy keeps only the chained tokens that pay Measured on Strix Halo (UD-IQ4_XS, 1-2K contexts) a verify row costs ~9 ms on a ~61 ms window, so chaining every 3+-token match (49% of chained drafts accepted) gave +6.4% tokens per step for +7% window time. The policy now picks the number of chained tokens k with the best expected tokens per ms: the MTP window's measured tokens + p_mtp (c + c^2 + .. + c^k) at the measured cost of the longer window, where p_mtp is the product of the draft layer's own draft probabilities and c the chained drafts' acceptance by match length (their own decayed counts, learned only from rounds that reached the chain). Unmeasured sizes are probed a few times when p_mtp * c >= 0.6. STRATA_LOOKUP_CHAIN_FIXED=1 takes every proposal as before. --- include/strata/spec/draft_policy.hpp | 9 ++++++ src/program/generate.cpp | 26 ++++++++++++---- src/spec/draft_policy.cpp | 45 ++++++++++++++++++++++++++++ src/spec/draft_policy_test.cpp | 17 +++++++++++ 4 files changed, 92 insertions(+), 5 deletions(-) diff --git a/include/strata/spec/draft_policy.hpp b/include/strata/spec/draft_policy.hpp index c77b8696..c4981e92 100644 --- a/include/strata/spec/draft_policy.hpp +++ b/include/strata/spec/draft_policy.hpp @@ -35,6 +35,14 @@ public: /// After the round: the window it used, the drafts accepted, and the round's time (verify + commit + draft). void observe(bool lookup, int t, int accepted, int match, double round_ms); + /// --lookup-chain: how many of `k_avail` lookup tokens to append after an MTP window of `t_mtp` tokens whose + /// drafts all hold with probability `p_mtp` (estimated from the draft layer's own probabilities): the k with the + /// best expected tokens per ms, E(t_mtp) + p_mtp (c + c^2 + .. + c^k) at the cost of t_mtp + k, if it beats the MTP + /// window alone by `margin`; c = the acceptance of chained drafts by match length (their own counts). 0 = none. + int chain(int t_mtp, double p_mtp, int k_avail, int match) const; + /// After a chained round: the MTP window's size, the chained tokens, the window's accepted drafts, its time. + void observe_chain(int t_mtp, int k, int accepted, int match, double round_ms); + double chain_rate(int match) const; double lookup_rate(int match) const; // current q for a match length double cost_ms(int t) const; // measured or scaled round time of a window of t tokens @@ -47,6 +55,7 @@ private: std::array cost_{}, cost_n_{}; // round ms by window size std::array mtp_tok_{}, mtp_n_{}; // tokens committed by MTP windows of that size std::array ok_{}, bad_{}; // lookup drafts accepted / windows cut short, decayed + std::array cok_{}, cbad_{}; // chained lookup drafts, the same (reached rounds only) }; } // namespace strata::spec diff --git a/src/program/generate.cpp b/src/program/generate.cpp index a47a94f5..2a46bb06 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -5481,6 +5481,7 @@ int main(int argc, char** argv) { int64_t t2_rej[8] = {}, t2_hit[8] = {}; // STRATA_MTP_TOP2: rejections inside the MTP drafts by depth, runner-up hits std::vector cbuf((size_t) S, 0), ctail; strata::spec::PromptLookupSource lookup_src(sfx); + static const bool chain_fixed = std::getenv("STRATA_LOOKUP_CHAIN_FIXED") != nullptr; // no policy gate int64_t draft_offered = 0, draft_accepted = 0; // what the session holds once this request is done: the prompt read so far, then every committed token std::vector consumed; @@ -5528,13 +5529,19 @@ int main(int argc, char** argv) { } } // --lookup-chain: what followed an earlier occurrence of the context + the MTP's drafts, after them - int chain_n = 0; + int chain_n = 0, cm = 0; if (o.lookup_chain > 0 && !first_window && !from_sfx && T < S) { - int cm = 0, csrc = -1; + int csrc = -1; const int nt = chain_tail(sfx, drafts.data(), T - 1, ctail); chain_n = strata::spec::propose_from_sources(lookup_src, ctail.data(), nt, T - 1, std::min(o.lookup_chain, S - T), o.lookup_chain_min, cbuf.data(), &cm, &csrc); + // the policy keeps the chained tokens that pay at this machine's measured window costs + if (chain_n > 0 && !chain_fixed) { + double p_mtp = 1.0; + for (int i = 0; i < T - 1; ++i) p_mtp *= dprob[(size_t) i]; + chain_n = policy.chain(T, p_mtp, chain_n, cm); + } } const int T_mtp = T; T += chain_n; @@ -5621,9 +5628,12 @@ int main(int argc, char** argv) { std::printf("ERR %s\n", err.c_str()); return 1; } - if (timed_round && !eos && chain_n == 0) // a chained window is neither an MTP nor a lookup window + if (timed_round && !eos && chain_n == 0) policy.observe(from_sfx, T, a, sfx_match, std::chrono::duration(Clock::now() - round0).count()); + else if (timed_round && !eos) // a chained window: its MTP part, its chain, its cost + policy.observe_chain(T_mtp, chain_n, a, cm, + std::chrono::duration(Clock::now() - round0).count()); if (eos) { finish = "stop"; break; } if (stop_req.load()) { finish = "cancel"; break; } x = outv[(size_t) a]; @@ -6384,13 +6394,18 @@ int main(int argc, char** argv) { } } // --lookup-chain: what followed an earlier occurrence of the context + the MTP's drafts, after them - int chain_n = 0; + int chain_n = 0, cm = 0; if (o.lookup_chain > 0 && use_mtp && !first_window && !from_sfx && T < o.spec) { - int cm = 0, csrc = -1; + int csrc = -1; const int nt = chain_tail(sfx, drafts.data(), T - 1, ctail); chain_n = strata::spec::propose_from_sources(lookup_src, ctail.data(), nt, T - 1, std::min(o.lookup_chain, o.spec - T), o.lookup_chain_min, cbuf.data(), &cm, &csrc); + if (chain_n > 0 && std::getenv("STRATA_LOOKUP_CHAIN_FIXED") == nullptr) { + double p_mtp = 1.0; + for (int i = 0; i < T - 1; ++i) p_mtp *= dprob[(size_t) i]; + chain_n = policy.chain(T, p_mtp, chain_n, cm); + } } const int T_mtp = T; T += chain_n; @@ -6481,6 +6496,7 @@ int main(int argc, char** argv) { const double round_ms = std::chrono::duration(Clock::now() - t0).count(); total_ms += round_ms; if (timed_round && chain_n == 0) policy.observe(from_sfx, T, a, sfx_match, round_ms); + else if (timed_round) policy.observe_chain(T_mtp, chain_n, a, cm, round_ms); if (rounds % 64 == 0) std::fprintf(stderr, "strata generate: position %lld, %lld tokens, %lld rounds\n", (long long) p, (long long) produced.size(), (long long) rounds); diff --git a/src/spec/draft_policy.cpp b/src/spec/draft_policy.cpp index 1ac77198..858f4a56 100644 --- a/src/spec/draft_policy.cpp +++ b/src/spec/draft_policy.cpp @@ -98,4 +98,49 @@ void DraftPolicy::observe(bool lookup, int t, int accepted, int match, double ro } } +double DraftPolicy::chain_rate(int match) const { + // prior: a chained draft is a lookup continuing the MTP's drafts - weaker evidence than a plain match of that length + constexpr double kChainPrior[kBuckets] = {0.45, 0.65, 0.8, 0.9}; + const int b = bucket(match); + return (cok_[b] + kPriorN * kChainPrior[b]) / (cok_[b] + cbad_[b] + kPriorN); +} + +int DraftPolicy::chain(int t_mtp, double p_mtp, int k_avail, int match) const { + t_mtp = std::clamp(t_mtp, 1, max_t_); + const int kmax = std::min(k_avail, max_t_ - t_mtp); + if (kmax <= 0) return 0; + const double e0 = mtp_tokens(t_mtp), base = e0 / cost_ms(t_mtp), c = chain_rate(match); + p_mtp = std::clamp(p_mtp, 0.0, 1.0); + double gain = 0.0, ci = 1.0, best = 0.0; + int best_k = 0; + for (int k = 1; k <= kmax; ++k) { + ci *= c; + gain += ci; + const double r = (e0 + p_mtp * gain) / cost_ms(t_mtp + k); + if (r > best) { best = r; best_k = k; } + } + if (best_k > 0 && best > base * (1.0 + margin_)) return best_k; + // as choose(): a size whose cost is only guessed is tried a few times when the continuation looks likely + const int t_full = t_mtp + kmax; + if (cost_n_[t_full] < kProbes && p_mtp * c >= 0.6) return kmax; + return 0; +} + +void DraftPolicy::observe_chain(int t_mtp, int k, int accepted, int match, double round_ms) { + const int t = std::clamp(t_mtp + k, 1, kMaxT); + if (round_ms > 0) { + cost_[t] = cost_n_[t] > 0 ? (1.0 - kCostAlpha) * cost_[t] + kCostAlpha * round_ms : round_ms; + cost_n_[t] += 1.0; + } + // the MTP part is an ordinary MTP window as far as its own drafts go + const int mtp_acc = std::min(accepted, t_mtp - 1); + const double got = mtp_acc + 1.0; + mtp_tok_[t_mtp] = mtp_n_[t_mtp] > 0 ? (1.0 - kTokAlpha) * mtp_tok_[t_mtp] + kTokAlpha * got : got; + mtp_n_[t_mtp] += 1.0; + if (accepted < t_mtp - 1) return; // the chain was never reached: it says nothing about the lookup + const int b = bucket(match), ok = accepted - (t_mtp - 1); + cok_[b] = kDecay * cok_[b] + ok; + cbad_[b] = kDecay * cbad_[b] + (ok < k ? 1.0 : 0.0); +} + } // namespace strata::spec diff --git a/src/spec/draft_policy_test.cpp b/src/spec/draft_policy_test.cpp index e04b3de8..3a7a3e61 100644 --- a/src/spec/draft_policy_test.cpp +++ b/src/spec/draft_policy_test.cpp @@ -58,6 +58,23 @@ int main() { for (int i = 0; i < 3; ++i) p.observe(true, 6, 5, 40, 3.0 * cost(6)); // it turns out very expensive check(!p.choose(4, 5, 40).lookup, "after the probes, the measured cost decides"); } + { + // --lookup-chain: rows cheap (UMA-like) and the chain always accepted -> chained; rows dear or the chain + // always rejected -> not + auto cheap = [](int t) { return 40.0 + 2.0 * (t - 1); }; + DraftPolicy p(8); + for (int t = 2; t <= 8; ++t) + for (int i = 0; i < 5; ++i) p.observe(false, t, 1, 0, cheap(t)); + for (int i = 0; i < 30; ++i) p.observe(false, 4, 2, 0, cheap(4)); + for (int i = 0; i < 30; ++i) p.observe_chain(4, 3, 6, 12, cheap(7)); // every chained token accepted + check(p.chain(4, 0.9, 3, 12) == 3, "chain: cheap rows, always accepted -> all 3 chained"); + DraftPolicy q(8); + for (int t = 2; t <= 8; ++t) + for (int i = 0; i < 5; ++i) q.observe(false, t, 1, 0, cost(t)); + for (int i = 0; i < 30; ++i) q.observe_chain(4, 3, 3, 4, cost(7)); // reached, never accepted + check(q.chain(4, 0.9, 3, 4) == 0, "chain: dear rows, never accepted -> none"); + check(q.chain(4, 0.9, 0, 4) == 0 && q.chain(8, 1.0, 3, 40) == 0, "chain: nothing proposed / no room -> none"); + } std::printf(g_fail ? "FAIL\n" : "PASS\n"); return g_fail ? 1 : 0; } From 2c697fdacec8525ba01a3256795b0421ad5a5d2e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 03:40:40 +0200 Subject: [PATCH 20/55] --mtp-q4 all|proj|head: the projections and the draft head separately On Strix Halo (UD-IQ4_XS, head Q6_K) the 4-bit head costs acceptance (tokens per step 2.81 -> 2.72 with both) while the smaller 40.5K-token subset (--mtp-draft-vocab data/draft_vocab_en.bin) costs none, so the two 4-bit copies are now separate choices. --- include/strata/core/mtp.hpp | 4 ++-- src/core/mtp.cpp | 2 +- src/program/generate.cpp | 14 ++++++++++---- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/include/strata/core/mtp.hpp b/include/strata/core/mtp.hpp index 8f290a73..9073877d 100644 --- a/include/strata/core/mtp.hpp +++ b/include/strata/core/mtp.hpp @@ -55,7 +55,7 @@ public: /// --mtp-q4 (opt-in; before load): the draft layer's Q8_0 projections and its draft head run from 4-bit (Q4_0) /// copies made at load/bind - fewer bytes per draft step; drafts only, the verify window decides every token. /// (The prompt path's batched K/V pass keeps the Q8_0 originals.) - void set_q4(bool on) { q4_ = on; } + void set_q4(bool proj, bool head) { q4_ = proj; q4_head_ = head; } /// --mtp-draft-vocab FILE (opt-in; before bind): the draft head's token subset from FILE instead of /// rt/draft_vocab.bin (e.g. data/draft_vocab_en.bin, 40K tokens) void set_draft_vocab(const std::string& path) { dvocab_path_ = path; } @@ -145,7 +145,7 @@ private: int device_ = -1; ///< the device `load` ran on: the public calls switch to it (layer split) int max_drafts_ = 1 << 30; bool hnorm_stream_ = false; - bool q4_ = false; + bool q4_ = false, q4_head_ = false; uint8_t* dense4_ = nullptr; ///< --mtp-q4: Q4_0 copies of the Q8_0 tensors std::vector> q4_off_; int dhead_type_ = -1; ///< the draft head subset's ggml type (the main head's, or Q4_0) diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp index d2f60518..2c1c13e1 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -555,7 +555,7 @@ bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float std::fprintf(stderr, "strata mtp: draft head over %lld tokens (%.1f MiB)\n", (long long) n_dvocab_, (double) (n_dvocab_ * row_bytes) / 1048576.0); dhead_type_ = head->type(); - if (q4_ && !make_q4_head(err)) return false; + if (q4_head_ && !make_q4_head(err)) return false; } } if (coupled_draft_env() && cparams_ == nullptr && !setup_coupled(err)) return false; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 2a46bb06..804af6d7 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -420,7 +420,7 @@ struct Options { /// its own (llama.cpp's qwen4exp MTP graph) instead of one RMS over all four (the default, tools/mtp_probe.py). bool mtp_hnorm_stream = false; /// --mtp-q4 (opt-in): the draft layer's projections and draft head from 4-bit copies (fewer bytes per draft step) - bool mtp_q4 = false; + std::string mtp_q4; ///< "" (off), all, proj (the projections only) or head (the draft head only) /// --mtp-draft-vocab FILE (opt-in): the draft head's token subset from FILE instead of /draft_vocab.bin std::string mtp_draft_vocab; /// A control vector on the residual stream (strata/kernels/cvec.hpp), with llama.cpp's flags: the @@ -526,7 +526,7 @@ void usage() { " --lookup-chain-min M the shortest context match --lookup-chain extends on (default 3)\n" " --mtp-hnorm pooled|stream the draft layer's hidden-input norm: one RMS over all four streams\n" " (default) or one per stream (llama.cpp's MTP graph)\n" - " --mtp-q4 opt-in: the draft layer's projections and draft head as 4-bit copies\n" + " --mtp-q4 all|proj|head opt-in: the draft layer's projections and/or draft head as 4-bit copies\n" " --mtp-draft-vocab FILE opt-in: the draft head's token subset (default /draft_vocab.bin)\n" " --control-vector-scaled FILE:SCALE[,...] a control vector GGUF on the residual stream (llama.cpp's\n" " format; --control-vector FILE = scale 1). --serve: requests switch it (cvec=0|1)\n" @@ -1223,7 +1223,13 @@ int main(int argc, char** argv) { } o.mtp_hnorm_stream = v == "stream"; } - else if (a == "--mtp-q4") o.mtp_q4 = true; + else if (a == "--mtp-q4") { + o.mtp_q4 = next("--mtp-q4"); + if (o.mtp_q4 != "all" && o.mtp_q4 != "proj" && o.mtp_q4 != "head") { + std::fprintf(stderr, "strata generate: --mtp-q4 takes all, proj or head\n"); + return 2; + } + } else if (a == "--mtp-draft-vocab") o.mtp_draft_vocab = next("--mtp-draft-vocab"); else if (a == "--control-vector") o.cvec_files.push_back({next("--control-vector"), 1.0f}); else if (a == "--control-vector-scaled") { @@ -2575,7 +2581,7 @@ int main(int argc, char** argv) { } if (!o.mtp.empty()) mtp.set_prompt_len((int64_t) o.tokens.size()); mtp.set_hnorm_per_stream(o.mtp_hnorm_stream); // --mtp-hnorm stream (opt-in), before any capture - mtp.set_q4(o.mtp_q4); // --mtp-q4 (opt-in), before load + mtp.set_q4(o.mtp_q4 == "all" || o.mtp_q4 == "proj", o.mtp_q4 == "all" || o.mtp_q4 == "head"); // before load if (!o.mtp_draft_vocab.empty()) mtp.set_draft_vocab(o.mtp_draft_vocab); // the draft layer is the canonical model's MTP head (512 experts) even when the target is pruned, // so it always sees the canonical geometry; `static` because MtpDrafter keeps a reference From fe6c5260ec34b9557f2ab979bd0ca0fb58305ec9 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 03:40:48 +0200 Subject: [PATCH 21/55] Verify: the hyper-connection read from the GGUF's Q8_0 projections (opt-in STRATA_HC_Q8=1; S23's parked patch) NativeDense keeps the six hc_* projections per layer as stored (Q8_0, 0.65 GiB) beside the pack's BF16 copy (1.20 GiB, --compat-bf16's rounding); the verify window's fused_gr_read_multi then reads them with split-K kernels: gr_down_q8 (10 row groups + the inject rows x 16 chunks of 640 columns, the norm folded in as unscaled partials + per-chunk sums of squares) and gr_up_q8. Every other path keeps BF16. Another summation order and the GGUF's own values: output-changing, so opt-in and quality-checked separately. Also the STRATA_GR_V3=2 knob (the two-half v3 split where only 64 KiB of LDS is available). Taken over from S23 (aurora_s23/hc_q8_grv3s2.diff) unchanged. --- include/strata/core/weights.hpp | 3 + include/strata/kernels/fused_gr.hpp | 5 + src/core/native_dense.cpp | 40 ++++- src/core/verify.cpp | 2 + src/kernels/cuda/fused_gr.cu | 237 +++++++++++++++++++++++++++- 5 files changed, 284 insertions(+), 3 deletions(-) diff --git a/include/strata/core/weights.hpp b/include/strata/core/weights.hpp index 5c6414f8..a9949123 100644 --- a/include/strata/core/weights.hpp +++ b/include/strata/core/weights.hpp @@ -90,6 +90,9 @@ struct WeightRef { const void* native_data = nullptr; void* native_q8_1 = nullptr; int native_type = -1; + /// S23 experiment (STRATA_HC_Q8=1): a hyper-connection projection's Q8_0 bytes as the GGUF stores them, owned by + /// NativeDense, for the verify window's read (every other path keeps the pack's BF16 `data`) + const void* hc_q8 = nullptr; /// Plan v0.3 P1: false when the loader SKIPPED this tensor's canonical bytes because another form serves it /// (native GGUF projections, the native head). The metadata above stays valid; `data` is null. bool resident = true; diff --git a/include/strata/kernels/fused_gr.hpp b/include/strata/kernels/fused_gr.hpp index 40eff30f..427eae20 100644 --- a/include/strata/kernels/fused_gr.hpp +++ b/include/strata/kernels/fused_gr.hpp @@ -36,6 +36,11 @@ struct FusedGrArgs { float* rs = nullptr; ///< workspace, hc floats float* inject_out = nullptr; ///< hc floats (when w_inject) float* mixed = nullptr; ///< n_embd + /// S23 experiment (STRATA_HC_Q8=1): the GGUF's Q8_0 projections (null: the BF16 ones above); fused_gr_read_multi + /// only + const uint8_t* q8_down = nullptr; ///< Q8_0 [hc_lr][hc*n_embd] + const uint8_t* q8_up = nullptr; ///< Q8_0 [hc*n_embd][hc_lr] + const uint8_t* q8_inject = nullptr;///< Q8_0 [hc][hc*n_embd] }; bool fused_gr_supported(int64_t n_embd, int64_t hc, int64_t hc_lr); diff --git a/src/core/native_dense.cpp b/src/core/native_dense.cpp index 4a86d48c..6abc9f26 100644 --- a/src/core/native_dense.cpp +++ b/src/core/native_dense.cpp @@ -6,6 +6,8 @@ #include #include #include +#include +#include #include #include #include @@ -13,6 +15,18 @@ namespace strata::core { namespace { +// S23 experiment (STRATA_HC_Q8=1): the hyper-connection projections' Q8_0 bytes for the verify read +bool hc_q8_requested() { + static const bool on = [] { const char* v = std::getenv("STRATA_HC_Q8"); return v != nullptr && v[0] == '1'; }(); + return on; +} +bool hc_q8_name(const std::string& name) { + if (name.rfind("blk.", 0) != 0) return false; + static const char* suffixes[] = {".hc_attn_down.weight", ".hc_attn_up.weight", ".hc_attn_inject.weight", + ".hc_ffn_down.weight", ".hc_ffn_up.weight", ".hc_ffn_inject.weight"}; + for (const char* suffix : suffixes) if (name.ends_with(suffix)) return true; + return false; +} bool eligible(const strata::TensorInfo& tensor, bool include_ple_key) { const auto& name = tensor.name; if (name.rfind("blk.", 0) != 0) return false; @@ -76,7 +90,7 @@ bool NativeDense::load(const std::vector& shards, WeightTable& tabl std::vector pending; std::set seen; int max_in = 0; - uint64_t total = 0; + uint64_t total = 0, hc_q8_bytes = 0; uint64_t split_count = 0, split_tensors = 0; std::set split_numbers; bool have_architecture = false; @@ -170,6 +184,25 @@ bool NativeDense::load(const std::vector& shards, WeightTable& tabl total += bytes; pending.push_back(Pending{&ref, (int) tensor.type, bytes, std::move(data)}); } + if (hc_q8_requested()) + for (const auto& tensor : gguf.tensors()) { + if (tensor.type != 8 || !hc_q8_name(tensor.name) || tensor.shape.size() != 2) continue; + auto found = table.table_.find(tensor.name); + if (found == table.table_.end() || found->second.hc_q8 != nullptr) continue; + auto& ref = found->second; + if (tensor.shape[0] != (uint64_t) ref.ne0 || tensor.shape[1] != (uint64_t) ref.ne1 || ref.ne0 % 32 != 0) { + err = "native dense (STRATA_HC_Q8): incompatible matrix " + tensor.name; return false; + } + const uint64_t bytes = (uint64_t) ref.ne0 / 32 * 34 * (uint64_t) ref.ne1; + void* p = nullptr; + if (cudaMalloc(&p, bytes) != cudaSuccess || + cudaMemcpy(p, gguf.tensor_data(tensor), bytes, cudaMemcpyHostToDevice) != cudaSuccess) { + err = "native dense (STRATA_HC_Q8) upload " + tensor.name; return false; + } + ref.hc_q8 = p; + weights_.push_back(p); + hc_q8_bytes += bytes; + } } if (pending.empty()) { err = "native dense: no supported GDN/QSA matrices in supplied shards"; return false; } void* allocation = nullptr; @@ -185,7 +218,10 @@ bool NativeDense::load(const std::vector& shards, WeightTable& tabl weights_.push_back(item.data.release()); } scratch_ = scratch.release(); - bytes_ = total; + bytes_ = total + hc_q8_bytes; + if (hc_q8_requested()) + std::fprintf(stderr, "strata: STRATA_HC_Q8=1: %.2f GiB of Q8_0 hyper-connection projections for the verify read\n", + (double) hc_q8_bytes / 1073741824.0); return true; } catch (const std::exception& error) { err = std::string("native dense: ") + error.what(); diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 999f85d8..e631ee74 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -496,6 +496,8 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { a.bo_prev = bo_ + t * N; a.inj_prev = inj_prev + t * HC; a.w_norm = (const float*) wn[half]->data; a.w_down = (const uint16_t*) wd[half]->data; a.w_up = (const uint16_t*) wu[half]->data; a.w_inject = (const uint16_t*) wi[half]->data; + a.q8_down = (const uint8_t*) wd[half]->hc_q8; a.q8_up = (const uint8_t*) wu[half]->hc_q8; + a.q8_inject = (const uint8_t*) wi[half]->hc_q8; a.eps = EPS; a.lo = lo_ + t * g.hc_lr; a.rs = rs_ + t * HC; a.inject_out = inj_out + t * HC; a.mixed = mixed_ + t * N; } diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cu index e7766fb7..d6515ac3 100644 --- a/src/kernels/cuda/fused_gr.cu +++ b/src/kernels/cuda/fused_gr.cu @@ -4,6 +4,7 @@ #include "strata/kernels/bf16_bits.hpp" #include "strata/kernels/verify_kernels.hpp" +#include #include #include @@ -798,6 +799,228 @@ int env_variant() { // per device: the variant `fused_gr_check` chose (0 = not checked yet) std::atomic g_variant[64]; +// ================================ S23 experiment (STRATA_HC_Q8=1): the read with the GGUF's Q8_0 projections ====== +// The pack holds the hyper-connection projections as BF16 (iq_pack.py --compat-bf16 rounds the GGUF's Q8_0 values to +// BF16: 1.20 GiB per verify step); this read takes the Q8_0 bytes as stored (0.65 GiB - and the GGUF's own values, +// not a rounding of them). The layout is the stream split of the v3 read above, at 4 chunks per stream: `down` runs +// on (10 groups of 32 rows + the inject rows) x 16 chunks of 640 columns = 176 blocks, each staging its chunk of +// R' * w_norm (unscaled) for the T tokens and writing the chunk's partial dots and sums of squares; `up` sums them +// per stream in a fixed order, applies rs, SwiGLU-free silu, and runs the default epilogue. Another summation order +// and other weights than the default read: an output-changing step (measured, quality-checked). +constexpr int Q8B = 34; // Q8_0 block: fp16 d + 32 int8 +constexpr int Q8_RPW = 4; // down rows per warp +constexpr int Q8_RG = LR / (WARPS * Q8_RPW); // 10 row groups (+1: the inject rows) +constexpr int Q8_KC = 640, Q8_NKC = D / Q8_KC; // 16 chunks, 4 per stream +constexpr int Q8_CPS = N / Q8_KC; // chunks per stream +constexpr int Q8_SPB = Q8_KC / 128; // 5 steps of 4 Q8_0 blocks (8 lanes x 4 values each) +__device__ __forceinline__ uint32_t q8_ld16(const uint8_t* p) { return *(const uint16_t*) p; } +__device__ __forceinline__ float q8_half(uint32_t h) { return __half2float(__ushort_as_half((unsigned short) h)); } +__device__ __forceinline__ float4 q8_four(uint32_t q, float d) { + return make_float4(d * (float) (int8_t) (q & 255u), d * (float) (int8_t) ((q >> 8) & 255u), + d * (float) (int8_t) ((q >> 16) & 255u), d * (float) (int8_t) (q >> 24)); +} + +template +__global__ void __launch_bounds__(THREADS) gr_down_q8_kernel(GrMulti m, float* __restrict__ part, float* __restrict__ ssg) { + __shared__ __align__(16) float xs[T][Q8_KC]; + __shared__ float red[WARPS][T]; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const int rg = blockIdx.x, kc = blockIdx.y, c = kc / Q8_CPS; + const bool inj = rg == Q8_RG; + const int nrows = inj ? ((m.a[0].q8_inject != nullptr && warp < HC) ? 1 : 0) : Q8_RPW; + const int row0 = inj ? warp : (rg * WARPS + warp) * Q8_RPW; + const uint8_t* wb = inj ? m.a[0].q8_inject : m.a[0].q8_down; + const int sub = lane & 7, bl = lane >> 3; // lanes 8b..8b+7: one Q8_0 block, 4 values each + uint32_t q[Q8_RPW][Q8_SPB]; + float dq[Q8_RPW][Q8_SPB]; +#pragma unroll + for (int r = 0; r < Q8_RPW; ++r) { + if (r >= nrows) break; + const uint8_t* row = wb + (size_t) (row0 + r) * (D / 32) * Q8B + (size_t) kc * (Q8_KC / 32) * Q8B; +#pragma unroll + for (int s = 0; s < Q8_SPB; ++s) { + const uint8_t* blk = row + (4 * s + bl) * Q8B; + dq[r][s] = q8_half(q8_ld16(blk)); + q[r][s] = q8_ld16(blk + 2 + 4 * sub) | q8_ld16(blk + 4 + 4 * sub) << 16; + } + } + float ssp[T]; +#pragma unroll + for (int k = 0; k < T; ++k) { + ssp[k] = 0.0f; + const FusedGrArgs& a = m.a[k]; + const float gw = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f; + for (int i = t; i < Q8_KC / 4; i += THREADS) { + const int col = kc * Q8_KC + 4 * i; + float4 r = *reinterpret_cast(a.R + col); + if (a.apply) { + const float4 b = *reinterpret_cast(a.bo_prev + (col - c * N)); + r.x = fmaf(b.x, gw, r.x); r.y = fmaf(b.y, gw, r.y); + r.z = fmaf(b.z, gw, r.z); r.w = fmaf(b.w, gw, r.w); + } + const float4 g = *reinterpret_cast(a.w_norm + col); + ssp[k] += r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w; + *reinterpret_cast(&xs[k][4 * i]) = make_float4(r.x * g.x, r.y * g.y, r.z * g.z, r.w * g.w); + } + } +#pragma unroll + for (int k = 0; k < T; ++k) { + const float v = warp_sum(ssp[k]); + if (lane == 0) red[warp][k] = v; + } + __syncthreads(); + if (rg == 0 && t < T) { + float s = 0.0f; + for (int w = 0; w < WARPS; ++w) s += red[w][t]; + ssg[t * Q8_NKC + kc] = s; + } + if (nrows == 0) return; +#pragma unroll + for (int r = 0; r < Q8_RPW; ++r) { + if (r >= nrows) break; + float acc[T]; +#pragma unroll + for (int k = 0; k < T; ++k) acc[k] = 0.0f; +#pragma unroll + for (int s = 0; s < Q8_SPB; ++s) { + const float4 w = q8_four(q[r][s], dq[r][s]); + const int v = 32 * (4 * s + bl) + 4 * sub; +#pragma unroll + for (int k = 0; k < T; ++k) { + const float4 x = *reinterpret_cast(&xs[k][v]); + acc[k] = fmaf(w.x, x.x, acc[k]); acc[k] = fmaf(w.y, x.y, acc[k]); + acc[k] = fmaf(w.z, x.z, acc[k]); acc[k] = fmaf(w.w, x.w, acc[k]); + } + } + const int prow = inj ? LR + warp : row0 + r; +#pragma unroll + for (int k = 0; k < T; ++k) { + const float v = warp_sum(acc[k]); + if (lane == 0) part[((size_t) k * Q8_NKC + kc) * PR + prow] = v; + } + } +} + +template +__global__ void __launch_bounds__(THREADS) gr_up_q8_kernel(GrMulti m, const float* __restrict__ part, + const float* __restrict__ ssg) { + __shared__ __align__(16) float lo[T][LR]; + __shared__ float rsS[T][HC]; + __shared__ float g[T][HC][UPM_COLS]; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const int d0 = blockIdx.x * UPM_COLS; + if (t < T * HC) { + const int k = t / HC, c = t - k * HC; + float ss = 0.0f; +#pragma unroll + for (int j = 0; j < Q8_CPS; ++j) ss += ssg[k * Q8_NKC + c * Q8_CPS + j]; + const float r = rsqrtf(ss / (float) N + m.a[k].eps); + rsS[k][c] = r; + if (blockIdx.x == 0) m.a[k].rs[c] = r; + } + __syncthreads(); + for (int i = t; i < T * PR; i += THREADS) { + const int k = i / PR, r = i - k * PR; + if (r >= LR && (blockIdx.x != 0 || m.a[k].w_inject == nullptr)) continue; + float sum = 0.0f; +#pragma unroll + for (int c = 0; c < HC; ++c) { + float p = 0.0f; +#pragma unroll + for (int j = 0; j < Q8_CPS; ++j) p += part[((size_t) k * Q8_NKC + c * Q8_CPS + j) * PR + r]; + sum = fmaf(rsS[k][c], p, sum); + } + if (r < LR) { + const float x = sum / (float) HC; + lo[k][r] = x / (1.0f + __expf(-x)); + } else { + m.a[k].inject_out[r - LR] = sum; + } + } + __syncthreads(); + constexpr int RPW8 = HC * UPM_COLS / WARPS; // 8 rows per warp +#pragma unroll 1 + for (int qq = 0; qq < RPW8; ++qq) { + const int r = warp + qq * WARPS; + const int c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd; + const uint8_t* row = m.a[0].q8_up + (size_t) i * (LR / 32) * Q8B; + float4 w[3]; +#pragma unroll + for (int s = 0; s < 3; ++s) { // lane: values 4 lane + 128 s (the third step: lanes 0-15) + const int v = 4 * lane + 128 * s; + if (v < LR) { + const uint8_t* blk = row + (v >> 5) * Q8B; + w[s] = q8_four(q8_ld16(blk + 2 + (v & 31)) | q8_ld16(blk + 4 + (v & 31)) << 16, q8_half(q8_ld16(blk))); + } else { + w[s] = make_float4(0.0f, 0.0f, 0.0f, 0.0f); + } + } + float rv = 0.0f, wn = 0.0f, bo = 0.0f, ip = 0.0f; + bool apply = false; + if (lane < T) { + const FusedGrArgs& a = m.a[lane]; + rv = a.R[i]; + wn = a.w_norm[i]; + apply = a.apply; + if (apply) { bo = a.bo_prev[d0 + dd]; ip = a.inj_prev[c]; } + } + float mine = 0.0f; +#pragma unroll + for (int k = 0; k < T; ++k) { + float acc = 0.0f; +#pragma unroll + for (int s = 0; s < 3; ++s) { + const int v = 4 * lane + 128 * s; + if (v < LR) { + const float4 x = *reinterpret_cast(&lo[k][v]); + acc = fmaf(w[s].x, x.x, acc); acc = fmaf(w[s].y, x.y, acc); + acc = fmaf(w[s].z, x.z, acc); acc = fmaf(w[s].w, x.w, acc); + } + } + acc = warp_sum(acc); + if (lane == k) mine = acc; + } + if (lane < T) { + if (apply) { + rv = fmaf(bo, 2.0f * sigmoidf_(ip / (float) HC), rv); + m.a[lane].R_out[i] = rv; + } + const float x = rv * wn * rsS[lane][c]; + g[lane][c][dd] = x * sigmoidf_(mine); + } + } + __syncthreads(); + for (int i = t; i < T * UPM_COLS; i += THREADS) { + const int k = i / UPM_COLS, col = i - k * UPM_COLS; + float sum = 0.0f; +#pragma unroll + for (int c = 0; c < HC; ++c) sum += g[k][c][col]; + m.a[k].mixed[d0 + col] = sum / (float) HC; + } +} + +template void launch_q8_t(const GrMulti& m, float* part, float* ssg, cudaStream_t st, unsigned long long* stamp_buf, + int stamp_i0) { + if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, (void*) st); + gr_down_q8_kernel<<>>(m, part, ssg); + if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, (void*) st); + gr_up_q8_kernel<<>>(m, part, ssg); +} +void launch_q8(const GrMulti& m, float* scratch, cudaStream_t st, unsigned long long* stamp_buf, int stamp_i0) { + float* part = scratch; + float* ssg = scratch + (size_t) m.T * Q8_NKC * PR; + switch (m.T) { + case 1: launch_q8_t<1>(m, part, ssg, st, stamp_buf, stamp_i0); break; + case 2: launch_q8_t<2>(m, part, ssg, st, stamp_buf, stamp_i0); break; + case 3: launch_q8_t<3>(m, part, ssg, st, stamp_buf, stamp_i0); break; + case 4: launch_q8_t<4>(m, part, ssg, st, stamp_buf, stamp_i0); break; + case 5: launch_q8_t<5>(m, part, ssg, st, stamp_buf, stamp_i0); break; + case 6: launch_q8_t<6>(m, part, ssg, st, stamp_buf, stamp_i0); break; + case 7: launch_q8_t<7>(m, part, ssg, st, stamp_buf, stamp_i0); break; + default: launch_q8_t<8>(m, part, ssg, st, stamp_buf, stamp_i0); break; + } +} + } // namespace void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, unsigned long long* stamp_buf, @@ -812,7 +1035,8 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi const FusedGrArgs& x = a[t]; if (!x.R || !x.w_norm || !x.w_down || !x.w_up || !x.lo || !x.rs || !x.mixed || (x.w_inject && !x.inject_out) || (x.apply && (!x.bo_prev || !x.inj_prev || !x.R_out)) || x.w_down != a[0].w_down || x.w_up != a[0].w_up || - x.w_inject != a[0].w_inject || x.w_norm != a[0].w_norm) { + x.w_inject != a[0].w_inject || x.w_norm != a[0].w_norm || x.q8_down != a[0].q8_down || + x.q8_up != a[0].q8_up || x.q8_inject != a[0].q8_inject) { std::fprintf(stderr, "fused_gr_read_multi: invalid arguments for token %d\n", t); std::exit(1); } @@ -820,6 +1044,15 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi m.xn = xn_scratch; m.T = n_tok; cudaStream_t st = (cudaStream_t) stream; + if (a[0].q8_down != nullptr && a[0].q8_up != nullptr && (a[0].w_inject == nullptr || a[0].q8_inject != nullptr)) { + launch_q8(m, xn_scratch, st, stamp_buf, stamp_i0); // S23 experiment: STRATA_HC_Q8=1 + const cudaError_t eq = cudaGetLastError(); + if (eq != cudaSuccess) { + std::fprintf(stderr, "fused_gr_read_multi q8: %s\n", cudaGetErrorString(eq)); + std::exit(1); + } + return; + } // STRATA_GR_V3=1: the two-kernel read above (another summation order - opt-in) static const bool v3 = [] { const char* v = std::getenv("STRATA_GR_V3"); return v != nullptr && std::atoi(v) != 0; }(); static int split3[64] = {}; // per device: 0 = not decided yet, 1 / 2 = column halves S, -1 = does not fit @@ -835,6 +1068,8 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi if (need1 <= limit && cudaFuncSetAttribute(gr_down_v3_kernel<1>, cudaFuncAttributeMaxDynamicSharedMemorySize, need1) == cudaSuccess) split = 1; + else if (need2 <= limit && std::getenv("STRATA_GR_V3") != nullptr && std::atoi(std::getenv("STRATA_GR_V3")) == 2) + split = 2; // S23 experiment: STRATA_GR_V3=2 takes the two-half split anyway (gfx1151: 64 KiB) else if (need2 <= limit) // #375 (kenh0u): the S = 2 split (a 64 KB opt-in card: Turing) disagrees with itself in gr_parity // (graph replay vs direct call) - such a card keeps the default read until that split is fixed From 348abafdd9ad23a7215373210fdb207e2401ce66 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 04:05:45 +0200 Subject: [PATCH 22/55] STRATA_HC_Q8=1: the F32 inject rows as Q8_0 too, so the Q8_0 read is taken The read takes the Q8_0 kernels only when the inject rows have a Q8_0 copy as well, and the GGUF stores them as F32: with only down/up loaded (0.62 GiB) every window still ran the BF16 read (Aurora: 18/18 outputs identical to the default, verify 61.4 vs 60.9 ms). The inject rows (4 x 10240 per projection) are now quantized at load with ggml's Q8_0 reference rounding. --- src/core/native_dense.cpp | 47 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 45 insertions(+), 2 deletions(-) diff --git a/src/core/native_dense.cpp b/src/core/native_dense.cpp index 6abc9f26..aae66aec 100644 --- a/src/core/native_dense.cpp +++ b/src/core/native_dense.cpp @@ -12,6 +12,9 @@ #include #include #include +#include +#include +#include namespace strata::core { namespace { @@ -27,6 +30,42 @@ bool hc_q8_name(const std::string& name) { for (const char* suffix : suffixes) if (name.ends_with(suffix)) return true; return false; } +// S25: the GGUF keeps the inject rows as F32 - quantized here to Q8_0 (ggml's reference rounding) so the Q8_0 read +// covers every hc projection +uint16_t half_bits(float f) { + uint32_t x; + std::memcpy(&x, &f, 4); + const uint32_t sign = (x >> 16) & 0x8000u; + int32_t e = (int32_t) ((x >> 23) & 0xff) - 127 + 15; + uint32_t m = x & 0x7fffffu; + if (e <= 0) { // subnormal or zero + if (e < -10) return (uint16_t) sign; + m |= 0x800000u; + const uint32_t shift = (uint32_t) (14 - e); + uint32_t h = m >> shift; + const uint32_t rem = m & ((1u << shift) - 1), half = 1u << (shift - 1); + if (rem > half || (rem == half && (h & 1u))) ++h; + return (uint16_t) (sign | h); + } + if (e >= 31) return (uint16_t) (sign | 0x7c00u); + uint32_t h = ((uint32_t) e << 10) | (m >> 13); + const uint32_t rem = m & 0x1fffu; + if (rem > 0x1000u || (rem == 0x1000u && (h & 1u))) ++h; + return (uint16_t) (sign | h); +} +std::vector q8_0_of(const float* x, uint64_t n) { + std::vector out((size_t) (n / 32 * 34)); + for (uint64_t b = 0; b < n / 32; ++b) { + float amax = 0.0f; + for (int j = 0; j < 32; ++j) amax = (std::max)(amax, std::fabs(x[b * 32 + j])); + const float d = amax / 127.0f, id = d != 0.0f ? 1.0f / d : 0.0f; + uint8_t* o = out.data() + b * 34; + const uint16_t hb = half_bits(d); + std::memcpy(o, &hb, 2); + for (int j = 0; j < 32; ++j) o[2 + j] = (uint8_t) (int8_t) std::lround(x[b * 32 + j] * id); + } + return out; +} bool eligible(const strata::TensorInfo& tensor, bool include_ple_key) { const auto& name = tensor.name; if (name.rfind("blk.", 0) != 0) return false; @@ -186,7 +225,8 @@ bool NativeDense::load(const std::vector& shards, WeightTable& tabl } if (hc_q8_requested()) for (const auto& tensor : gguf.tensors()) { - if (tensor.type != 8 || !hc_q8_name(tensor.name) || tensor.shape.size() != 2) continue; + const bool f32_inject = tensor.type == 0 && tensor.name.ends_with("_inject.weight"); + if ((tensor.type != 8 && !f32_inject) || !hc_q8_name(tensor.name) || tensor.shape.size() != 2) continue; auto found = table.table_.find(tensor.name); if (found == table.table_.end() || found->second.hc_q8 != nullptr) continue; auto& ref = found->second; @@ -195,8 +235,11 @@ bool NativeDense::load(const std::vector& shards, WeightTable& tabl } const uint64_t bytes = (uint64_t) ref.ne0 / 32 * 34 * (uint64_t) ref.ne1; void* p = nullptr; + std::vector q8; + if (f32_inject) q8 = q8_0_of((const float*) gguf.tensor_data(tensor), (uint64_t) ref.ne0 * (uint64_t) ref.ne1); if (cudaMalloc(&p, bytes) != cudaSuccess || - cudaMemcpy(p, gguf.tensor_data(tensor), bytes, cudaMemcpyHostToDevice) != cudaSuccess) { + cudaMemcpy(p, f32_inject ? (const void*) q8.data() : gguf.tensor_data(tensor), bytes, + cudaMemcpyHostToDevice) != cudaSuccess) { err = "native dense (STRATA_HC_Q8) upload " + tensor.name; return false; } ref.hc_q8 = p; From 8b30b1d58701300b547c7a37552dfe60a2e89024 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 04:20:49 +0200 Subject: [PATCH 23/55] Decode attention: the score phase one cell per thread (opt-in STRATA_ATTN_LANECELL=1, meant bit-identical) attn_chunk_kernel scored a chunk's 64 cells warp by warp: each lane 8 of the 256 dimensions, then one warp_sum per query head - 12 shuffle reductions per cell, which is what made the kernel ~53 us per layer at T=1 and +32 us per window row on gfx1151 (it scales linearly with T). With the switch, thread t scores cell t % 64 for 3 of the 12 heads alone: the same 8-dimension partial expression per former lane, then lane 0's butterfly order (a[l] += a[l + o], o = 16 .. 1), so each score has the same operations in the same order. Softmax, values and the merge are unchanged. --- src/kernels/cuda/qsa_decode_attn.cu | 64 +++++++++++++++++++++++------ 1 file changed, 51 insertions(+), 13 deletions(-) diff --git a/src/kernels/cuda/qsa_decode_attn.cu b/src/kernels/cuda/qsa_decode_attn.cu index 4035999a..d8c260c2 100644 --- a/src/kernels/cuda/qsa_decode_attn.cu +++ b/src/kernels/cuda/qsa_decode_attn.cu @@ -80,7 +80,7 @@ __device__ __forceinline__ void load8(const QsaAttnPools& p, bool value, long lo } else load8_q4(p, value, row, d0, out); } -template +template __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __restrict__ q, QsaAttnPools p, const int32_t* __restrict__ ids, const int32_t* __restrict__ step, int n_kv_heads, @@ -120,6 +120,41 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest srow[t] = r; } __syncthreads(); + if constexpr (LANE_CELL) { + // S25 (STRATA_ATTN_LANECELL=1): thread t scores cell t % 64 for heads 3 (t / 64) .. +2 by itself - the same + // 8-dimension partial per former lane (the identical expression), then the former warp_sum's butterfly as + // lane 0 ran it (a[l] += a[l + o] for o = 16 .. 1), so every score is bit-identical without 12 shuffle + // reductions per cell + constexpr int HPT = G * CHUNK / THREADS; // heads per thread (3) + const int c = t % CHUNK, h0 = (t / CHUNK) * HPT; + if (c >= n_here || srow[c] < 0) { +#pragma unroll + for (int j = 0; j < HPT; ++j) sp[h0 + j][c] = -FLT_MAX; + } else { + float a[HPT][32]; +#pragma unroll + for (int l = 0; l < 32; ++l) { + float k8[8]; + load8(p, false, srow[c], l * 8, k8); +#pragma unroll + for (int j = 0; j < HPT; ++j) { + const float4 qa = *reinterpret_cast(&sq[h0 + j][l * 8]); + const float4 qb = *reinterpret_cast(&sq[h0 + j][l * 8 + 4]); + float s = k8[0] * qa.x + k8[1] * qa.y + k8[2] * qa.z + k8[3] * qa.w + + k8[4] * qb.x + k8[5] * qb.y + k8[6] * qb.z + k8[7] * qb.w; + a[j][l] = s; + } + } +#pragma unroll + for (int j = 0; j < HPT; ++j) { +#pragma unroll + for (int o = 16; o > 0; o >>= 1) +#pragma unroll + for (int l = 0; l < o; ++l) a[j][l] = a[j][l] + a[j][l + o]; + sp[h0 + j][c] = a[j][0] * scale; + } + } + } else // scores: each warp takes cells warp, warp+8, ...; each lane holds 8 of the 256 dimensions. for (int c = warp; c < CHUNK; c += WARPS) { if (c >= n_here || srow[c] < 0) { @@ -227,18 +262,21 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3 const float scale = 1.0f / sqrtf((float) HD); const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv, (unsigned) n_q); cudaStream_t st = (cudaStream_t) stream; - if (kv_mode == 3) - attn_chunk_kernel<3><<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, - scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); - else if (kv_mode == 2) - attn_chunk_kernel<2><<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, - scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); - else if (kv_mode == 1) - attn_chunk_kernel<1><<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, - scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); - else - attn_chunk_kernel<0><<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, - scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); + // S25: STRATA_ATTN_LANECELL=1 - the score phase one cell per thread (bit-identical scores, no shuffle reductions) + static const bool lane_cell = [] { const char* v = std::getenv("STRATA_ATTN_LANECELL"); return v && v[0] == '1'; }(); +#define STRATA_ATTN_LAUNCH(M, LC) attn_chunk_kernel<<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride) + if (lane_cell) { + if (kv_mode == 3) STRATA_ATTN_LAUNCH(3, true); + else if (kv_mode == 2) STRATA_ATTN_LAUNCH(2, true); + else if (kv_mode == 1) STRATA_ATTN_LAUNCH(1, true); + else STRATA_ATTN_LAUNCH(0, true); + } else { + if (kv_mode == 3) STRATA_ATTN_LAUNCH(3, false); + else if (kv_mode == 2) STRATA_ATTN_LAUNCH(2, false); + else if (kv_mode == 1) STRATA_ATTN_LAUNCH(1, false); + else STRATA_ATTN_LAUNCH(0, false); + } +#undef STRATA_ATTN_LAUNCH attn_merge_kernel<<>>(part_acc, part_m, part_l, n_chunks, attn, stride); const cudaError_t e = cudaGetLastError(); From c637ed5a6e880fefd74fedc16b245a94e9c201cb Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 04:22:52 +0200 Subject: [PATCH 24/55] bf16 multi-row GEMV: 4 output rows per block (opt-in STRATA_MMVF_ROWS=1, bit-identical by construction) The router (512 x 2560) and the indexer projections run bf16_f32_mmvf_multi_kernel: one block per output row, so the window's T activation rows were read again by every block (+3.3 us per row per launch on gfx1151, ~0.2 ms per window row). With the switch a block computes 4 output rows from one read of the activations; per output each thread keeps the same pairs, FMA order and reductions. --- src/kernels/cuda/native_bf16.cu | 96 +++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) diff --git a/src/kernels/cuda/native_bf16.cu b/src/kernels/cuda/native_bf16.cu index 1390a6ab..57b89f09 100644 --- a/src/kernels/cuda/native_bf16.cu +++ b/src/kernels/cuda/native_bf16.cu @@ -2,6 +2,7 @@ #include "strata/kernels/bf16_bits.hpp" #include +#include #include #include #include @@ -118,6 +119,83 @@ __global__ void bf16_f32_mmvf_multi_kernel(const float* __restrict__ x, int64_t if (k < n_tok) y[(size_t) k * ldy + blockIdx.x] = acc[k]; } +// S25 (STRATA_MMVF_ROWS=1): RPB output rows per block. Each block read its row's weights once but all T activation +// rows again (n_out blocks x T x n_in floats through L2 - the part that grew with T); here a block reads the +// activations once for RPB rows. Per output, thread t still walks pairs t, t + BLOCK_SIZE, ... with the same two +// ordered FMAs and the same warp and block reductions: bit-identical to bf16_f32_mmvf_multi_kernel. +template +__global__ void bf16_f32_mmvf_rows_kernel(const float* __restrict__ x, int64_t ldx, const uint16_t* __restrict__ w, + float* __restrict__ y, int64_t ldy, int n_in, int n_out, int n_tok) { + const int t = threadIdx.x; + const int o0 = blockIdx.x * RPB; + __shared__ float partials[RPB][NT][32]; + if constexpr (BLOCK_SIZE > 32) { + if (t < 32) +#pragma unroll + for (int r = 0; r < RPB; ++r) +#pragma unroll + for (int k = 0; k < NT; ++k) partials[r][k][t] = 0.0f; + __syncthreads(); + } + float acc[RPB][NT]; +#pragma unroll + for (int r = 0; r < RPB; ++r) +#pragma unroll + for (int k = 0; k < NT; ++k) acc[r][k] = 0.0f; + for (int pair = t; pair < n_in / 2; pair += BLOCK_SIZE) { + float2 in[NT]; +#pragma unroll + for (int k = 0; k < NT; ++k) + if (k < n_tok) in[k] = reinterpret_cast(x + (size_t) k * ldx)[pair]; +#pragma unroll + for (int r = 0; r < RPB; ++r) { + if (o0 + r >= n_out) break; + const uint32_t weight = reinterpret_cast(w + (size_t) (o0 + r) * n_in)[pair]; + const float w0 = f32_from_bf16((uint16_t) weight), w1 = f32_from_bf16((uint16_t) (weight >> 16)); +#pragma unroll + for (int k = 0; k < NT; ++k) { + if (k < n_tok) { + acc[r][k] = __fmaf_rn(w0, in[k].x, acc[r][k]); + acc[r][k] = __fmaf_rn(w1, in[k].y, acc[r][k]); + } + } + } + } +#pragma unroll + for (int r = 0; r < RPB; ++r) +#pragma unroll + for (int k = 0; k < NT; ++k) acc[r][k] = mmvf_warp_sum(acc[r][k]); + if constexpr (BLOCK_SIZE > 32) { + if ((t & 31) == 0) +#pragma unroll + for (int r = 0; r < RPB; ++r) +#pragma unroll + for (int k = 0; k < NT; ++k) partials[r][k][t / 32] = acc[r][k]; + __syncthreads(); + if (t < 32) +#pragma unroll + for (int r = 0; r < RPB; ++r) +#pragma unroll + for (int k = 0; k < NT; ++k) acc[r][k] = mmvf_warp_sum(partials[r][k][t]); + } + if (t == 0) +#pragma unroll + for (int r = 0; r < RPB; ++r) + if (o0 + r < n_out) +#pragma unroll + for (int k = 0; k < NT; ++k) + if (k < n_tok) y[(size_t) k * ldy + o0 + r] = acc[r][k]; +} + +template +void launch_rows(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy, int n_in, int n_out, int n_tok, + cudaStream_t st) { + constexpr int RPB = 4; + const unsigned nb = (unsigned) ((n_out + RPB - 1) / RPB); + if (n_tok <= 4) bf16_f32_mmvf_rows_kernel<<>>(x, ldx, w, y, ldy, n_in, n_out, n_tok); + else bf16_f32_mmvf_rows_kernel<<>>(x, ldx, w, y, ldy, n_in, n_out, n_tok); +} + int mmvf_block_size(int64_t n_in) { int best = 32; int64_t best_iterations = (n_in + 63) / 64; @@ -140,6 +218,24 @@ void bf16_gemv_fp32_mmvf_multi(const float* x, int64_t ldx, const uint16_t* w, f w == nullptr || y == nullptr || (reinterpret_cast(x) & 7u) != 0) throw std::invalid_argument("bf16_gemv_fp32_mmvf_multi: 1..8 rows, even n_in/ldx, aligned pointers"); const cudaStream_t st = (cudaStream_t) stream; + static const bool rows = [] { const char* v = std::getenv("STRATA_MMVF_ROWS"); return v && v[0] == '1'; }(); + if (rows && n_out >= 64) { + const int ni = (int) n_in, no = (int) n_out; + switch (mmvf_block_size(n_in)) { + case 32: launch_rows<32>(x, ldx, w, y, ldy, ni, no, n_tok, st); break; + case 64: launch_rows<64>(x, ldx, w, y, ldy, ni, no, n_tok, st); break; + case 96: launch_rows<96>(x, ldx, w, y, ldy, ni, no, n_tok, st); break; + case 128: launch_rows<128>(x, ldx, w, y, ldy, ni, no, n_tok, st); break; + case 160: launch_rows<160>(x, ldx, w, y, ldy, ni, no, n_tok, st); break; + case 192: launch_rows<192>(x, ldx, w, y, ldy, ni, no, n_tok, st); break; + case 224: launch_rows<224>(x, ldx, w, y, ldy, ni, no, n_tok, st); break; + default: launch_rows<256>(x, ldx, w, y, ldy, ni, no, n_tok, st); break; + } + const cudaError_t result = cudaGetLastError(); + if (result != cudaSuccess) + throw std::runtime_error(std::string("bf16_gemv_fp32_mmvf_multi launch: ") + cudaGetErrorString(result)); + return; + } #define STRATA_MMVF_M(N) case N: \ if (n_tok <= 4) bf16_f32_mmvf_multi_kernel<<<(unsigned) n_out, N, 0, st>>>(x, ldx, w, y, ldy, (int) n_in, n_tok); \ else bf16_f32_mmvf_multi_kernel<<<(unsigned) n_out, N, 0, st>>>(x, ldx, w, y, ldy, (int) n_in, n_tok); break From be7889ed84a191cd69d12c28a6f7d1a1c15985df Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 03:28:31 +0000 Subject: [PATCH 25/55] verify: a fully resident decode window without the host round trip (opt-in), and fewer quantize launches STRATA_VERIFY_RESIDENT=1: when every expert of every layer is resident in the VRAM/UMA tier (checked once at init; a full cache never evicts; one stage only), the window graph is recorded without the per-layer host step: no doorbell_publish, no wait_flag_ge (3 per layer), no plan copy from mapped memory, no PCIe/CPU share (fetch_blobs, rebase_ptrs, its empty grouped launches, copy_rows_from_mapped) and no moe_hit_add: the device plans each group (resident_plan, the host's exact loop) and the combine reads the hit rows as 0.0f + hit (combine), which is what the zeroed part rows plus parts += hit gave. run() then skips the per-layer spin. Same tokens. resident_plan: the plan in one block of 128 threads (entry i per thread; groups in first-occurrence order, entries in increasing i, the same arrays) instead of one thread - 44 us -> a few us per call on gfx1151, 48 per window. Used by STRATA_VERIFY_DEVICE_PLAN=1 too. STRATA_VERIFY_QDEDUP=1: the experts' q8_1 image of the MoE input is made before the shared expert, whose gate/up read it instead of quantizing the same rows again (quantize_q8_1_rows and native_quantize_q8_1 write the same bytes); the shared expert's SwiGLU and its q8_1 run as one launch (native_swiglu_q8_1_kernel: the same expression, then native_quantize_q8_1_kernel's block quantizer); the BF16 copy of the input is skipped when the shared expert's native BF16 gate (which never reads it) is on. Same bytes, same tokens. Aurora (gfx1151, UD-IQ4_XS, S23's c-u4 config, one binary, env-only arms): output ids identical in every run. Per verify window (rocprofv3 trace, 8K prompt + 300 outputs, 114 windows): see aurora_s23.md (S26, overhead). --- include/strata/core/verify.hpp | 1 + include/strata/kernels/native_moe.hpp | 4 ++ include/strata/kernels/shared_expert.hpp | 6 +- src/core/verify.cpp | 64 ++++++++++++++++++--- src/kernels/cuda/native_moe.cu | 19 +++++- src/kernels/cuda/shared_expert.cu | 40 +++++++++++-- src/kernels/cuda/verify_kernels.cu | 73 +++++++++++++++++++++++- 7 files changed, 187 insertions(+), 20 deletions(-) diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index 5717eb4f..34f9ca90 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -174,6 +174,7 @@ private: int device_ = -1; ///< the device `init` ran on: run/commit switch to it (layer split) std::atomic released_{false}; ///< #267: release_gpu_waits ran (maybe on the watchdog thread): no more windows bool device_plan_ = false; ///< E-6: resident-only layers planned on the device (STRATA_VERIFY_DEVICE_PLAN) + bool resident_ = false; ///< STRATA_VERIFY_RESIDENT: every expert resident, no host step per layer uint32_t* skip_ = nullptr; ///< E-6: per group, the ring whose plan the device built (0: the host's) unsigned long long* slot_off_d_ = nullptr; ///< E-6: the slot offsets on the device int64_t lb_ = 0, le_ = -1; ///< set_stage: the layers this verifier runs (-1: to the last) diff --git a/include/strata/kernels/native_moe.hpp b/include/strata/kernels/native_moe.hpp index 34760efe..1e36dc11 100644 --- a/include/strata/kernels/native_moe.hpp +++ b/include/strata/kernels/native_moe.hpp @@ -18,4 +18,8 @@ void native_moe_combine(const float* parts, const float* weights, const float* s /// n_tok rows (parts [n,k,N], weights [n,k], shared/output [n,N]) in one launch, each as the single call. void native_moe_combine_multi(const float* parts, const float* weights, const float* shared, float* output, int64_t n_embd, int64_t k, int n_tok, void* stream); +/// STRATA_VERIFY_RESIDENT: the same, reading every part as `0.0f + hit[i]` - bitwise what a zeroed part row plus +/// moe_hit_add (parts += hit) gave, without the zero fill and the add launch. +void native_moe_combine_multi_hits(const float* hits, const float* weights, const float* shared, float* output, + int64_t n_embd, int64_t k, int n_tok, void* stream); } diff --git a/include/strata/kernels/shared_expert.hpp b/include/strata/kernels/shared_expert.hpp index 8909ed9e..e9148a10 100644 --- a/include/strata/kernels/shared_expert.hpp +++ b/include/strata/kernels/shared_expert.hpp @@ -24,6 +24,7 @@ namespace strata::kernels { /// Configure before session capture; captured graphs retain their selected kernels. /// In this mode shared_expert requires its optional unrounded x_f32 input. void shared_expert_set_native_bf16(bool enabled); +bool shared_expert_native_bf16(); ///< the native BF16 gate is on: x_bf16 is not read /// Optional native GGUF projections. Each supported type with nonnull data /// replaces only that canonical projection; absent or unsupported entries fall @@ -72,9 +73,12 @@ void shared_expert(const uint8_t* x_q8_0, const uint8_t* x_q8k, const uint16_t* /// multi-column MMVQ, so the weights are read once; every token is bitwise `shared_expert` on that token. /// `x` (n_tok, n_embd) f32, `x_bf16` the same rounded (only read when the native BF16 gate is off), `gate`/`up` /// (n_tok, n_ff) scratch, `g` n_tok floats, `out` (n_tok, n_embd). `nw.q8_1` must hold n_tok columns of n_embd. +/// x_q8_1_ready: the q8_1 image of x (n_tok rows), already quantized by the caller with the same quantizer (the +/// same bytes native_quantize_q8_1 writes): its gate/up read it and x is not quantized again, and the SwiGLU and +/// its q8_1 run as one launch (same values). Null: the separate launches. void shared_expert_multi(int n_tok, const float* x, const uint16_t* x_bf16, const NativeSharedWeights& nw, const uint16_t* gate_inp_bf16, float* gate, float* up, float* g, float* out, int64_t n_embd, - int64_t n_ff, void* stream); + int64_t n_ff, void* stream, const void* x_q8_1_ready = nullptr); /// The MoE block's final combination, `ref/moe.py::moe` L156: /// diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 999f85d8..f6f1a060 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -56,6 +56,7 @@ constexpr float EPS = 1e-6f; using Clock = std::chrono::steady_clock; double ms_since(Clock::time_point t) { return std::chrono::duration(Clock::now() - t).count(); } const bool g_dbg = std::getenv("STRATA_VERIFY_DEBUG") != nullptr; +const bool g_qdedup = [] { const char* v = std::getenv("STRATA_VERIFY_QDEDUP"); return v != nullptr && std::atoi(v) != 0; }(); #define VDBG(...) do { if (g_dbg) { std::fprintf(stderr, "verify dbg: " __VA_ARGS__); std::fflush(stderr); } } while (0) struct Bump { @@ -358,6 +359,25 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& const char* v = std::getenv("STRATA_VERIFY_DEVICE_PLAN"); device_plan_ = v != nullptr && std::atoi(v) != 0; } + // STRATA_VERIFY_RESIDENT=1 (opt-in): when EVERY routed expert of every layer is resident in the VRAM/UMA tier + // (checked here, once; a full cache never evicts), the window graph is recorded without the host round trip: + // no doorbell, no flag waits, no plan copy from mapped memory, no PCIe/CPU share (fetch, rebase, its grouped + // launch, the mapped-row copy); the device plans each group (the host's exact loop, E-6) and the combine reads + // the hit rows as `0.0f + hit` (what the zeroed CPU rows + moe_hit_add gave). Same tokens, same arithmetic. + { + const char* v = std::getenv("STRATA_VERIFY_RESIDENT"); + if (v != nullptr && std::atoi(v) != 0 && lb_ == 0 && le_ == g.n_layers && next_ == nullptr) { + std::vector res((size_t) (g.n_layers * g.n_expert)); + bool all = cudaMemcpy(res.data(), hits.d_res, res.size() * sizeof(int32_t), cudaMemcpyDeviceToHost) == + cudaSuccess; + for (size_t i = 0; all && i < res.size(); ++i) all = res[i] >= 0; + if (all) device_plan_ = true; + resident_ = all; + std::fprintf(stderr, "strata verify: STRATA_VERIFY_RESIDENT=1: %s\n", + all ? "every expert resident, the window runs without the host round trip" + : "not every expert is resident - the host-planned window stays"); + } + } if (device_plan_) { bool ok2 = cudaMalloc((void**) &skip_, 64) == cudaSuccess && cudaMemset(skip_, 0, 64) == cudaSuccess; if (ok2 && hits.slot_off != nullptr && hits.n_slots > 0) { @@ -365,7 +385,7 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& cudaMemcpy(slot_off_d_, hits.slot_off, (size_t) hits.n_slots * sizeof(unsigned long long), cudaMemcpyHostToDevice) == cudaSuccess; } - if (!ok2) { cudaGetLastError(); device_plan_ = false; } + if (!ok2) { cudaGetLastError(); device_plan_ = false; resident_ = false; } } std::fprintf(stderr, "strata verify: window up to %d tokens, %.1f MiB of device buffers\n", max_t, (double) count.used / 1048576.0); @@ -688,8 +708,9 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { hits_.cache_base, slot_off_d_, (long long) hits_.blob, plan_ + (size_t) grp * (size_t) (plan_i32_ + 16), (long long) max_t_ * K, skip_ + grp, (uint32_t) ((l - lb_) * G + grp + 1), cs); - doorbell_publish(xm, ids_ + tb * K, w_ + tb * K, (int64_t) n * N, (int64_t) n * K, m_x_ + tb * N, - m_ids_ + tb * K, m_w_ + tb * K, m_seq_, cs); + if (!resident_) // STRATA_VERIFY_RESIDENT: no host step, so no doorbell + doorbell_publish(xm, ids_ + tb * K, w_ + tb * K, (int64_t) n * N, (int64_t) n * K, m_x_ + tb * N, + m_ids_ + tb * K, m_w_ + tb * K, m_seq_, cs); stamp(l, 17, grp); { const WeightRef *wgi = need(v, "ffn_gate_inp_shexp.weight", err), *wsg = need(v, "ffn_gate_shexp.weight", err), @@ -703,19 +724,28 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { nsw.up_type = wsu->native_type; nsw.up_data = wsu->native_data; nsw.down_type = wsd->native_type; nsw.down_data = wsd->native_data; nsw.q8_1 = xq_; + // STRATA_VERIFY_QDEDUP=1: the experts' q8_1 image of xm is made first and the shared expert's gate/up + // read it (quantize_q8_1_rows and native_quantize_q8_1 write the same bytes), and the BF16 copy of xm + // is skipped when the shared expert's native BF16 gate (which never reads it) is on. + const bool qdedup = g_qdedup && strata::kernels::cpu::expert_layout().native; + if (qdedup) quantize_q8_1_rows(xm, n, N, nat_xq_ + (size_t) tb * (N / 32) * 36, cs); + if (!(qdedup && shared_expert_native_bf16())) { if (dec_batch) f32_to_bf16_bulk(mixed_ + tb * N, sh_bf16_ + tb * N, (int64_t) n * N, cs); // contiguous rows else for (int t = tb; t < te; ++t) f32_to_bf16_bulk(mixed_ + t * N, sh_bf16_ + t * N, N, cs); + } try { shared_expert_multi(n, xm, sh_bf16_ + tb * N, nsw, (const uint16_t*) wgi->data, sh_gate_ + (size_t) tb * g.n_ff, - sh_up_ + (size_t) tb * g.n_ff, sh_g_ + tb, shared_ + tb * N, N, g.n_ff, cs); + sh_up_ + (size_t) tb * g.n_ff, sh_g_ + tb, shared_ + tb * N, N, g.n_ff, cs, + qdedup ? (const void*) (nat_xq_ + (size_t) tb * (N / 32) * 36) : nullptr); } catch (const std::exception& e) { err = std::string("verify shared expert: ") + e.what(); return false; } } - if (strata::kernels::cpu::expert_layout().native) - quantize_q8_1_rows(xm, n, N, nat_xq_ + (size_t) tb * (N / 32) * 36, cs); - else + if (strata::kernels::cpu::expert_layout().native) { + if (!(g_qdedup && strata::kernels::cpu::expert_layout().native)) + quantize_q8_1_rows(xm, n, N, nat_xq_ + (size_t) tb * (N / 32) * 36, cs); + } else quantize_q8_0_scaled(xm, hit_xq_ + (size_t) tb * (N / 32) * 34, hit_xs_ + (size_t) tb * (N / 32), (int64_t) n * N, cs); stamp(l, 18, grp); return true; @@ -727,7 +757,9 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { const uint32_t ring = (uint32_t) ((l - lb_) * G + grp + 1); const int64_t cap = (int64_t) n * K, capx = (int64_t) max_t_ * K; int32_t* pl = plan_ + (size_t) grp * (size_t) (plan_i32_ + 16); - if (device_plan_) { // E-6: skipped when the device planned this group (all its experts resident) + if (resident_) { + // STRATA_VERIFY_RESIDENT: resident_plan (pre) wrote this group's plan into `pl`; nothing to wait for + } else if (device_plan_) { // E-6: skipped when the device planned this group (all its experts resident) wait_flag_ge_or(m_flagA_, ring, skip_ + grp, cs); copy_i32_from_mapped_unless(pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, skip_ + grp, ring, cs); } else { @@ -760,6 +792,18 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { }; grouped(p_ptr, p_start, p_counts); stamp(l, 20, grp); + if (resident_ && native_moe_combine_enabled()) { + // every row is a hit: combine straight from hit_out as 0.0f + hit (= the zeroed row + moe_hit_add) + try { + native_moe_combine_multi_hits(hit_out, w_ + tb * K, shared_ + tb * N, bo_ + tb * N, N, K, n, cs); + } catch (const std::exception& e) { err = "verify combine: " + std::string(e.what()); return false; } + } else { + if (resident_) { + if (cudaMemsetAsync(parts_ + (size_t) tb * K * N, 0, sizeof(float) * (size_t) n * K * N, cs) != cudaSuccess) { + err = "verify: zeroing the parts failed"; + return false; + } + } else { if (device_plan_) wait_flag_ge_or(m_flagB_, ring, skip_ + grp, cs); else wait_flag_ge(m_flagB_, ring, cs); // the PCIe share is in staging (DMA) or mapped if (sink_.pcie_mode == 2) { // stage it with a copy kernel, then point at staging @@ -784,6 +828,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { else copy_from_mapped(parts_ + (size_t) tb * K * N, m_ymiss_ + (size_t) tb * K * N, (int64_t) n * K * N, cs); } + } // !resident_ moe_hit_add(parts_ + (size_t) tb * K * N, hit_out, p_dst, p_counts + 1, cap, N, cs); if (dec_batch && n > 1 && native_moe_combine_enabled()) { // one launch for the window's rows try { @@ -795,6 +840,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { mb.weights = w_ + t * K; mb.shared = shared_ + t * N; if (!moe_combine_parts(g, l, K, mb, parts_ + (size_t) t * K * N, bo_ + t * N, cs, err)) return false; } + } // the resident combine from hit_out stamp(l, 24, grp); if (l == g.n_layers - 1) { for (int t = tb; t < te; ++t) gr_write(Rt(t), bo_ + t * N, inj2_ + t * HC, gs, Rt(t), cs); @@ -1063,7 +1109,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, volatile uint32_t* const flag = h_flag_; const int G = groups_[T] > 0 ? groups_[T] : 1; const int gtb[2] = {0, (T + 1) / 2}, gte[2] = {G == 2 ? (T + 1) / 2 : T, T}; - const int64_t steps = (le_ - lb_) * G; + const int64_t steps = resident_ ? 0 : (le_ - lb_) * G; // STRATA_VERIFY_RESIDENT: the GPU never rings const bool test_stall = g_test_stall > 0 && windows + 1 == g_test_stall; // #267 test hook (off: false) for (int64_t k = 0; k < steps; ++k) { const int64_t l = lb_ + k / G; diff --git a/src/kernels/cuda/native_moe.cu b/src/kernels/cuda/native_moe.cu index 7f1f91ce..a8fa4337 100644 --- a/src/kernels/cuda/native_moe.cu +++ b/src/kernels/cuda/native_moe.cu @@ -31,6 +31,7 @@ namespace strata::kernels { namespace { std::atomic enabled{false}; +template __global__ void combine(const float* __restrict__ parts, const float* __restrict__ weights, const float* __restrict__ shared, float* __restrict__ output, int64_t n_embd, int k) { @@ -39,9 +40,14 @@ __global__ void combine(const float* __restrict__ parts, const float* __restrict parts += tk * k * n_embd; weights += tk * k; if (shared) shared += tk * n_embd; output += tk * n_embd; const int64_t col = int64_t(blockIdx.x) * blockDim.x + threadIdx.x; if (col >= n_embd) return; - float sum = parts[col] * weights[0]; + // ZADD: a part is 0.0f + hit (the zeroed row plus moe_hit_add of the verify window), rounded as that add + float p0 = parts[col]; + if (ZADD) p0 = 0.0f + p0; + float sum = p0 * weights[0]; for (int expert = 1; expert < k; ++expert) { - sum += parts[int64_t(expert) * n_embd + col] * weights[expert]; + float p = parts[int64_t(expert) * n_embd + col]; + if (ZADD) p = 0.0f + p; + sum += p * weights[expert]; } if (shared) sum += shared[col]; output[col] = sum; @@ -83,4 +89,13 @@ void native_moe_combine_multi(const float* parts, const float* weights, const fl const auto error = cudaGetLastError(); if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); } +void native_moe_combine_multi_hits(const float* hits, const float* weights, const float* shared, float* output, + int64_t n_embd, int64_t k, int n_tok, void* stream) { + if (!stream || n_embd <= 0 || k < 1 || k > 15 || n_tok < 1) + throw std::invalid_argument("native MoE combine (hits) requires a stream, width, 1..15 experts, tokens"); + combine<<(stream)>>>( + hits, weights, shared, output, n_embd, int(k)); + const auto error = cudaGetLastError(); + if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); +} } diff --git a/src/kernels/cuda/shared_expert.cu b/src/kernels/cuda/shared_expert.cu index d795bf84..1bb5c997 100644 --- a/src/kernels/cuda/shared_expert.cu +++ b/src/kernels/cuda/shared_expert.cu @@ -27,6 +27,7 @@ #include "strata/kernels/s_gemv.hpp" #include "strata/kernels/native_mmvq.hpp" +#include #include #include @@ -68,6 +69,27 @@ __global__ void native_swiglu_kernel(const float* gate, const float* up, float* out[i] = __fdividef(gate[i], 1.0f + __expf(-gate[i])) * up[i]; } + +// STRATA_VERIFY_QDEDUP: native_swiglu_kernel and native_quantize_q8_1_kernel in one launch. Each thread computes +// the same swiglu expression (and still writes it to `out`), then the 32-lane block's q8_1 exactly as +// native_quantize_q8_1_kernel does (XOR-tree max / sum, d = amax / 127, roundf(x / d), ds = (d, sum)). +struct SwqQ81 { half2 ds; int8_t qs[32]; }; +__global__ void native_swiglu_q8_1_kernel(const float* gate, const float* up, float* out, SwqQ81* __restrict__ y, + int n) { + const int i = blockIdx.x * 256 + threadIdx.x; + if (i >= n) return; // n is a multiple of 32: only whole warps return + const float xi = __fdividef(gate[i], 1.0f + __expf(-gate[i])) * up[i]; + out[i] = xi; + float amax = fabsf(xi), sum = xi; +#pragma unroll + for (int offset = 16; offset > 0; offset >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffff, amax, offset, 32)); +#pragma unroll + for (int offset = 16; offset > 0; offset >>= 1) sum += __shfl_xor_sync(0xffffffff, sum, offset, 32); + const float d = amax / 127.0f; + const int8_t q = amax == 0.0f ? 0 : roundf(xi / d); + y[i / 32].qs[i % 32] = q; + if (i % 32 == 0) y[i / 32].ds = make_half2(d, sum); +} __global__ void to_f16_kernel(const float* __restrict__ in, uint16_t* __restrict__ out, int n) { const int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < n) out[i] = f16_from_f32(in[i]); @@ -157,6 +179,7 @@ __global__ void moe_combine_kernel(const float* __restrict__ parts, const float* } // namespace void shared_expert_set_native_bf16(bool enabled) { native_bf16 = enabled; } +bool shared_expert_native_bf16() { return native_bf16; } namespace { __global__ void scale_rows_kernel(float* __restrict__ out, const float* __restrict__ g, int n) { @@ -168,16 +191,21 @@ __global__ void scale_rows_kernel(float* __restrict__ out, const float* __restri void shared_expert_multi(int n_tok, const float* x, const uint16_t* x_bf16, const NativeSharedWeights& nw, const uint16_t* gate_inp_bf16, float* gate, float* up, float* g, float* out, int64_t n_embd, - int64_t n_ff, void* stream) { + int64_t n_ff, void* stream, const void* x_q8_1_ready) { if (n_tok < 1 || n_tok > 8 || !nw.q8_1 || !nw.gate_data || !nw.up_data || !nw.down_data || !stream) throw std::invalid_argument("shared_expert_multi: needs 1..8 tokens, native weights, scratch and a stream"); cudaStream_t cs = (cudaStream_t) stream; - native_quantize_q8_1(x, nw.q8_1, (int) n_embd, n_tok, stream); - native_mmvq(nw.gate_type, nw.gate_data, nw.q8_1, gate, (int) n_embd, (int) n_ff, n_tok, stream); - native_mmvq(nw.up_type, nw.up_data, nw.q8_1, up, (int) n_embd, (int) n_ff, n_tok, stream); + const void* xq = x_q8_1_ready ? x_q8_1_ready : nw.q8_1; + if (!x_q8_1_ready) native_quantize_q8_1(x, nw.q8_1, (int) n_embd, n_tok, stream); + native_mmvq(nw.gate_type, nw.gate_data, xq, gate, (int) n_embd, (int) n_ff, n_tok, stream); + native_mmvq(nw.up_type, nw.up_data, xq, up, (int) n_embd, (int) n_ff, n_tok, stream); const int n = (int) (n_ff * n_tok); - native_swiglu_kernel<<<(unsigned) ((n + THREADS - 1) / THREADS), THREADS, 0, cs>>>(gate, up, gate, n); - native_quantize_q8_1(gate, nw.q8_1, (int) n_ff, n_tok, stream); + if (x_q8_1_ready != nullptr && (n_ff % 32) == 0) { // STRATA_VERIFY_QDEDUP: swiglu + its q8_1 in one launch + native_swiglu_q8_1_kernel<<<(unsigned) ((n + 255) / 256), 256, 0, cs>>>(gate, up, gate, (SwqQ81*) nw.q8_1, n); + } else { + native_swiglu_kernel<<<(unsigned) ((n + THREADS - 1) / THREADS), THREADS, 0, cs>>>(gate, up, gate, n); + native_quantize_q8_1(gate, nw.q8_1, (int) n_ff, n_tok, stream); + } native_mmvq(nw.down_type, nw.down_data, nw.q8_1, out, (int) n_ff, (int) n_embd, n_tok, stream); static const bool batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }(); if (native_bf16 && batch && n_tok > 1) { // one gemv for all rows (outputs identical), one sigmoid launch diff --git a/src/kernels/cuda/verify_kernels.cu b/src/kernels/cuda/verify_kernels.cu index 7908ce40..1272f7e0 100644 --- a/src/kernels/cuda/verify_kernels.cu +++ b/src/kernels/cuda/verify_kernels.cu @@ -471,6 +471,71 @@ __global__ void resident_plan_kernel(const int32_t* __restrict__ ids, int n, int __threadfence(); *skip = ring; } +// The same plan in one block of 128 threads (n <= 128): thread i owns entry i. Groups are the distinct experts in +// order of first occurrence; group g's entries are its occurrences in increasing i - exactly the loop above +// (S26: the one-thread loop took ~44 us per call on gfx1151, 48 per window). +__global__ void resident_plan_par_kernel(const int32_t* __restrict__ ids, int n, int k, const int32_t* __restrict__ res, + int n_expert, const uint8_t* cache_base, const unsigned long long* slot_off, + long long blob, int32_t* __restrict__ pl, long long capx, uint32_t* skip, + uint32_t ring) { + __shared__ int32_t s_id[128]; + __shared__ int s_first[128], s_size[128]; + __shared__ int s_bad; + const int i = threadIdx.x; + if (i == 0) s_bad = 0; + __syncthreads(); + int32_t e = -1; + if (i < n) { + e = ids[i]; + s_id[i] = e; + if (e < 0 || e >= n_expert || res[e] < 0) s_bad = 1; + } + __syncthreads(); + if (s_bad) { if (i == 0) *skip = 0; return; } + int first = i, rank = 0, size = 0; + if (i < n) { + for (int j = 0; j < n; ++j) { + const bool same = s_id[j] == e; + if (same && j < first) first = j; + if (same && j < i) ++rank; + size += same; + } + } + if (i < n) { s_first[i] = first; s_size[i] = size; } + __syncthreads(); + int32_t* counts = pl; + int32_t* start = pl + 4; + int32_t* dst = start + capx + 1; + int32_t* tok = dst + capx; + const long long ptr_off = ((4 + (capx + 1) + 2 * capx) + 1) & ~1ll; + unsigned long long* ptr = (unsigned long long*) (pl + ptr_off); + int32_t* start2 = pl + ptr_off + 4 * capx; + if (i < n) { + // group of entry i = the number of first occurrences before `first`; its start = their sizes' sum + int group = 0, gstart = 0; + for (int j = 0; j < first; ++j) + if (s_first[j] == j) { ++group; gstart += s_size[j]; } + if (i == first) { + const int32_t slot = res[e]; + ptr[group] = (unsigned long long) (cache_base + (slot_off ? (size_t) slot_off[slot] : (size_t) slot * (size_t) blob)); + start[group] = gstart; + } + dst[gstart + rank] = i; + tok[gstart + rank] = i / k; + if (i == 0) { + int groups = 0; + for (int j = 0; j < n; ++j) groups += s_first[j] == j; + start[groups] = n; + start2[0] = n; + counts[0] = groups; + counts[1] = n; + counts[2] = 0; + } + } + __threadfence(); + __syncthreads(); + if (i == 0) *skip = ring; +} __global__ void wait_flag_ge_or_kernel(const volatile uint32_t* flag, uint32_t value, const volatile uint32_t* skip) { if (*skip == value) return; while (*flag < value) strata_spin_pause(); @@ -492,8 +557,12 @@ __global__ void copy_or_zero_kernel(float4* __restrict__ dst, const volatile flo void resident_plan(const int32_t* ids, int n_entries, int k, const int32_t* res_layer, int n_expert, const uint8_t* cache_base, const unsigned long long* slot_off, long long blob, int32_t* plan, long long capx, uint32_t* skip, uint32_t ring, void* stream) { - resident_plan_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(ids, n_entries, k, res_layer, n_expert, cache_base, slot_off, - blob, plan, capx, skip, ring); + if (n_entries <= 128) + resident_plan_par_kernel<<<1, 128, 0, (cudaStream_t) stream>>>(ids, n_entries, k, res_layer, n_expert, cache_base, + slot_off, blob, plan, capx, skip, ring); + else + resident_plan_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(ids, n_entries, k, res_layer, n_expert, cache_base, slot_off, + blob, plan, capx, skip, ring); check("resident_plan"); } void wait_flag_ge_or(const uint32_t* flag, uint32_t value, const uint32_t* skip, void* stream) { From 5cf0079bcc4f2c051f437f9ede8e85bb2e1172aa Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 03:28:31 +0000 Subject: [PATCH 26/55] HIP: the packed Q6_K heads (opt-in STRATA_Q6_PACKED=1), bitwise The main output head (248320 x 2560) and the MTP draft head (its 106299-row subset) are Q6_K: 210-byte blocks, so every int load is 2-byte aligned. STRATA_Q6_PACKED=1 builds a packed copy of each at load - the same bytes as ql / qh / scales / d planes (+497 MiB, +213 MiB) - and native_q6_k_mmvq on a registered pointer runs native_q6_k_packed_kernel: aligned non-temporal dword loads, 640 persistent workgroups, and the thread ownership, q6_q8_dot_impl expression, accumulation order and reduction of native_q6_k_mmvq_kernel / native_mmvq_multi_kernel, so every output is bitwise equal (exact multi-column layout only). STRATA_Q6P_SELFTEST=1 checks it at load (1-4 columns, memcmp) and times it paired; =2 also sweeps the grid. gfx1151 load-time self-test (11 paired samples, medians): main head 1 column 2420 -> 2300 us, 2 columns 2563 -> 2455, 4 columns 2973 -> 2975 (no gain: not bandwidth-bound there); draft head 1 column 1319-1351 -> 946-961 us, 2 columns 1420-1459 -> 1064-1090, 4 columns 1629-1678 -> 1320-1365. Outputs bitwise equal. Grid 320-20480 flat. --- include/strata/kernels/native_mmvq.hpp | 8 + src/core/mtp.cpp | 5 +- src/core/native_head.cpp | 3 + src/kernels/cuda/native_mmvq.cu | 246 +++++++++++++++++++++++++ 4 files changed, 261 insertions(+), 1 deletion(-) diff --git a/include/strata/kernels/native_mmvq.hpp b/include/strata/kernels/native_mmvq.hpp index a8894d73..dfb8db5e 100644 --- a/include/strata/kernels/native_mmvq.hpp +++ b/include/strata/kernels/native_mmvq.hpp @@ -100,6 +100,14 @@ void native_q8_0_pack_host(const void* gguf_blocks, void* out, int n_in, int n_o void native_q8_0_packed_register(const void* gguf_weights, const void* packed, int n_in, int n_out); void native_q8_0_packed_unregister(const void* gguf_weights); +/// STRATA_Q6_PACKED=1 (opt-in): a packed copy of a Q6_K matrix (the output heads) - the same bytes as ql / qh / +/// scales / d planes - that native_q6_k_mmvq calls on `weights` read instead (bitwise equal outputs). The copy is +/// owned here: native_q6_k_pack builds it from the device matrix (false: not eligible or failed; nothing changes), +/// native_q6_k_unpack frees it. STRATA_Q6P_SELFTEST=1 checks it bitwise and times it at load. +bool native_q6_k_packed_enabled(); +bool native_q6_k_pack(const void* weights, int n_in, int n_out, const char* what); +void native_q6_k_unpack(const void* weights); + void native_q8_0_f32(const void* weights, const float* x, void* scratch_q8_1, float* y, int n_in, int n_out, int ncols, void* stream); diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp index e2b89b6f..cf490bbd 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -120,7 +120,7 @@ MtpDrafter::~MtpDrafter() { if (state_arena_) cudaFree(state_arena_); if (arena_) cudaFree(arena_); if (head_logits_) cudaFree(head_logits_); - if (dhead_) cudaFree(dhead_); + if (dhead_) { strata::kernels::native_q6_k_unpack(dhead_); cudaFree(dhead_); } if (dvocab_) cudaFree(dvocab_); void* hosts[] = {h_tok_, h_step_, h_pos_, h_row_, h_out_, h_prob_}; for (void* h : hosts) if (h) cudaFreeHost(h); @@ -443,6 +443,9 @@ bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float vram_ += (uint64_t) (n_dvocab_ * row_bytes) + raw.size(); std::fprintf(stderr, "strata mtp: draft head over %lld tokens (%.1f MiB)\n", (long long) n_dvocab_, (double) (n_dvocab_ * row_bytes) / 1048576.0); + if (head->type() == 14 && strata::kernels::native_q6_k_packed_enabled()) // STRATA_Q6_PACKED=1 + strata::kernels::native_q6_k_pack(dhead_, (int) (row_bytes / 210) * 256, (int) n_dvocab_, + "MTP draft head"); } } if (coupled_draft_env() && cparams_ == nullptr && !setup_coupled(err)) return false; diff --git a/src/core/native_head.cpp b/src/core/native_head.cpp index acb4f81f..7c976b2d 100644 --- a/src/core/native_head.cpp +++ b/src/core/native_head.cpp @@ -12,6 +12,7 @@ namespace strata::core { NativeHead::~NativeHead() { + if (weights_) strata::kernels::native_q6_k_unpack(weights_); if (scratch_) cudaFree(scratch_); if (weights_) cudaFree(weights_); } @@ -61,6 +62,8 @@ bool NativeHead::load(const std::vector& shards, int64_t n_in, int6 n_in_ = (int) n_in; n_out_ = (int) n_out; type_ = (int) tensor->type; + if (type_ == 14 && strata::kernels::native_q6_k_packed_enabled()) // STRATA_Q6_PACKED=1 + strata::kernels::native_q6_k_pack(weights_, n_in_, n_out_, "output head"); return true; } catch (const std::exception& error) { err = std::string("native head: ") + error.what(); diff --git a/src/kernels/cuda/native_mmvq.cu b/src/kernels/cuda/native_mmvq.cu index eac781e4..175ca08d 100644 --- a/src/kernels/cuda/native_mmvq.cu +++ b/src/kernels/cuda/native_mmvq.cu @@ -38,6 +38,8 @@ #include #include #include +#include +#include namespace strata::kernels { namespace { @@ -1250,6 +1252,122 @@ bool q8_packed_mmvq(const void* weights, const void* x_q8_1, float* y, int n_in, return true; } + +// ============================ STRATA_Q6_PACKED=1: the packed Q6_K head layout (opt-in) ============================ +// +// The output heads (the main head, 248320 rows, and the MTP draft head's row subset) are Q6_K matrices of 2560-wide +// rows: 10 blocks of 210 bytes each, so every int load is 2-byte aligned and a row is 2100 bytes. The packed copy +// holds the SAME bytes as four planes - ql (128 B per block), qh (64 B), scales (16 B), d (2 B) - so a thread's +// two words are aligned dword loads (non-temporal). Thread ownership (block tid / 32 + 4 i, word tid % 32), the +// q6_q8_dot_impl expression, the per-thread order and the reduction are those of native_q6_k_mmvq_kernel / +// native_mmvq_multi_kernel: every output is bitwise equal. Persistent workgroups. +int g_q6p_grid_override = 0; // the self-test's grid sweep (STRATA_Q6P_SELFTEST=2) +int q6p_grid() { + if (g_q6p_grid_override > 0) return g_q6p_grid_override; + static const int grid = [] { + const char* v = std::getenv("STRATA_Q6P_GRID"); + const int g = v ? std::atoi(v) : 0; + return g > 0 ? g : 640; + }(); + return grid; +} + +template +__launch_bounds__(WARPS * WARP, 1) +__global__ void native_q6_k_packed_kernel(const int* __restrict__ ql, const int* __restrict__ qh, + const int8_t* __restrict__ sc, const half* __restrict__ dpl, + const Q81Block* __restrict__ x, float* __restrict__ y, + int n_in, int n_out, int row_step) { + const int tid = WARP * int(threadIdx.y) + int(threadIdx.x); + const int nb = n_in / 256; + const int x_stride = n_in / Q8K; + const int iqs = tid % 32; + const int bq8_offset = 4 * (iqs / 16) + (iqs % 16) / 8; + const int scale_offset = 8 * (iqs / 16) + (iqs % 16) / 4; + const int vh_shift = 2 * ((iqs % 16) / 8); + const int qh_word = 8 * (iqs / 16) + iqs % 8; + __shared__ float partial[2][WARPS - 1][NCOLS][WARP]; + int buf = 0; + for (int row = int(blockIdx.x); row < n_out; row += row_step, buf ^= 1) { + float tmp[NCOLS] = {}; + for (int kbx = tid / 32; kbx < nb; kbx += WARPS * WARP / 32) { + const std::size_t block = std::size_t(row) * nb + kbx; + const int vl = STRATA_Q8P_LOAD(ql + block * 32 + iqs); + const int vh = STRATA_Q8P_LOAD(qh + block * 16 + qh_word) >> vh_shift; + const int8_t* scales = sc + block * 16 + scale_offset; + const float d = dpl[block]; + const int kby = kbx * 8; +#pragma unroll + for (int j = 0; j < NCOLS; ++j) { + const Q81Block* xb = x + std::size_t(j) * x_stride + kby; + int u[2]; + float d8[2]; +#pragma unroll + for (int i = 0; i < 2; ++i) { + u[i] = reinterpret_cast(xb[bq8_offset + 2 * i].qs)[iqs % 8]; + d8[i] = __low2float(xb[bq8_offset + 2 * i].ds); + } + tmp[j] += q6_q8_dot_impl(vl, vh, u, scales, d, d8); + } + } + if (threadIdx.y > 0) { +#pragma unroll + for (int j = 0; j < NCOLS; ++j) partial[buf][threadIdx.y - 1][j][threadIdx.x] = tmp[j]; + } + __syncthreads(); + if (threadIdx.y == 0) { +#pragma unroll + for (int j = 0; j < NCOLS; ++j) { +#pragma unroll + for (int l = 0; l < WARPS - 1; ++l) tmp[j] += partial[buf][l][j][threadIdx.x]; + tmp[j] = warp_sum(tmp[j]); + if (threadIdx.x == 0) y[std::size_t(j) * n_out + row] = tmp[j]; + } + } + } +} + +bool g_q6_bypass = false; // the load-time self-test times the GGUF-layout kernels with the copy registered + +// the packed planes of one Q6_K matrix (owned: allocated by native_q6_k_pack, freed by native_q6_k_unpack) +struct Q6Packed { void* base; const int* ql; const int* qh; const int8_t* sc; const half* d; int n_in, n_out; }; +std::unordered_map& q6_packed_registry() { + static std::unordered_map registry; + return registry; +} + +template +void q6_packed_launch(const Q6Packed& w, const Q81Block* x, float* y, cudaStream_t s) { + const int grid = (std::min)(w.n_out, q6p_grid()); + native_q6_k_packed_kernel<<>>(w.ql, w.qh, w.sc, w.d, x, y, w.n_in, + w.n_out, grid); +} + +bool q6_packed_mmvq(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) { + auto& registry = q6_packed_registry(); + if (registry.empty() || g_q6_bypass || (ncols > 1 && !g_multi_exact)) return false; + const auto found = registry.find(weights); + if (found == registry.end() || found->second.n_in != n_in || found->second.n_out != n_out) return false; + validate_shape(n_in, ncols, 256); + validate_pointer(x_q8_1); + validate_pointer(y); + validate_stream(stream); + const auto* x = static_cast(x_q8_1); + const auto s = static_cast(stream); + switch (ncols) { + case 1: q6_packed_launch<1>(found->second, x, y, s); break; + case 2: q6_packed_launch<2>(found->second, x, y, s); break; + case 3: q6_packed_launch<3>(found->second, x, y, s); break; + case 4: q6_packed_launch<4>(found->second, x, y, s); break; + case 5: q6_packed_launch<5>(found->second, x, y, s); break; + case 6: q6_packed_launch<6>(found->second, x, y, s); break; + case 7: q6_packed_launch<7>(found->second, x, y, s); break; + case 8: q6_packed_launch<8>(found->second, x, y, s); break; + default: throw std::invalid_argument("native MMVQ requires 1 <= ncols <= 8"); + } + launch_check(); + return true; +} } // namespace bool native_q8_0_packed_enabled() { @@ -1287,6 +1405,133 @@ void native_q8_0_packed_register(const void* gguf_weights, const void* packed, i void native_q8_0_packed_unregister(const void* gguf_weights) { q8_packed_registry().erase(gguf_weights); } +bool native_q6_k_packed_enabled() { + static const bool enabled = [] { + const char* v = std::getenv("STRATA_Q6_PACKED"); + return v && v[0] == '1' && v[1] == '\0'; + }(); + return enabled; +} + +bool native_q6_k_pack(const void* weights, int n_in, int n_out, const char* what) { + if (!weights || n_in <= 0 || n_in % 256 || n_in / 256 < WARPS * WARP / 32 || n_out < 2048) return false; + if (q6_packed_registry().count(weights)) return true; + const std::size_t nb = std::size_t(n_in / 256) * std::size_t(n_out); + const std::size_t bytes = nb * sizeof(Q6KBlock); + std::vector host(nb); + if (cudaMemcpy(host.data(), weights, bytes, cudaMemcpyDeviceToHost) != cudaSuccess) { cudaGetLastError(); return false; } + // planes: ql | qh | scales | d, each 256-byte aligned + const std::size_t o_qh = (nb * 128 + 255) & ~std::size_t(255); + const std::size_t o_sc = (o_qh + nb * 64 + 255) & ~std::size_t(255); + const std::size_t o_d = (o_sc + nb * 16 + 255) & ~std::size_t(255); + const std::size_t total = o_d + nb * 2; + std::vector packed(total, 0); + for (std::size_t b = 0; b < nb; ++b) { + std::memcpy(packed.data() + b * 128, host[b].ql, 128); + std::memcpy(packed.data() + o_qh + b * 64, host[b].qh, 64); + std::memcpy(packed.data() + o_sc + b * 16, host[b].scales, 16); + std::memcpy(packed.data() + o_d + b * 2, &host[b].d, 2); + } + void* dev = nullptr; + if (cudaMalloc(&dev, total) != cudaSuccess) { cudaGetLastError(); return false; } + if (cudaMemcpy(dev, packed.data(), total, cudaMemcpyHostToDevice) != cudaSuccess) { + cudaFree(dev); cudaGetLastError(); return false; + } + auto* base = static_cast(dev); + q6_packed_registry()[weights] = Q6Packed{dev, reinterpret_cast(base), + reinterpret_cast(base + o_qh), + reinterpret_cast(base + o_sc), + reinterpret_cast(base + o_d), n_in, n_out}; + std::fprintf(stderr, "strata: STRATA_Q6_PACKED=1 packed the %s (%d x %d, +%.1f MiB)\n", what, n_out, n_in, + total / 1048576.0); + // STRATA_Q6P_SELFTEST=1: bitwise check against the GGUF-layout kernels (1..4 columns) and paired timings + if (const char* v = std::getenv("STRATA_Q6P_SELFTEST"); v && (v[0] == '1' || v[0] == '2')) { + cudaStream_t s = nullptr; + cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking); + const int nq = n_in / Q8K; + std::vector hx(std::size_t(4) * nq); + uint32_t r = 12345u; + for (auto& blk : hx) { + for (auto& q : blk.qs) { r = r * 1664525u + 1013904223u; q = int8_t(int((r >> 24) & 255u) - 128); } + r = r * 1664525u + 1013904223u; + blk.ds = __floats2half2_rn(0.001f + float(r >> 8) * 1e-9f, 0.0f); + } + void *dx = nullptr, *ya = nullptr, *yb = nullptr; + cudaMalloc(&dx, hx.size() * sizeof(Q81Block)); + cudaMalloc(&ya, std::size_t(4) * n_out * 4); + cudaMalloc(&yb, std::size_t(4) * n_out * 4); + cudaMemcpy(dx, hx.data(), hx.size() * sizeof(Q81Block), cudaMemcpyHostToDevice); + std::vector a(std::size_t(4) * n_out), c(std::size_t(4) * n_out); + bool same = true; + for (int nc = 1; nc <= 4; ++nc) { + g_q6_bypass = true; + native_q6_k_mmvq(weights, dx, (float*) ya, n_in, n_out, nc, s); + g_q6_bypass = false; + native_q6_k_mmvq(weights, dx, (float*) yb, n_in, n_out, nc, s); + cudaStreamSynchronize(s); + cudaMemcpy(a.data(), ya, std::size_t(nc) * n_out * 4, cudaMemcpyDeviceToHost); + cudaMemcpy(c.data(), yb, std::size_t(nc) * n_out * 4, cudaMemcpyDeviceToHost); + same = same && std::memcmp(a.data(), c.data(), std::size_t(nc) * n_out * 4) == 0; + } + cudaEvent_t e0, e1; + cudaEventCreate(&e0); cudaEventCreate(&e1); + for (int nc : {1, 2, 4}) { + std::vector tb, tc; + for (int k = 0; k < 11; ++k) { + for (int pass = 0; pass < 2; ++pass) { + const bool cand = (pass == 0) == (k % 2 == 1); + g_q6_bypass = !cand; + cudaEventRecord(e0, s); + for (int it = 0; it < 5; ++it) native_q6_k_mmvq(weights, dx, (float*) (cand ? yb : ya), n_in, n_out, nc, s); + cudaEventRecord(e1, s); + cudaEventSynchronize(e1); + float ms = 0; cudaEventElapsedTime(&ms, e0, e1); + (cand ? tc : tb).push_back(ms * 1000.0f / 5); + } + } + g_q6_bypass = false; + std::sort(tb.begin(), tb.end()); std::sort(tc.begin(), tc.end()); + std::fprintf(stderr, "strata: Q6_K packed self-test %s ncols %d: GGUF %.1f us (%.1f-%.1f), packed %.1f us " + "(%.1f-%.1f), 11 paired samples\n", what, nc, tb[5], tb[0], tb[10], tc[5], tc[0], tc[10]); + } + std::fprintf(stderr, "strata: Q6_K packed self-test %s: outputs %s (1-4 columns)\n", what, + same ? "BITWISE EQUAL" : "DIFFER"); + if (v[0] == '2') { // grid sweep of the packed kernel + for (int grid : {160, 320, 640, 1280, 2560, 5120, 20480}) { + g_q6p_grid_override = grid; + for (int nc : {1, 2, 4}) { + std::vector tc; + for (int k = 0; k < 7; ++k) { + cudaEventRecord(e0, s); + for (int it = 0; it < 5; ++it) native_q6_k_mmvq(weights, dx, (float*) yb, n_in, n_out, nc, s); + cudaEventRecord(e1, s); + cudaEventSynchronize(e1); + float ms = 0; cudaEventElapsedTime(&ms, e0, e1); + tc.push_back(ms * 1000.0f / 5); + } + std::sort(tc.begin(), tc.end()); + std::fprintf(stderr, "strata: Q6_K packed grid sweep %s grid %d ncols %d: %.1f us (%.1f-%.1f)\n", + what, grid, nc, tc[3], tc[0], tc[6]); + } + } + g_q6p_grid_override = 0; + } + cudaEventDestroy(e0); cudaEventDestroy(e1); + cudaFree(dx); cudaFree(ya); cudaFree(yb); + cudaStreamDestroy(s); + if (!same) { native_q6_k_unpack(weights); return false; } + } + return true; +} + +void native_q6_k_unpack(const void* weights) { + auto& registry = q6_packed_registry(); + const auto found = registry.find(weights); + if (found == registry.end()) return; + cudaFree(found->second.base); + registry.erase(found); +} + void native_mmvq_set_multi_exact(bool exact) { g_multi_exact = exact; } bool native_mmvq_multi_exact() { return g_multi_exact; } @@ -1507,6 +1752,7 @@ void native_q4_k_f32(const void* weights, const float* x, void* scratch_q8_1, void native_q6_k_mmvq(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) { + if (q6_packed_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream)) return; // STRATA_Q6_PACKED=1 heads validate_shape(n_in, ncols, 256); if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); validate_pointer(weights); From e3c3d6bade73619e20c15f8d6cbd1cc57733a4c6 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 05:35:38 +0200 Subject: [PATCH 27/55] GDN verify step: each head's columns over 4 blocks (opt-in STRATA_GDN_SPLIT=1, bit-identical by construction) gdn_step_norm_multi_kernel ran one 512-thread block per head - 32 blocks for a layer's 2 MB state, ~36 us per launch at T=1 on gfx1151 (~60 GB/s) and +4 us per window row; it runs twice per GDN layer and window (the window and the commit's replay). With the switch the recurrence runs on (head, 32-column) blocks with the same (column, row group) threads and state rows, so every column's arithmetic is unchanged; the output norm, which needs a head's 128 columns, follows in gdn_out_norm_kernel with the same warps and the same sum order. --- src/kernels/cuda/verify_kernels.cu | 93 ++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) diff --git a/src/kernels/cuda/verify_kernels.cu b/src/kernels/cuda/verify_kernels.cu index 7908ce40..a44cd460 100644 --- a/src/kernels/cuda/verify_kernels.cu +++ b/src/kernels/cuda/verify_kernels.cu @@ -180,6 +180,89 @@ __global__ void __launch_bounds__(S * RG) gdn_step_norm_multi_kernel(float* __re } } +// S25 (STRATA_GDN_SPLIT=1): the same recurrence with each head's 128 state columns over 4 blocks of 32 columns +// (128 threads: the same (column, row group) threads, each with the same 32 state rows), so 4x the blocks of +// gdn_step_norm_multi_kernel - which ran one 512-thread block per head (32 blocks) and read the 2 MB state of a layer +// at ~60 GB/s. Every column's arithmetic is the original's; the output norm, which needs all 128 columns of a head, +// moves to gdn_out_norm_kernel: this kernel leaves the unnormalized output `oc` in y and the second kernel sums the +// squares by the same warps (columns 32w..32w+31, the same butterfly) in the same order. +constexpr int GS_COLS = 32; +__global__ void __launch_bounds__(GS_COLS * RG) gdn_step_split_kernel(float* __restrict__ state, + const float* __restrict__ hbuf, int C, + const float* __restrict__ gate, + const float* __restrict__ beta, + float* __restrict__ y, int h_k, int h_v, int T, + const int32_t* __restrict__ n_keep, + int t_out_begin) { + __shared__ float sk[S], sq[S]; + __shared__ float red[RG][GS_COLS]; + const int head = blockIdx.x; + const int c0 = blockIdx.y * GS_COLS; + const int lc = threadIdx.x; // local column + const int col = c0 + lc; + const int rg = threadIdx.y; + const int tid = rg * GS_COLS + lc; + const int qh = head % h_k; + const int qk = S * h_k; + const int value_dim = S * h_v; + const int n = n_keep ? *n_keep : T; + float s[RPG]; + float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col; + const size_t row_stride = (size_t) h_v * S; +#pragma unroll + for (int r = 0; r < RPG; ++r) s[r] = base[r * row_stride]; + for (int t = 0; t < n; ++t) { + const float* ht = hbuf + (size_t) t * C; + __syncthreads(); + if (tid < S) { sk[tid] = ht[qk + qh * S + tid]; sq[tid] = ht[qh * S + tid]; } + __syncthreads(); + const float g = __expf(gate[(size_t) t * h_v + head]); + float kv = 0.0f; +#pragma unroll + for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv); + red[rg][lc] = kv; + __syncthreads(); + const float kv_col = red[0][lc] + red[1][lc] + red[2][lc] + red[3][lc]; + const float delta = (ht[2 * qk + head * S + col] - g * kv_col) * beta[(size_t) t * h_v + head]; + float o = 0.0f; +#pragma unroll + for (int r = 0; r < RPG; ++r) { + s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta); + o = fmaf(s[r], sq[rg * RPG + r], o); + } + __syncthreads(); + red[rg][lc] = o; + __syncthreads(); + if (rg == 0 && t >= t_out_begin) + y[(size_t) t * value_dim + head * S + col] = + (red[0][lc] + red[1][lc] + red[2][lc] + red[3][lc]) * rsqrtf((float) S); + } + if (n_keep != nullptr && n > 0) { +#pragma unroll + for (int r = 0; r < RPG; ++r) base[r * row_stride] = s[r]; + } +} + +// y = oc * rsqrt(mean(oc^2) + eps) * gamma * sigmoid(z) per head and token, with gdn_step_norm_multi_kernel's sums +__global__ void __launch_bounds__(S) gdn_out_norm_kernel(const float* __restrict__ z, const float* __restrict__ gamma, + float eps, float* __restrict__ y, int h_v, int T, + const int32_t* __restrict__ n_keep, int t_out_begin) { + __shared__ float wsum[S / 32]; + const int head = blockIdx.x, t = blockIdx.y + t_out_begin, col = threadIdx.x; + const int n = n_keep ? *n_keep : T; + if (t >= n) return; + const int value_dim = S * h_v; + const float oc = y[(size_t) t * value_dim + head * S + col]; + float sq_part = oc * oc; + for (int o2 = 16; o2 > 0; o2 >>= 1) sq_part += __shfl_xor_sync(0xffffffffu, sq_part, o2); + if ((col & 31) == 0) wsum[col >> 5] = sq_part; + __syncthreads(); + const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3]; + const float scale = rsqrtf(ss / (float) S + eps); + const float zz = z[(size_t) t * value_dim + head * S + col]; + y[(size_t) t * value_dim + head * S + col] = oc * scale * gamma[col] * (1.0f / (1.0f + __expf(-zz))); +} + __global__ void embedding_gather_dev_kernel(const uint8_t* __restrict__ codes, const float* __restrict__ scales, const float* __restrict__ offsets, const int32_t* __restrict__ tokens, int64_t n, int code_bits, int code_bias, int group_elems, @@ -417,6 +500,16 @@ void gdn_step_norm_multi(float* state, const float* h, int conv_channels, const std::fprintf(stderr, "gdn_step_norm_multi: invalid arguments\n"); std::exit(1); } + static const bool split = [] { const char* v = std::getenv("STRATA_GDN_SPLIT"); return v && v[0] == '1'; }(); + if (split) { + gdn_step_split_kernel<<>>( + state, h, conv_channels, gate, beta, y, h_k, h_v, n_tok, n_keep, t_out_begin); + if (n_tok > t_out_begin) + gdn_out_norm_kernel<<>>( + z, gamma, eps, y, h_v, n_tok, n_keep, t_out_begin); + check("gdn_step_norm_multi (split)"); + return; + } gdn_step_norm_multi_kernel<<<(unsigned) h_v, dim3(S, RG), 0, (cudaStream_t) stream>>>( state, h, conv_channels, gate, beta, z, gamma, eps, y, h_k, h_v, n_tok, n_keep, t_out_begin); check("gdn_step_norm_multi"); From 58729711d952149196a9c64fc789043fdfa1ffbc Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 06:00:25 +0200 Subject: [PATCH 28/55] STRATA_HC_Q8=1: inject rows as the exact BF16, the final mixer from Q8_0 too The GGUF's F32 inject rows hold BF16-exact values (conversions.json: "the values are BF16's"), so quantizing them to Q8_0 only added error: the Q8_0 read now takes the pack's BF16 inject rows (STRATA_HC_Q8_INJECT=1 keeps the Q8_0 copy). The final mixer before the head (output_hc_down/up, also BF16-rounded in the pack) now reads the GGUF's Q8_0 values through the same multi read. --- src/core/native_dense.cpp | 6 +++++- src/core/verify.cpp | 18 +++++++++++++++++- src/kernels/cuda/fused_gr.cu | 18 ++++++++++++++---- 3 files changed, 36 insertions(+), 6 deletions(-) diff --git a/src/core/native_dense.cpp b/src/core/native_dense.cpp index aae66aec..62a42db7 100644 --- a/src/core/native_dense.cpp +++ b/src/core/native_dense.cpp @@ -24,6 +24,7 @@ bool hc_q8_requested() { return on; } bool hc_q8_name(const std::string& name) { + if (name == "output_hc_down.weight" || name == "output_hc_up.weight") return true; // S25: the final mixer too if (name.rfind("blk.", 0) != 0) return false; static const char* suffixes[] = {".hc_attn_down.weight", ".hc_attn_up.weight", ".hc_attn_inject.weight", ".hc_ffn_down.weight", ".hc_ffn_up.weight", ".hc_ffn_inject.weight"}; @@ -225,7 +226,10 @@ bool NativeDense::load(const std::vector& shards, WeightTable& tabl } if (hc_q8_requested()) for (const auto& tensor : gguf.tensors()) { - const bool f32_inject = tensor.type == 0 && tensor.name.ends_with("_inject.weight"); + // S25: the F32 inject rows hold BF16-exact values: the read takes the pack's BF16 rows unless + // STRATA_HC_Q8_INJECT=1 asks for a Q8_0 copy + static const bool q8_inject = [] { const char* v = std::getenv("STRATA_HC_Q8_INJECT"); return v && v[0] == '1'; }(); + const bool f32_inject = q8_inject && tensor.type == 0 && tensor.name.ends_with("_inject.weight"); if ((tensor.type != 8 && !f32_inject) || !hc_q8_name(tensor.name) || tensor.shape.size() != 2) continue; auto found = table.table_.find(tensor.name); if (found == table.table_.end() || found->second.hc_q8 != nullptr) continue; diff --git a/src/core/verify.cpp b/src/core/verify.cpp index e631ee74..57a0a2da 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -829,7 +829,23 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { const WeightRef *hn = wt.find("output_hc_norm.weight"), *hd = wt.find("output_hc_down.weight"), *hu = wt.find("output_hc_up.weight"); if (!hn || !hd || !hu) { err = "verify: an output_hc_* weight is missing"; return false; } - for (int t = 0; t < T; ++t) { + // S25 (STRATA_HC_Q8=1): the final mixer from the GGUF's Q8_0 projections too, through the same multi read + // (no pending write, no inject) + const bool mix_q8 = hd->hc_q8 != nullptr && hu->hc_q8 != nullptr && head_ != nullptr && head_->loaded(); + if (mix_q8) { + FusedGrArgs fa[kFusedGrMaxT]; + for (int t = 0; t < T; ++t) { + FusedGrArgs& a = fa[t]; + a.R = Rt(t); a.R_out = Rt(t); a.apply = false; + a.w_norm = (const float*) hn->data; a.w_down = (const uint16_t*) hd->data; + a.w_up = (const uint16_t*) hu->data; a.w_inject = nullptr; + a.q8_down = (const uint8_t*) hd->hc_q8; a.q8_up = (const uint8_t*) hu->hc_q8; + a.eps = EPS; a.lo = lo_ + t * g.hc_lr; a.rs = rs_ + t * HC; + a.mixed = head_mixed_ + t * N; + } + fused_gr_read_multi(fa, T, xn_, cs); + } + for (int t = 0; t < T && !mix_q8; ++t) { BlockBuffers bb = ss.block; bb.R = Rt(t); bb.mixed = head_mixed_ + t * N; diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cu index d6515ac3..ec7ddb56 100644 --- a/src/kernels/cuda/fused_gr.cu +++ b/src/kernels/cuda/fused_gr.cu @@ -827,7 +827,10 @@ __global__ void __launch_bounds__(THREADS) gr_down_q8_kernel(GrMulti m, float* _ const int t = threadIdx.x, lane = t & 31, warp = t >> 5; const int rg = blockIdx.x, kc = blockIdx.y, c = kc / Q8_CPS; const bool inj = rg == Q8_RG; - const int nrows = inj ? ((m.a[0].q8_inject != nullptr && warp < HC) ? 1 : 0) : Q8_RPW; + // S25: the inject rows are F32 in the GGUF with BF16-exact values, so by default they are read as the pack's BF16 + // (exact); a Q8_0 copy (STRATA_HC_Q8_INJECT=1) is the other option + const bool inj_bf16 = inj && m.a[0].q8_inject == nullptr; + const int nrows = inj ? (((m.a[0].q8_inject != nullptr || m.a[0].w_inject != nullptr) && warp < HC) ? 1 : 0) : Q8_RPW; const int row0 = inj ? warp : (rg * WARPS + warp) * Q8_RPW; const uint8_t* wb = inj ? m.a[0].q8_inject : m.a[0].q8_down; const int sub = lane & 7, bl = lane >> 3; // lanes 8b..8b+7: one Q8_0 block, 4 values each @@ -835,7 +838,7 @@ __global__ void __launch_bounds__(THREADS) gr_down_q8_kernel(GrMulti m, float* _ float dq[Q8_RPW][Q8_SPB]; #pragma unroll for (int r = 0; r < Q8_RPW; ++r) { - if (r >= nrows) break; + if (r >= nrows || inj_bf16) break; const uint8_t* row = wb + (size_t) (row0 + r) * (D / 32) * Q8B + (size_t) kc * (Q8_KC / 32) * Q8B; #pragma unroll for (int s = 0; s < Q8_SPB; ++s) { @@ -883,8 +886,15 @@ __global__ void __launch_bounds__(THREADS) gr_down_q8_kernel(GrMulti m, float* _ for (int k = 0; k < T; ++k) acc[k] = 0.0f; #pragma unroll for (int s = 0; s < Q8_SPB; ++s) { - const float4 w = q8_four(q[r][s], dq[r][s]); const int v = 32 * (4 * s + bl) + 4 * sub; + float4 w; + if (inj_bf16) { + const uint2 b = *reinterpret_cast(m.a[0].w_inject + (size_t) row0 * D + (size_t) kc * Q8_KC + v); + w = make_float4(__uint_as_float(b.x << 16), __uint_as_float(b.x & 0xffff0000u), + __uint_as_float(b.y << 16), __uint_as_float(b.y & 0xffff0000u)); + } else { + w = q8_four(q[r][s], dq[r][s]); + } #pragma unroll for (int k = 0; k < T; ++k) { const float4 x = *reinterpret_cast(&xs[k][v]); @@ -1044,7 +1054,7 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi m.xn = xn_scratch; m.T = n_tok; cudaStream_t st = (cudaStream_t) stream; - if (a[0].q8_down != nullptr && a[0].q8_up != nullptr && (a[0].w_inject == nullptr || a[0].q8_inject != nullptr)) { + if (a[0].q8_down != nullptr && a[0].q8_up != nullptr) { // inject: Q8_0 copy, or the BF16 rows launch_q8(m, xn_scratch, st, stamp_buf, stamp_i0); // S23 experiment: STRATA_HC_Q8=1 const cudaError_t eq = cudaGetLastError(); if (eq != cudaSuccess) { From d92c9feb78ce3082b5f1df834e9001117908f508 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 06:59:29 +0200 Subject: [PATCH 29/55] Verify PLE block: the window's key and value projections at once (opt-in STRATA_PLE_BATCH=1, bit-identical) Layer 1's PLE block ran its key (10240 x 2560) and value (2560 x 2560) GEMVs once per window row, reading ~40 MB of weights per row. Both depend only on the row's n-gram embedding, so with the switch the group's rows go through the multi-row forms of the same kernels (native MMVQ over n columns / bf16_gemv_fp32_mmvf_multi, each row's arithmetic the single-row call's) and ple_block copies its row's results instead of recomputing them. The history-dependent rest of the block stays row by row. --- include/strata/core/verify.hpp | 2 ++ include/strata/kernels/ple.hpp | 6 ++++++ src/core/verify.cpp | 27 ++++++++++++++++++++++++++- src/kernels/cuda/ple.cu | 9 +++++++-- 4 files changed, 41 insertions(+), 3 deletions(-) diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index 5717eb4f..6e0bf4ec 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -198,6 +198,8 @@ private: VerifyHits hits_; const NativeHead* head_ = nullptr; int max_t_ = 0; + float* ple_key_ = nullptr; ///< STRATA_PLE_BATCH: the window rows' PLE key / value projections + float* ple_val_ = nullptr; int last_t_ = 0; int64_t last_pos0_ = 0; int32_t last_tokens_[8] = {}; diff --git a/include/strata/kernels/ple.hpp b/include/strata/kernels/ple.hpp index fabad838..30afb01d 100644 --- a/include/strata/kernels/ple.hpp +++ b/include/strata/kernels/ple.hpp @@ -33,6 +33,7 @@ namespace strata::kernels { /// Opt in to pinned CUDA BF16/F32 MMVF for the PLE value projection only (default false). /// Configure before session capture; captured graphs retain their selected projection kernels. void ple_set_native_bf16(bool enabled); +bool ple_native_bf16(); /// Opt in to pinned CUDA postprojection norms, gate, convolution and residual /// arithmetic (default false). Set before capture; existing graphs keep their @@ -70,6 +71,11 @@ struct PleWeights { /// Plan v0.3 P6: the IQ model files keep `ple_key` in BF16 ([n_embd, hc_dim], `w[o*n_embd+i]`); when set it /// replaces both key paths above. const uint16_t* key_bf16 = nullptr; + /// S25 (STRATA_PLE_BATCH=1): the key (hc_dim) and value (n_embd) projections of `emb`, already computed by the + /// caller for a window's rows at once (the same kernels' multi-row forms); ple_block then copies them instead of + /// running its own GEMVs + const float* pre_key = nullptr; + const float* pre_value = nullptr; }; /// Everything the block produces, in the order `ple_layer_xcheck`'s oracle writes it. Any pointer may be diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 57a0a2da..812074d7 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -320,6 +320,7 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& sh_up_ = b.take(T * (uint64_t) g.n_ff); sh_g_ = b.take(T + 4); head_logits_ = b.take(T * (uint64_t) n_vocab_); hist_snap_ = b.take(T * HS); + ple_key_ = b.take(T * (uint64_t) strata::kernels::NG_HC_DIM); ple_val_ = b.take(T * N); }; Bump count; carve(count); @@ -472,13 +473,37 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { bool pending = l > 0 && !cvec().covers(l - 1); if (l == 1 && ple_on) { float* normalized = (float*) ((uint8_t*) ss.ple.scratch + ple_block_scratch_bytes()); + // S25 (STRATA_PLE_BATCH=1): the key and value projections depend only on each row's n-gram embedding, so + // the group's rows run through the multi-row forms of the same kernels (the weights read once); every + // row's arithmetic is the single-row call's. The history-dependent rest stays row by row. + static const bool ple_batch = [] { const char* e = std::getenv("STRATA_PLE_BATCH"); return e && e[0] == '1'; }(); + PleWeights pw = ss.ple.w; + const bool nkey = pw.key_native_data != nullptr && pw.key_bf16 == nullptr; + const bool batched = ple_batch && n > 1 && (pw.key_bf16 != nullptr || nkey) && ple_native_bf16(); + if (batched) { + try { + if (pw.key_bf16 != nullptr) + bf16_gemv_fp32_mmvf_multi(ple_ + tb * N, N, pw.key_bf16, ple_key_ + (size_t) tb * NG_HC_DIM, + NG_HC_DIM, N, NG_HC_DIM, n, cs); + else { + native_quantize_q8_1(ple_ + tb * N, xq_, (int) N, n, cs); + native_mmvq(pw.key_native_type, pw.key_native_data, xq_, ple_key_ + (size_t) tb * NG_HC_DIM, + (int) N, NG_HC_DIM, n, cs); + } + bf16_gemv_fp32_mmvf_multi(ple_ + tb * N, N, pw.value_bf16, ple_val_ + tb * N, N, N, N, n, cs); + } catch (const std::exception& e) { + err = std::string("verify PLE batch: ") + e.what(); + return false; + } + } for (int t = tb; t < te; ++t) { + if (batched) { pw.pre_key = ple_key_ + (size_t) t * NG_HC_DIM; pw.pre_value = ple_val_ + t * N; } gr_write(Rt(t), bo_ + t * N, inj2_ + t * HC, gs, Rt(t), cs); PleOut po; po.normalized = normalized; po.result = Rt(t); try { - ple_block(ple_ + t * N, Rt(t), ss.ple.hist, ss.ple.w, po, ss.ple.scratch, cs); + ple_block(ple_ + t * N, Rt(t), ss.ple.hist, pw, po, ss.ple.scratch, cs); ple_history_advance(ss.ple.hist, normalized, cs); } catch (const std::exception& e) { err = std::string("verify PLE: ") + e.what(); diff --git a/src/kernels/cuda/ple.cu b/src/kernels/cuda/ple.cu index 6585bbaa..3f37ab7a 100644 --- a/src/kernels/cuda/ple.cu +++ b/src/kernels/cuda/ple.cu @@ -197,6 +197,7 @@ void ck(cudaError_t e, const char* what) { } // namespace void ple_set_native_bf16(bool enabled) { native_bf16 = enabled; } +bool ple_native_bf16() { return native_bf16; } void ple_set_native_postops(bool enabled) { native_postops = enabled; } bool ple_native_postops_enabled() { return native_postops; } @@ -303,7 +304,9 @@ void ple_block(const float* emb, const float* hidden, const float* hist_rows, co // ---- key = grouped_norm(ple_key @ emb). The optional native projection // follows pinned CUDA Q8_1 MMVQ; the default retains its canonical Q8_0 path. - if (w.key_bf16 != nullptr) { + if (w.pre_key != nullptr) { + cudaMemcpyAsync(d_key, w.pre_key, (size_t) hc_dim * sizeof(float), cudaMemcpyDeviceToDevice, st); + } else if (w.key_bf16 != nullptr) { bf16_gemv_fp32_mmvf(emb, w.key_bf16, d_key, n_embd, hc_dim, stream); } else if (native_key) { native_quantize_q8_1(emb, w.key_native_q8_1, n_embd, 1, stream); @@ -319,7 +322,9 @@ void ple_block(const float* emb, const float* hidden, const float* hist_rows, co } // The value projection's independent option leaves the nonlinear PLE operations unchanged. - if (native_bf16) { + if (w.pre_value != nullptr) { + cudaMemcpyAsync(d_value, w.pre_value, (size_t) n_embd * sizeof(float), cudaMemcpyDeviceToDevice, st); + } else if (native_bf16) { bf16_gemv_fp32_mmvf(emb, w.value_bf16, d_value, n_embd, n_embd, stream); } else { to_bf16_kernel<<<(n_embd + THREADS - 1) / THREADS, THREADS, 0, st>>>(emb, d_emb16, n_embd); From 48d10a4996d7cc2637031d6f8d83c407e9017725 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 07:24:46 +0200 Subject: [PATCH 30/55] Prompt path: STRATA_PREFILL_DUMP_R_ALL=FILE, every position's final residual as BF16 (opt-in, for distillation data) Appends [n][hc*n_embd] BF16 rows (round-to-nearest-even) in position order for every batched prompt chunk: the input the MTP draft layer reads, for training it against this trunk. Off unless the variable is set. --- src/prefill/prefill.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index e4ddd1c1..83ddd1b5 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -2110,6 +2110,28 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e std::fclose(f); } } + if (const char* dump = std::getenv("STRATA_PREFILL_DUMP_R_ALL")) { + // S25 (draft-layer distillation data, opt-in): every position's final multi-stream residual as BF16 + // (round-to-nearest-even), rows in position order, appended across chunks and requests: [n][hc*n_embd] + cudaStreamSynchronize(m.cs); + if (std::FILE* f = std::fopen(dump, "ab")) { + constexpr int64_t kRows = 512; + std::vector rows((size_t) (kRows * D)); + std::vector out((size_t) (kRows * D)); + for (int64_t t0 = 0; t0 < T; t0 += kRows) { + const int64_t nr = std::min(kRows, T - t0); + cudaMemcpy(rows.data(), m.R + t0 * D, (size_t) (nr * D) * 4, cudaMemcpyDeviceToHost); + for (int64_t i = 0; i < nr * D; ++i) { + uint32_t u; + std::memcpy(&u, &rows[(size_t) i], 4); + u += 0x7fffu + ((u >> 16) & 1u); + out[(size_t) i] = (uint16_t) (u >> 16); + } + std::fwrite(out.data(), 2, (size_t) (nr * D), f); + } + std::fclose(f); + } + } if (on_chunk || on_stage_chunk) { const auto toc = Clock::now(); if (cudaStreamSynchronize(m.cs) != cudaSuccess) { From 31b2472a3feeab1dc3f8802ec4f0a5d042ca04f1 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 07:32:53 +0000 Subject: [PATCH 31/55] prefill: opt-in STRATA_HC_UPMIX=1 - the hyper-connection up projection with gr_mix_r as its epilogue (gfx11) The read's up GEMM wrote `gated` (T x 10240 FP32: 671 MB per 16K chunk) for gr_mix_r to read back. gr_upmix computes a tile of 128 tokens x 16 columns for the 4 streams on the matrix cores (BF16 in, FP32 accumulate, the block's 64 w_up rows staged in LDS once) and runs the mix in registers, in gr_mix_r's order. The grid is ordered column-tile fastest: the blocks in flight share one token tile, so the R reads of the epilogue stay on few pages (token-tile fastest touched 512 rows x 40 KB per block: 28 ms instead of 3.7 at 8K - address translation on this box goes through the IOMMU). STRATA_HC_UPMIX_CHECK=N runs the default pair on the first N reads and prints the difference. gfx1151, UD-IQ4_XS: `mixed` vs the default rel RMS 1.2-3.6e-7 on every read of an 8K prompt; prompt-timing "hc read" 1352 / 1313 -> 1080 / 1212 ms at 8K; 64K prompt 874.3 / 876.1 -> 902.7 / 903.0 tok/s. Rounding-level (the K order of the GEMM): teacher-forced KL on three text offsets 0.170 / 0.085 / 0.032 vs the accepted MMQ-vs-fused pair's 0.153 / 0.117 / 0.030; ledger and 8K / 64K retrieval pass. Off by default. --- include/strata/prefill/kernels.hpp | 4 ++ src/prefill/kernels.cu | 92 ++++++++++++++++++++++++++++++ src/prefill/prefill.cpp | 45 +++++++++++++-- 3 files changed, 137 insertions(+), 4 deletions(-) diff --git a/include/strata/prefill/kernels.hpp b/include/strata/prefill/kernels.hpp index e10d8ba1..f643918a 100644 --- a/include/strata/prefill/kernels.hpp +++ b/include/strata/prefill/kernels.hpp @@ -25,6 +25,10 @@ void gr_mix_r(const float* R, const float* rs, const float* w_norm, const float* int64_t T, void* stream, uint16_t* mixed_h = nullptr, uint16_t* mixed16_lo = nullptr); /// F-2: gr_write, then gr_norm_rs of the next half (its norm weights) over the rows just written - the same bits as /// the two calls, without reading R back. +/// S23 (opt-in STRATA_HC_UPMIX=1): the up projection (lo16 x w_up^T, BF16, FP32 accumulate) with gr_mix_r as its +/// epilogue - `gated` is never written. False (nothing launched) off gfx11. +bool gr_upmix(const uint16_t* lo16, const uint16_t* w_up, const float* R, const float* rs, const float* w_norm, + float* mixed, uint16_t* mixed16, uint16_t* mixed_h, int64_t T, void* stream); void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* w_norm_next, float eps, float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo = nullptr); /// lo16[t, k] = bf16(silu(lo[t, k] / hc)) diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 6f1ec519..8322b9a8 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -11,6 +11,7 @@ #include #include #include +#include namespace strata::prefill { namespace { @@ -798,6 +799,77 @@ __global__ void to_bf16_kernel(const float* __restrict__ x, uint16_t* __restrict } } +// S23 (opt-in STRATA_HC_UPMIX=1, gfx11): the hyper-connection read's up projection with gr_mix_r as its epilogue. The +// up GEMM's FP32 output `gated` (T x 10240: 671 MB per 16K chunk) is never written or read back: a block computes a +// tile of 64 tokens x 64 columns for all 4 streams on the matrix cores (BF16 in, FP32 accumulate over K = 320; the +// lo16 and w_up tiles staged in LDS), and each lane already holds the 4 streams' values of its (token, column) - the +// mix (x_c = R * rs * w, sum of x_c * sigmoid(gated_c), / 4) runs in registers, in gr_mix_r_kernel's order. The +// GEMM sums K in another order than hipBLASLt: rounding-level, hence opt-in and quality-gated. +#if defined(__HIPCC__) +typedef __bf16 um_b16 __attribute__((ext_vector_type(16))); +typedef float um_f8 __attribute__((ext_vector_type(8))); +__device__ __forceinline__ um_f8 um_wmma(um_b16 a, um_b16 b, um_f8 c) { +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__) + return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a, b, c); +#else + (void) a; (void) b; return c; // not a gfx11 device pass: never launched (runtime gate) +#endif +} +constexpr int UM_T = 128, UM_D = 16, UM_LD = LR + 8; // a block: 128 tokens x 16 columns x the 4 streams +__device__ __forceinline__ um_b16 um_frag(const uint16_t* p) { // 16 BF16 (32 bytes, 16-byte aligned) + const uint4 a = *reinterpret_cast(p), b = *reinterpret_cast(p + 8); + const uint32_t w[8] = {a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w}; + return __builtin_bit_cast(um_b16, w); +} +// The block's w_up rows (16 columns x 4 streams x all 320 k) are staged in LDS once; each wave streams its own 16 +// tokens' lo16 rows from global memory (every A fragment feeds the 4 streams' WMMAs) - one barrier per block. +__global__ void __launch_bounds__(256) gr_upmix_kernel(const uint16_t* __restrict__ lo16, const uint16_t* __restrict__ wu, + const float* __restrict__ R, const float* __restrict__ rs, + const float* __restrict__ w, float* __restrict__ mixed, + uint16_t* __restrict__ mixed16, uint16_t* __restrict__ mixed_h, + int64_t T) { + __shared__ __align__(16) uint16_t sB[HC * UM_D][UM_LD]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, l16 = lane & 15, hi = lane >> 4; + // blocks ordered column-tile fastest: the blocks in flight share a token tile, so the epilogue's R reads run + // along rows (token-tile fastest scattered them over 512 rows x 40 KB per block: 28 ms instead of 3.7 at 8K) + const int64_t t0 = (int64_t) blockIdx.y * UM_T + 16 * wave; + const int d0 = blockIdx.x * UM_D; + for (int i = tid; i < HC * UM_D * (LR / 8); i += 256) { + const int rr = i / (LR / 8), q = i % (LR / 8); + const int c = rr / UM_D, dd = rr % UM_D; + *reinterpret_cast(&sB[rr][8 * q]) = *reinterpret_cast(wu + (size_t) (c * N + d0 + dd) * LR + 8 * q); + } + __syncthreads(); + if (t0 >= T) return; + const int64_t ta = t0 + l16 < T ? t0 + l16 : T - 1; + const uint16_t* arow = lo16 + ta * LR; + um_f8 acc[HC]; +#pragma unroll + for (int c = 0; c < HC; ++c) acc[c] = um_f8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; +#pragma unroll + for (int ks = 0; ks < LR; ks += 16) { + const um_b16 a = um_frag(arow + ks); +#pragma unroll + for (int c = 0; c < HC; ++c) acc[c] = um_wmma(a, um_frag(&sB[c * UM_D + l16][ks]), acc[c]); + } + const int d = d0 + l16; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int64_t t = t0 + 2 * i + hi; + if (t >= T) continue; + float s = 0.0f; +#pragma unroll + for (int c = 0; c < HC; ++c) { + const float x = R[t * D + c * N + d] * rs[t * HC + c] * w[c * N + d]; // gr_mix_r_kernel's order + s = fmaf(x, sigm(acc[c][i]), s); + } + s /= (float) HC; + mixed[t * N + d] = s; + if (mixed16) mixed16[t * N + d] = bf(s); + if (mixed_h) mixed_h[t * N + d] = hf(s); + } +} +#endif } // namespace void kv_append(const float* K, const float* V, int64_t T, int64_t pos0, const int32_t* page_table, int64_t page_size, @@ -841,6 +913,26 @@ void gr_mix_r(const float* R, const float* rs, const float* w_norm, const float* mixed_h, mixed16_lo); check("gr_mix_r"); } +bool gr_upmix(const uint16_t* lo16, const uint16_t* w_up, const float* R, const float* rs, const float* w_norm, + float* mixed, uint16_t* mixed16, uint16_t* mixed_h, int64_t T, void* stream) { +#if defined(__HIPCC__) + static const bool gfx11 = [] { + int dev = 0; + cudaDeviceProp p; + if (cudaGetDevice(&dev) != cudaSuccess || cudaGetDeviceProperties(&p, dev) != cudaSuccess) return false; + return std::strncmp(p.gcnArchName, "gfx11", 5) == 0; + }(); + if (!gfx11 || T <= 0) return false; + gr_upmix_kernel<<>>( + lo16, w_up, R, rs, w_norm, mixed, mixed16, mixed_h, T); + check("gr_upmix"); + return true; +#else + (void) lo16; (void) w_up; (void) R; (void) rs; (void) w_norm; (void) mixed; (void) mixed16; (void) mixed_h; + (void) T; (void) stream; + return false; +#endif +} void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* w_norm_next, float eps, float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo) { gr_write_norm_rs_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, bo, inj, inj_ld, w_norm_next, eps, diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 54c9cb7e..79c9351f 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -167,6 +167,12 @@ inline int bf16x2_mode() { return v; } inline bool bf16x2() { return bf16x2_mode() != 0; } +// S23 (opt-in STRATA_HC_UPMIX=1): the hyper-connection read's up projection and gr_mix_r as one kernel (gr_upmix, gfx11); +// STRATA_HC_UPMIX_CHECK=N also runs the default pair on the first N reads and reports the difference of `mixed` +inline bool hc_upmix() { + static const bool v = [] { const char* e = std::getenv("STRATA_HC_UPMIX"); return e != nullptr && e[0] == '1'; }(); + return v; +} inline bool bf16x2_hc() { return bf16x2_mode() == 1; } // F-1: STRATA_GR_UNFUSED=1 keeps the FP32 copy of the normalized rows (gr_norm + gr_mix), the A/B arm @@ -1409,11 +1415,42 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e normed = false; if (!bf16_proj(m.gemm, wd, m.xn16, m.lo, T, sd, err, 0, m.xn16_lo)) return false; gr_silu(m.lo, m.lo16, T, m.cs, m.lo16_lo); - if (!bf16_proj(m.gemm, wu, m.lo16, m.gated, T, su, err, 0, m.lo16_lo)) return false; + bool upmixed = false; + if (hc_upmix() && !gr_unfused() && !m.lo16_lo && !m.mixed_bf_lo && + wu->kind == core::WeightKind::Bf16InF32 && wu->data && wu->ne0 == LR && wu->ne1 == D) { + static int checks = [] { const char* e = std::getenv("STRATA_HC_UPMIX_CHECK"); return e ? std::atoi(e) : 0; }(); + if (checks > 0) { // the default pair first, kept for the comparison + --checks; + if (!bf16_proj(m.gemm, wu, m.lo16, m.gated, T, su, err)) return false; + gr_mix_r(m.R, m.grs, (const float*) wn->data, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h); + std::vector ref((size_t) T * N), got((size_t) T * N); + cudaMemcpyAsync(ref.data(), m.mixed, ref.size() * 4, cudaMemcpyDeviceToHost, m.cs); + upmixed = gr_upmix(m.lo16, (const uint16_t*) wu->data, m.R, m.grs, (const float*) wn->data, + m.mixed, m.mixed_bf, m.mixed_h, T, m.cs); + cudaMemcpyAsync(got.data(), m.mixed, got.size() * 4, cudaMemcpyDeviceToHost, m.cs); + cudaStreamSynchronize(m.cs); + double e2 = 0, r2 = 0, emax = 0; + for (size_t i = 0; i < ref.size(); ++i) { + const double dd = (double) got[i] - ref[i]; + e2 += dd * dd; r2 += (double) ref[i] * ref[i]; emax = std::max(emax, std::fabs(dd)); + } + std::fprintf(stderr, "strata: STRATA_HC_UPMIX_CHECK layer %lld half %d T %lld: mixed rel RMS %.3e, " + "max |diff| %.3e (%s)\n", (long long) l, half, (long long) T, + std::sqrt(e2 / std::max(r2, 1e-30)), emax, upmixed ? "upmix" : "upmix refused"); + } else { + upmixed = gr_upmix(m.lo16, (const uint16_t*) wu->data, m.R, m.grs, (const float*) wn->data, + m.mixed, m.mixed_bf, m.mixed_h, T, m.cs); + } + } + if (!upmixed && !bf16_proj(m.gemm, wu, m.lo16, m.gated, T, su, err, 0, m.lo16_lo)) return false; if (!bf16_proj(m.gemm, wi, m.xn16, m.inj, T, si, err, 0, m.xn16_lo)) return false; - if (gr_unfused()) gr_mix(m.xn, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h, m.mixed_bf_lo); - else gr_mix_r(m.R, m.grs, (const float*) wn->data, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h, - m.mixed_bf_lo); + if (upmixed) { + } else if (gr_unfused()) { + gr_mix(m.xn, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h, m.mixed_bf_lo); + } else { + gr_mix_r(m.R, m.grs, (const float*) wn->data, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h, + m.mixed_bf_lo); + } if (half == 0 && !core::is_qsa_layer(g, l)) { // ======================= GDN ======================= From 7aaf466d188f69286fc9e79ef3b6fcd4dc00e8b9 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 07:32:53 +0000 Subject: [PATCH 32/55] qsa: opt-in STRATA_PA_FAST=1 - the gfx11 prompt attention with single FP16 q and p prompt_attn_wmma_kernel carries q and p as FP16 hi + lo pairs (two WMMAs each, FP32-level). SPLIT = false drops the lo halves: FP16 attention as the usual flash-attention kernels, half the matrix work. gfx1151, real 64K selections (16383 queries x 2051 cells, one QSA layer): 138.7 -> 117.8 ms; rel RMS vs FP64 4.8e-7 -> 2.7e-4. Engine 8K "qsa attn" 718 / 712 -> 589 / 590 ms. Teacher-forced KL on three text offsets 0.153 / 0.087 / 0.027 (the accepted MMQ-vs-fused pair: 0.153 / 0.117 / 0.030). Off by default. --- src/kernels/cuda/qsa_prompt_attn.cu | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/src/kernels/cuda/qsa_prompt_attn.cu b/src/kernels/cuda/qsa_prompt_attn.cu index 30de4b34..6cfd8e43 100644 --- a/src/kernels/cuda/qsa_prompt_attn.cu +++ b/src/kernels/cuda/qsa_prompt_attn.cu @@ -754,6 +754,10 @@ __device__ __forceinline__ wh8 i8_to_h(const uint32_t* x) { // PA_KL codes, ex return h; } +// SPLIT = true (default): q and p carried as FP16 hi + lo pairs (two WMMAs each: FP32-level). S23 (opt-in +// STRATA_PA_FAST=1): SPLIT = false, one FP16 image each - half the matrix work, rounding-level (FP16 attention as the +// usual flash-attention kernels), quality-gated +template __global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float* __restrict__ q, QsaAttnPools p, const int32_t* __restrict__ ids, const int32_t* __restrict__ steps, int n_kv_heads, @@ -859,7 +863,7 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float* } const wh8 b = i8_to_h(kx); s = wmma_f16(qh[kk], b, s); - s = wmma_f16(ql[kk], b, s); + if constexpr (SPLIT) s = wmma_f16(ql[kk], b, s); } #pragma unroll for (int i = 0; i < 8; ++i) S.part[warp][PA_ROW(i, half)][nt * 16 + col] = s[i] * ksc; @@ -925,7 +929,7 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float* #pragma unroll for (int i = 0; i < PA_KL; ++i) b[i] = (_Float16) (int) (int8_t) S.v[warp][cb + i][d]; tmp[j] = wmma_f16(ah, b, tmp[j]); - tmp[j] = wmma_f16(al, b, tmp[j]); + if constexpr (SPLIT) tmp[j] = wmma_f16(al, b, tmp[j]); } } float a[8]; @@ -988,9 +992,15 @@ bool launch_wmma(const float* q, const QsaAttnPools& pools, const int32_t* ids, 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_wmma_kernel<<>>( - 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); + static const bool fast = [] { const char* e = std::getenv("STRATA_PA_FAST"); return e != nullptr && e[0] == '1'; }(); + if (fast) + prompt_attn_wmma_kernel<<>>( + 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); + else + prompt_attn_wmma_kernel<<>>( + 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) { From 4c00d2e7a32771740678547d990c78084aa991c8 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 07:32:53 +0000 Subject: [PATCH 33/55] prefill: opt-in STRATA_PF_GEMM=1 - a gfx11 WMMA GEMM for the FP16 prompt projections strata_pf_gemm_f16 (wmma_gemm.cu), tried in Gemm::f16 before hipBLASLt for T >= 64, N >= 512, K % 32 == 0, beta 0 / 1: block 128 x 256 (128 x 128 below N 1024), BK 32, 8 waves of 64 x 64, LDS double buffer with the next stage prefetched into named registers, grouped tile order (8 row tiles sweep all column tiles, so the weights stream from DRAM once per group). FP32 accumulation, another K order than hipBLASLt: rounding-level. gfx1151, M 16384 (TFLOPS, tuned hipBLASLt in brackets): 12288 x 2560 33.0 (27.4), 10240 x 2560 31.9 (26.8), 6144 x 2560 31.1 (25.9), 2560 x 2560 30.1 (24.9), 640 x 2560 30.2 (25.3), 2560 x 6144 19.4 (19.1); the register-only WMMA ceiling is ~50. Engine 8K: gdn 1122 / 1112 -> 1083 / 1071 ms, qsa proj 813 / 716 -> 692 / 676, gdn out proj 753 -> 645 / 665. Teacher-forced KL 0.099 / 0.028 on two text offsets (accepted pair: 0.117 / 0.030). Off by default. With STRATA_HC_UPMIX + STRATA_PA_FAST, UD-IQ4_XS 64K prompt 872.8 / 880.6 -> 942.4 / 937.8 tok/s. --- src/prefill/gemm.cu | 2 + src/prefill/wmma_gemm.cu | 121 +++++++++++++++++++++++++++++++++++++++ src/prefill/wmma_gemm.h | 5 ++ 3 files changed, 128 insertions(+) diff --git a/src/prefill/gemm.cu b/src/prefill/gemm.cu index 2cfd6de5..0e6b3758 100644 --- a/src/prefill/gemm.cu +++ b/src/prefill/gemm.cu @@ -413,6 +413,8 @@ void Gemm::f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_ #ifdef STRATA_USE_HIP // #313 (opt-in STRATA_WMMA_GEMM=1): RDNA3 / RDNA3.5 WMMA dense GEMM, before hipBLASLt (falls through when false) static const bool wmma_on = [] { const char* v = std::getenv("STRATA_WMMA_GEMM"); return v && v[0] != 0 && v[0] != '0'; }(); + static const bool pf_on = [] { const char* v = std::getenv("STRATA_PF_GEMM"); return v && v[0] == '1'; }(); + if (pf_on && strata_pf_gemm_f16(X, W, Y, T, N, K, ldy, beta, stream_)) return; // S23: opt-in if (wmma_on && T >= 16 && (beta == 0.0f || beta == 1.0f) && strata_wmma_gemm_f16(X, W, Y, T, N, K, ldy, beta, stream_)) { return; diff --git a/src/prefill/wmma_gemm.cu b/src/prefill/wmma_gemm.cu index 95af0828..cd379636 100644 --- a/src/prefill/wmma_gemm.cu +++ b/src/prefill/wmma_gemm.cu @@ -282,8 +282,129 @@ bool strata_wmma_gemm_bf16(const uint16_t* X, const uint16_t* W, float* Y, return strata_wmma_gemm_dispatch<__bf16>(X, W, Y, T, N, K, ldy, beta, stream); } +// =========================================================================== +// S23 (opt-in STRATA_PF_GEMM=1): the prompt projections' FP16 GEMM on gfx11 (gfx1151: 30-33 TFLOPS on the 16K-row +// projection shapes where the tuned hipBLASLt reaches 25-27; s23/gemm_probe4.hip). Block 128 x BN (BN 256 or 128), +// BK 32, 8 waves of 64 x BN/4, LDS double buffer with the next stage prefetched into named registers (arrays there +// went to scratch), grouped tile order (8 row tiles sweep all column tiles: the weights stream from DRAM once per +// group). FP32 accumulation, K in another order than hipBLASLt: rounding-level, quality-gated. +// =========================================================================== +namespace pfg { +typedef _Float16 h16 __attribute__((ext_vector_type(16))); +typedef float f8 __attribute__((ext_vector_type(8))); +constexpr int BM = 128, BK = 32, LDK = BK + 8, GM = 8; +__device__ __forceinline__ h16 frag(const _Float16* p) { + const uint4 a = *reinterpret_cast(p), b = *reinterpret_cast(p + 8); + const uint32_t w[8] = {a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w}; + return __builtin_bit_cast(h16, w); +} +template +__global__ void __launch_bounds__(256) kernel(const _Float16* __restrict__ X, const _Float16* __restrict__ W, + float* __restrict__ Y, int M, int N, int K, int ldy, int accumulate) { +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__) + constexpr int TN = WN / 16, NB = BN / 64; + __shared__ __align__(16) _Float16 sA[2][BM][LDK]; + __shared__ __align__(16) _Float16 sB[2][BN][LDK]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, l16 = lane & 15, hi = lane >> 4; + const int wm = wave & 1, wn = wave >> 1; + const int num_m = (M + BM - 1) / BM, num_n = (N + BN - 1) / BN, b = blockIdx.x; + const int group = b / (GM * num_n), first_m = group * GM, gsize = min(GM, num_m - first_m); + const int m0 = (first_m + (b % (GM * num_n)) % gsize) * BM, n0 = ((b % (GM * num_n)) / gsize) * BN; + const int sr = tid >> 2, sq = tid & 3; + auto ldA = [&](int k0, int r) -> uint4 { + return *reinterpret_cast(X + (size_t) min(m0 + r, M - 1) * K + k0 + 8 * sq); + }; + auto ldB = [&](int k0, int r) -> uint4 { + return *reinterpret_cast(W + (size_t) min(n0 + r, N - 1) * K + k0 + 8 * sq); + }; + f8 acc[4][TN]; + for (int i = 0; i < 4; ++i) for (int j = 0; j < TN; ++j) acc[i][j] = f8{0, 0, 0, 0, 0, 0, 0, 0}; + uint4 ra0 = ldA(0, sr), ra1 = ldA(0, sr + 64), rb0 = ldB(0, sr), rb1 = ldB(0, sr + 64), rb2 = rb0, rb3 = rb0; + if constexpr (NB > 2) { rb2 = ldB(0, sr + 128); rb3 = ldB(0, sr + 192); } + int buf = 0; + *reinterpret_cast(&sA[0][sr][8 * sq]) = ra0; *reinterpret_cast(&sA[0][sr + 64][8 * sq]) = ra1; + *reinterpret_cast(&sB[0][sr][8 * sq]) = rb0; *reinterpret_cast(&sB[0][sr + 64][8 * sq]) = rb1; + if constexpr (NB > 2) { *reinterpret_cast(&sB[0][sr + 128][8 * sq]) = rb2; *reinterpret_cast(&sB[0][sr + 192][8 * sq]) = rb3; } + __syncthreads(); + for (int k0 = 0; k0 < K; k0 += BK) { + const bool more = k0 + BK < K; + if (more) { + ra0 = ldA(k0 + BK, sr); ra1 = ldA(k0 + BK, sr + 64); rb0 = ldB(k0 + BK, sr); rb1 = ldB(k0 + BK, sr + 64); + if constexpr (NB > 2) { rb2 = ldB(k0 + BK, sr + 128); rb3 = ldB(k0 + BK, sr + 192); } + } +#pragma unroll + for (int ks = 0; ks < BK; ks += 16) { + h16 a[4], bb[TN]; +#pragma unroll + for (int i = 0; i < 4; ++i) a[i] = frag(&sA[buf][64 * wm + 16 * i + l16][ks]); +#pragma unroll + for (int j = 0; j < TN; ++j) bb[j] = frag(&sB[buf][WN * wn + 16 * j + l16][ks]); +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int j = 0; j < TN; ++j) acc[i][j] = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a[i], bb[j], acc[i][j]); + } + if (more) { + const int nb = buf ^ 1; + *reinterpret_cast(&sA[nb][sr][8 * sq]) = ra0; *reinterpret_cast(&sA[nb][sr + 64][8 * sq]) = ra1; + *reinterpret_cast(&sB[nb][sr][8 * sq]) = rb0; *reinterpret_cast(&sB[nb][sr + 64][8 * sq]) = rb1; + if constexpr (NB > 2) { *reinterpret_cast(&sB[nb][sr + 128][8 * sq]) = rb2; *reinterpret_cast(&sB[nb][sr + 192][8 * sq]) = rb3; } + __syncthreads(); + buf = nb; + } + } +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int j = 0; j < TN; ++j) { + const int n = n0 + WN * wn + 16 * j + l16; + if (n >= N) continue; +#pragma unroll + for (int e = 0; e < 8; ++e) { + const int m = m0 + 64 * wm + 16 * i + 2 * e + hi; + if (m < M) { + float* y = Y + (size_t) m * ldy + n; + *y = accumulate ? *y + acc[i][j][e] : acc[i][j][e]; + } + } + } +#endif +} +} // namespace pfg + +bool strata_pf_gemm_f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy, + float beta, void* stream) { + if (!X || !W || !Y || T < 64 || N < 512 || K % pfg::BK != 0 || K < pfg::BK) return false; + if (beta != 0.0f && beta != 1.0f) return false; + if (ldy <= 0) ldy = N; + if (ldy < N || T > (1LL << 30) || N > (1LL << 30) || K > (1LL << 30)) return false; + static const bool gfx11 = [] { + int dev = 0; + hipDeviceProp_t prop{}; + if (hipGetDevice(&dev) != hipSuccess || hipGetDeviceProperties(&prop, dev) != hipSuccess) return false; + return std::strncmp(prop.gcnArchName, "gfx11", 5) == 0; + }(); + if (!gfx11) return false; + hipStream_t s = static_cast(stream); + const int acc = beta == 1.0f ? 1 : 0; + const int64_t mt = (T + pfg::BM - 1) / pfg::BM; + if (N >= 1024) { + const unsigned grid = (unsigned) (mt * ((N + 255) / 256)); + pfg::kernel<256, 64><<>>((const _Float16*) X, (const _Float16*) W, Y, (int) T, (int) N, (int) K, + (int) ldy, acc); + } else { + const unsigned grid = (unsigned) (mt * ((N + 127) / 128)); + pfg::kernel<128, 32><<>>((const _Float16*) X, (const _Float16*) W, Y, (int) T, (int) N, (int) K, + (int) ldy, acc); + } + return hipGetLastError() == hipSuccess; +} + #else // Non-HIP / Non-GFX11 compilation fallback +bool strata_pf_gemm_f16(const uint16_t*, const uint16_t*, float*, int64_t, int64_t, int64_t, int64_t, float, void*) { + return false; +} bool strata_wmma_gemm_f16(const uint16_t*, const uint16_t*, float*, int64_t, int64_t, int64_t, int64_t, float, void*) { diff --git a/src/prefill/wmma_gemm.h b/src/prefill/wmma_gemm.h index 49474dfd..1a5085ca 100644 --- a/src/prefill/wmma_gemm.h +++ b/src/prefill/wmma_gemm.h @@ -17,6 +17,11 @@ bool strata_wmma_gemm_f16(const uint16_t* X, const uint16_t* W, float* Y, /// W: N x K row-major (leading dim K), bf16 (uint16_t) /// Y: T x N row-major with leading dimension ldy >= N, fp32 (float) /// Returns true if executed on WMMA, false if unsupported shape/parameters (fall back to hipblas). +/// S23 (opt-in STRATA_PF_GEMM=1): Y = beta * Y + X . W^T, FP16 in, FP32 out, beta 0 or 1, K a multiple of 32, +/// T >= 64, N >= 512; the 128 x 256 / 128 x 128 grouped-order WMMA kernel. False (nothing launched) otherwise / off gfx11. +bool strata_pf_gemm_f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy, + float beta, void* stream = nullptr); + bool strata_wmma_gemm_bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy, float beta, void* stream = nullptr); From 22abb92dffefa969b89e9a27ee0308c74c35f0f9 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 08:19:26 +0000 Subject: [PATCH 34/55] GDN decode step and activation quantizes: bitwise faster paths (STRATA_GDN_SPLIT=1, opt-in STRATA_QFUSE=1) GDN step (verify_kernels.cu, S25's STRATA_GDN_SPLIT=1 split, handed to S26): - the commit's replay writes no outputs (t_out_begin = MT): y_dummy_ was never read; the state is unchanged; - the commit runs gdn_state_replay_kernel: S25's column split (4 blocks of 32 columns per head) with gate, beta and the v column of every row prefetched and the next row's k / q loaded while the current one computes; - the window keeps the old kernel for one row (the split did not pay there) and runs the split for 2+ rows with gdn_out_norm_kernel rewritten in the old kernel's code shape: S25's 128-thread norm differed from the old kernel by 1 ulp in ~7% of the outputs (405 of 6144 at T=1); the S x RG version is bitwise equal. gfx1151 harness (h_v 48, 36 layers rotating, paired, every layer memcmp-equal): commit 44.1 -> 39.1 us at 1 row, 50.7 -> 41.8 at 3, 60.8 -> 46.1 at 6; window 23.8 -> 23.2 us at 2 rows, 30.1 -> 26.7 at 4. STRATA_QFUSE=1: q8_1 images written by their producers instead of a separate native_quantize_q8_1 launch: - the GDN output norm (both window kernels) quantizes its outputs (warp = one 32-column q8_1 block), contraction off in the quantizer so fma(a, b, shfl) cannot round the first sum differently (that made ds.sum differ by 1 ulp); - the hyper-connection read (gr_up_multi_kernel, gr_up_q8_kernel): the second of the two 16-column blocks of each 32-column group (a per-caller counter, reset by that block) reads the 32 `mixed` values back and quantizes them - attention side into xq_, FFN side into nat_xq_; fused_gr_read_multi returns whether it wrote them (the v3 read does not). gr_parity: new check, T 1..8, direct and graph replays, q8_1 bytes equal to native_quantize_q8_1's. Harness: GDN step + quantize 23.1 -> 20.5 us (1 row), 26.4 -> 23.3 (2), 32.6 -> 27.0 (4), q8_1 bytes equal. Engine (UD-IQ4_XS, c-best2 + the switch, S25's 18 prompts, 256 new tokens): 18/18 identical in every run; c-best2 49.46 / 49.44 tok/s, + STRATA_GDN_SPLIT=1 50.13 / 50.23 / 49.99, + STRATA_QFUSE=1 50.10 / 49.98 / 49.95. --- include/strata/core/verify.hpp | 1 + include/strata/kernels/fused_gr.hpp | 7 +- include/strata/kernels/verify_kernels.hpp | 4 +- src/core/verify.cpp | 37 +++-- src/kernels/cuda/fused_gr.cu | 49 +++++- src/kernels/cuda/verify_kernels.cu | 177 +++++++++++++++++++--- src/kernels/gr_parity.cpp | 49 ++++++ 7 files changed, 285 insertions(+), 39 deletions(-) diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index 34f9ca90..a0c0dde2 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -176,6 +176,7 @@ private: bool device_plan_ = false; ///< E-6: resident-only layers planned on the device (STRATA_VERIFY_DEVICE_PLAN) bool resident_ = false; ///< STRATA_VERIFY_RESIDENT: every expert resident, no host step per layer uint32_t* skip_ = nullptr; ///< E-6: per group, the ring whose plan the device built (0: the host's) + unsigned* qcnt_ = nullptr; ///< S26 STRATA_QFUSE: the HC read's q8_1 group counters (n_embd / 32) unsigned long long* slot_off_d_ = nullptr; ///< E-6: the slot offsets on the device int64_t lb_ = 0, le_ = -1; ///< set_stage: the layers this verifier runs (-1: to the last) const float* hand_in_ = nullptr; diff --git a/include/strata/kernels/fused_gr.hpp b/include/strata/kernels/fused_gr.hpp index 427eae20..d56f21b3 100644 --- a/include/strata/kernels/fused_gr.hpp +++ b/include/strata/kernels/fused_gr.hpp @@ -41,6 +41,10 @@ struct FusedGrArgs { const uint8_t* q8_down = nullptr; ///< Q8_0 [hc_lr][hc*n_embd] const uint8_t* q8_up = nullptr; ///< Q8_0 [hc*n_embd][hc_lr] const uint8_t* q8_inject = nullptr;///< Q8_0 [hc][hc*n_embd] + /// S26 STRATA_QFUSE=1 (fused_gr_read_multi, the default and Q8_0 reads): also write `mixed`'s q8_1 image here (the + /// bytes native_quantize_q8_1 would write); q8_cnt = n_embd / 32 zeroed counters owned by the caller (token 0's) + uint8_t* q8_mixed = nullptr; + unsigned* q8_cnt = nullptr; }; bool fused_gr_supported(int64_t n_embd, int64_t hc, int64_t hc_lr); @@ -51,7 +55,8 @@ void fused_gr_read(const FusedGrArgs& a, void* stream); /// weight pointers and eps must be the same for every t); `xn_scratch` is n_tok * hc * n_embd floats. Every /// token's outputs are bitwise `fused_gr_read(a[t])`. constexpr int kFusedGrMaxT = 8; -void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, +/// Returns true when it also wrote the q8_1 images (every token's q8_mixed set and this read supports it). +bool fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, unsigned long long* stamp_buf = nullptr, int stamp_i0 = 0); /// The multi read's variants (#315; not main's opt-in STRATA_GR_V3 read, which sums in another order), all computing diff --git a/include/strata/kernels/verify_kernels.hpp b/include/strata/kernels/verify_kernels.hpp index 50d951a6..11f31b61 100644 --- a/include/strata/kernels/verify_kernels.hpp +++ b/include/strata/kernels/verify_kernels.hpp @@ -34,7 +34,9 @@ void gdn_ab_multi(const float* x, const uint16_t* w_alpha, const uint16_t* w_bet /// *n_keep tokens are run and the state is written (commit; `y` may be scratch). Bitwise `fused_gdn_step_norm`. void gdn_step_norm_multi(float* state, const float* h, int conv_channels, const float* gate, const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, int n_tok, - const int32_t* n_keep, void* stream, int t_out_begin = 0); + const int32_t* n_keep, void* stream, int t_out_begin = 0, void* xq_out = nullptr); +/// (xq_out, S26 STRATA_QFUSE: also write the q8_1 image of output rows [t_out_begin, n_tok) there - the bytes +/// native_quantize_q8_1(y + t_out_begin * value_dim, xq_out, value_dim, n_tok - t_out_begin) would write.) /// Spin until *flag >= value (a mapped host flag). The value is fixed at capture, so several rings can be /// outstanding at once (the split verify window keeps two). void wait_flag_ge(const uint32_t* flag, uint32_t value, void* stream); diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 10849d75..f690ccb1 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -57,6 +57,8 @@ using Clock = std::chrono::steady_clock; double ms_since(Clock::time_point t) { return std::chrono::duration(Clock::now() - t).count(); } const bool g_dbg = std::getenv("STRATA_VERIFY_DEBUG") != nullptr; const bool g_qdedup = [] { const char* v = std::getenv("STRATA_VERIFY_QDEDUP"); return v != nullptr && std::atoi(v) != 0; }(); +// S26 STRATA_QFUSE=1: activation q8_1 images written by their producers (the GDN output norm) - the same bytes +const bool g_qfuse = [] { const char* v = std::getenv("STRATA_QFUSE"); return v != nullptr && std::atoi(v) != 0; }(); #define VDBG(...) do { if (g_dbg) { std::fprintf(stderr, "verify dbg: " __VA_ARGS__); std::fflush(stderr); } } while (0) struct Bump { @@ -176,6 +178,7 @@ Verifier::~Verifier() { for (auto& e : exec_) if (e) cudaGraphExecDestroy(e); if (commit_exec_) cudaGraphExecDestroy(commit_exec_); + if (qcnt_) cudaFree(qcnt_); if (cs_) cudaStreamDestroy(cs_); if (copy_) { cudaStreamSynchronize(copy_); cudaStreamDestroy(copy_); } if (commit_done_) cudaEventDestroy(commit_done_); @@ -378,6 +381,14 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& : "not every expert is resident - the host-planned window stays"); } } + if (g_qfuse) { // S26: the HC read's q8_1 group counters, zeroed once (each launch leaves them zero) + if (cudaMalloc((void**) &qcnt_, sizeof(unsigned) * (size_t) (g.n_embd / 32)) != cudaSuccess || + cudaMemset(qcnt_, 0, sizeof(unsigned) * (size_t) (g.n_embd / 32)) != cudaSuccess) { + cudaGetLastError(); + if (qcnt_) cudaFree(qcnt_); + qcnt_ = nullptr; + } + } if (device_plan_) { bool ok2 = cudaMalloc((void**) &skip_, 64) == cudaSuccess && cudaMemset(skip_, 0, 64) == cudaSuccess; if (ok2 && hits.slot_off != nullptr && hits.n_slots > 0) { @@ -520,11 +531,16 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { a.q8_inject = (const uint8_t*) wi[half]->hc_q8; a.eps = EPS; a.lo = lo_ + t * g.hc_lr; a.rs = rs_ + t * HC; a.inject_out = inj_out + t * HC; a.mixed = mixed_ + t * N; + if (qcnt_ != nullptr) { // S26 STRATA_QFUSE: the consumer's q8_1 image written by the read itself + a.q8_cnt = qcnt_; + if (half == 0) a.q8_mixed = xq_ + (size_t) (t - tb) * (N / 32) * 36; + else if (strata::kernels::cpu::expert_layout().native) a.q8_mixed = nat_xq_ + (size_t) t * (N / 32) * 36; + } } - fused_gr_read_multi(fa, n, xn_ + (size_t) tb * HC * N, cs, (prof_on_ && grp == 0) ? prof_ : nullptr, + return fused_gr_read_multi(fa, n, xn_ + (size_t) tb * HC * N, cs, (prof_on_ && grp == 0) ? prof_ : nullptr, (int) (l * kProfPer + (half == 0 ? 27 : 30))); }; - gr_read_group(0, pending, inj2_, inj_); + 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; try { @@ -546,7 +562,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { float* hb = h_L_ + (size_t) gi * MT * C; float* gate = gate_L_ + (size_t) gi * MT * HV; float* beta = beta_L_ + (size_t) gi * MT * HV; - native_quantize_q8_1(xm, xq_, (int) N, n, cs); + 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); stamp(l, 2, grp); gdn_conv_l2_multi(conv, qkv, (const float*) wc->data, hb, (int) C, (int) (2 * HK), EPS, n, cs, tb); @@ -559,9 +575,9 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { stamp(l, 5, grp); // the recurrence from the untouched state over tokens [0, te); outputs only for this group's gdn_step_norm_multi(state, hb, (int) C, gate, beta, z_, (const float*) wnm->data, EPS, y_, (int) HK, - (int) HV, te, nullptr, cs, tb); + (int) HV, te, nullptr, cs, tb, g_qfuse ? (void*) xq_ : nullptr); stamp(l, 6, grp); - native_quantize_q8_1(y_ + (size_t) tb * ZV, xq_, (int) ZV, n, cs); + if (!g_qfuse) native_quantize_q8_1(y_ + (size_t) tb * ZV, xq_, (int) ZV, n, cs); // STRATA_QFUSE: done above native_mmvq(wout->native_type, wout->native_data, xq_, bo_ + tb * N, (int) ZV, (int) N, n, cs); } else { // ======================= QSA ======================= @@ -586,7 +602,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { // the per-token GEMVs / norms / RoPEs / copies of this layer as one launch over the // window's rows each - row-wise identical arithmetic (STRATA_DEC_BATCH=0: token by token) const bool qb = dec_batch && n > 1 && native_qsa_enabled() && native_rope_enabled() && !st.kv_q4; - native_quantize_q8_1(xm, xq_, (int) N, n, cs); + if (!q8_attn) native_quantize_q8_1(xm, xq_, (int) N, n, cs); if (qb) bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) wik->data, idx_raw + tb * ID, ID, N, ID, n, cs); 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); @@ -689,7 +705,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { return false; } stamp(l, 16, grp); - gr_read_group(1, true, inj_, inj2_); + const bool q8_ffn = gr_read_group(1, true, inj_, inj2_); // true: nat_xq_ holds the MoE input's q8_1 // the window's rows routed in 2 launches (one router GEMV reading the weight once, one // top-10) instead of 2 per token; every row's arithmetic is the single-token call's (STRATA_DEC_BATCH=0: old) const WeightRef* w_router = v.get("ffn_gate_inp.weight"); @@ -730,7 +746,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { // read it (quantize_q8_1_rows and native_quantize_q8_1 write the same bytes), and the BF16 copy of xm // is skipped when the shared expert's native BF16 gate (which never reads it) is on. const bool qdedup = g_qdedup && strata::kernels::cpu::expert_layout().native; - if (qdedup) quantize_q8_1_rows(xm, n, N, nat_xq_ + (size_t) tb * (N / 32) * 36, cs); + if (qdedup && !q8_ffn) quantize_q8_1_rows(xm, n, N, nat_xq_ + (size_t) tb * (N / 32) * 36, cs); if (!(qdedup && shared_expert_native_bf16())) { if (dec_batch) f32_to_bf16_bulk(mixed_ + tb * N, sh_bf16_ + tb * N, (int64_t) n * N, cs); // contiguous rows else for (int t = tb; t < te; ++t) f32_to_bf16_bulk(mixed_ + t * N, sh_bf16_ + t * N, N, cs); @@ -746,7 +762,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { } if (strata::kernels::cpu::expert_layout().native) { if (!(g_qdedup && strata::kernels::cpu::expert_layout().native)) - quantize_q8_1_rows(xm, n, N, nat_xq_ + (size_t) tb * (N / 32) * 36, cs); + if (!q8_ffn) quantize_q8_1_rows(xm, n, N, nat_xq_ + (size_t) tb * (N / 32) * 36, cs); } else quantize_q8_0_scaled(xm, hit_xq_ + (size_t) tb * (N / 32) * 34, hit_xs_ + (size_t) tb * (N / 32), (int64_t) n * N, cs); stamp(l, 18, grp); @@ -1026,7 +1042,8 @@ bool Verifier::capture_commit(std::string& err) { gdn_conv_commit(conv, qkv, (int) C, commit_, cs_); gdn_step_norm_multi(state, h_L_ + (size_t) gdn_index * MT * C, (int) C, gate_L_ + (size_t) gdn_index * MT * HV, beta_L_ + (size_t) gdn_index * MT * HV, z_, (const float*) wnm->data, EPS, y_dummy_, - (int) g.ssm_k_heads, (int) HV, (int) MT, commit_, cs_); + (int) g.ssm_k_heads, (int) HV, (int) MT, commit_, cs_, + (int) MT); // S26: t_out_begin = MT - the replay's outputs (y_dummy_) are never read ++gdn_index; } else { const QsaState& st = ss.qsa_states[qsa_index]; diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cu index d6515ac3..4546dd05 100644 --- a/src/kernels/cuda/fused_gr.cu +++ b/src/kernels/cuda/fused_gr.cu @@ -145,6 +145,41 @@ struct GrMulti { int T; }; + +// S26 STRATA_QFUSE=1: the q8_1 image of `mixed`, written by the up kernels below. A q8_1 block is 32 columns and an +// up block owns UPM_COLS = 16, so the second of the two blocks that own a 32-column group (a per-group counter, +// incremented after the block's writes are fenced, reset by that block for the next launch) reads the 32 values back +// and quantizes them with native_quantize_q8_1_kernel's quantizer: one warp per token, the same XOR-tree max and sum, +// d = amax / 127, roundf(x / d), ds = (d, sum) - the bytes the separate launch writes. +struct GrQ81 { half2 ds; int8_t qs[32]; }; +static_assert(2 * 16 == 32, "two up blocks per q8_1 group"); +__device__ __forceinline__ void gr_q8_tail(const GrMulti& m, int d0) { + __shared__ int last; + __threadfence(); + __syncthreads(); + if (threadIdx.x == 0) { + unsigned* c = m.a[0].q8_cnt + d0 / 32; + last = atomicAdd(c, 1u) == 1u; + if (last) atomicExch(c, 0u); + } + __syncthreads(); + if (!last) return; + __threadfence(); + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + if (warp >= m.T) return; + const int c0 = (d0 / 32) * 32; + const float xi = *reinterpret_cast(m.a[warp].mixed + c0 + lane); + float amax = fabsf(xi), sum = xi; +#pragma unroll + for (int o = 16; o > 0; o >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o)); +#pragma unroll + for (int o = 16; o > 0; o >>= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o); + const float d = amax / 127.0f; + const int8_t q = amax == 0.0f ? 0 : roundf(xi / d); + GrQ81* y = reinterpret_cast(m.a[warp].q8_mixed) + c0 / 32; + y->qs[lane] = q; + if (lane == 0) y->ds = make_half2(d, sum); +} // Step 1 of `gr_down_kernel`, one block per token, same threads and reduction order: rs[t] and xn[t] to global. __global__ void __launch_bounds__(THREADS) gr_norm_multi_kernel(GrMulti m) { __shared__ float part[WARPS][HC]; @@ -306,6 +341,7 @@ __global__ void __launch_bounds__(THREADS) gr_up_multi_kernel(GrMulti m) { for (int c = 0; c < HC; ++c) s += g[k][c][col]; m.a[k].mixed[d0 + col] = s / (float) HC; } + if (m.a[0].q8_mixed != nullptr) gr_q8_tail(m, d0); // S26 STRATA_QFUSE } @@ -997,6 +1033,7 @@ __global__ void __launch_bounds__(THREADS) gr_up_q8_kernel(GrMulti m, const floa for (int c = 0; c < HC; ++c) sum += g[k][c][col]; m.a[k].mixed[d0 + col] = sum / (float) HC; } + if (m.a[0].q8_mixed != nullptr) gr_q8_tail(m, d0); // S26 STRATA_QFUSE } template void launch_q8_t(const GrMulti& m, float* part, float* ssg, cudaStream_t st, unsigned long long* stamp_buf, @@ -1023,7 +1060,7 @@ void launch_q8(const GrMulti& m, float* scratch, cudaStream_t st, unsigned long } // namespace -void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, unsigned long long* stamp_buf, +bool fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, unsigned long long* stamp_buf, int stamp_i0) { if (n_tok < 1 || n_tok > kFusedGrMaxT || xn_scratch == nullptr) { std::fprintf(stderr, "fused_gr_read_multi: invalid arguments\n"); @@ -1041,6 +1078,11 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi std::exit(1); } } + // S26 STRATA_QFUSE: every token needs its q8_1 destination and token 0 the counters; otherwise none is written + bool q8 = a[0].q8_cnt != nullptr; + for (int t = 0; t < n_tok; ++t) q8 = q8 && a[t].q8_mixed != nullptr; + if (!q8) + for (int t = 0; t < n_tok; ++t) m.a[t].q8_mixed = nullptr; m.xn = xn_scratch; m.T = n_tok; cudaStream_t st = (cudaStream_t) stream; @@ -1051,7 +1093,7 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi std::fprintf(stderr, "fused_gr_read_multi q8: %s\n", cudaGetErrorString(eq)); std::exit(1); } - return; + return q8; } // STRATA_GR_V3=1: the two-kernel read above (another summation order - opt-in) static const bool v3 = [] { const char* v = std::getenv("STRATA_GR_V3"); return v != nullptr && std::atoi(v) != 0; }(); @@ -1095,7 +1137,7 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi std::fprintf(stderr, "fused_gr_read_multi v3: %s\n", cudaGetErrorString(e3)); std::exit(1); } - return; + return false; // the v3 read: no q8_1 (the caller quantizes) } // the default read (STRATA_GR_V3 unset): v1, or the bitwise-equal v2 / v3 this card's check accepted launch_multi(m, fused_gr_variant(), st, stamp_buf, stamp_i0); @@ -1104,6 +1146,7 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi std::fprintf(stderr, "fused_gr_read_multi: %s\n", cudaGetErrorString(e)); std::exit(1); } + return q8; } bool fused_gr_supported(int64_t n_embd, int64_t hc, int64_t hc_lr) { diff --git a/src/kernels/cuda/verify_kernels.cu b/src/kernels/cuda/verify_kernels.cu index 97072de3..7637538b 100644 --- a/src/kernels/cuda/verify_kernels.cu +++ b/src/kernels/cuda/verify_kernels.cu @@ -5,6 +5,7 @@ #include "strata/kernels/verify_kernels.hpp" #include "strata/kernels/dp4a.hpp" +#include #include #include @@ -112,6 +113,25 @@ __global__ void __launch_bounds__(256) gdn_ab_multi_kernel(const float* __restri } } +// S26 (STRATA_QFUSE=1): the q8_1 image of a 32-column block, written by the warp that holds those columns with +// native_quantize_q8_1_kernel's quantizer (the same XOR-tree max and sum, d = amax / 127, roundf(x / d), ds = (d, sum)). +struct GdnQ81 { half2 ds; int8_t qs[32]; }; +__device__ __forceinline__ void gdn_q8_1_store(GdnQ81* __restrict__ xq, size_t idx, float xi) { + // no contraction: xi is a product here, and fma(a, b, shfl) would round the first sum unlike the separate + // quantizer, which reads xi from memory (S26 harness: ds.sum differed by 1 ulp without this) +#pragma clang fp contract(off) + float amax = fabsf(xi), sum = xi; +#pragma unroll + for (int o = 16; o > 0; o >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o)); +#pragma unroll + for (int o = 16; o > 0; o >>= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o); + const float d = amax / 127.0f; + const int8_t q = amax == 0.0f ? 0 : roundf(xi / d); + xq[idx / 32].qs[idx % 32] = q; + if (idx % 32 == 0) xq[idx / 32].ds = make_half2(d, sum); +} + +template __global__ void __launch_bounds__(S * RG) gdn_step_norm_multi_kernel(float* __restrict__ state, const float* __restrict__ hbuf, int C, const float* __restrict__ gate, @@ -119,7 +139,8 @@ __global__ void __launch_bounds__(S * RG) gdn_step_norm_multi_kernel(float* __re const float* __restrict__ z, const float* __restrict__ gamma, float eps, float* __restrict__ y, int h_k, int h_v, int T, - const int32_t* __restrict__ n_keep, int t_out_begin) { + const int32_t* __restrict__ n_keep, int t_out_begin, + GdnQ81* __restrict__ xq) { __shared__ float sk[S], sq[S]; __shared__ float red[RG][S]; __shared__ float wsum[S * RG / 32]; @@ -171,7 +192,13 @@ __global__ void __launch_bounds__(S * RG) gdn_step_norm_multi_kernel(float* __re const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3]; const float scale = rsqrtf(ss / (float) S + eps); const float zz = z[(size_t) t * value_dim + head * S + col]; - y[(size_t) t * value_dim + head * S + col] = oc * scale * gamma[col] * (1.0f / (1.0f + __expf(-zz))); + if constexpr (Q) { + const float yv = oc * scale * gamma[col] * (1.0f / (1.0f + __expf(-zz))); + y[(size_t) t * value_dim + head * S + col] = yv; + gdn_q8_1_store(xq, (size_t) (t - t_out_begin) * value_dim + head * S + col, yv); + } else { + y[(size_t) t * value_dim + head * S + col] = oc * scale * gamma[col] * (1.0f / (1.0f + __expf(-zz))); + } } } if (n_keep != nullptr && n > 0) { @@ -186,7 +213,11 @@ __global__ void __launch_bounds__(S * RG) gdn_step_norm_multi_kernel(float* __re // at ~60 GB/s. Every column's arithmetic is the original's; the output norm, which needs all 128 columns of a head, // moves to gdn_out_norm_kernel: this kernel leaves the unnormalized output `oc` in y and the second kernel sums the // squares by the same warps (columns 32w..32w+31, the same butterfly) in the same order. +// S26: OUT = false (the commit, whose outputs nobody reads) drops the output reduction and its two barriers; the +// norm kernel below has the old kernel's code shape (S x RG threads, rg 0 holding oc), which makes it bitwise equal - +// the 128-thread version differed from the old kernel by 1 ulp in ~7% of the outputs. constexpr int GS_COLS = 32; +template __global__ void __launch_bounds__(GS_COLS * RG) gdn_step_split_kernel(float* __restrict__ state, const float* __restrict__ hbuf, int C, const float* __restrict__ gate, @@ -230,6 +261,7 @@ __global__ void __launch_bounds__(GS_COLS * RG) gdn_step_split_kernel(float* __r s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta); o = fmaf(s[r], sq[rg * RPG + r], o); } + if (!OUT) continue; __syncthreads(); red[rg][lc] = o; __syncthreads(); @@ -243,24 +275,108 @@ __global__ void __launch_bounds__(GS_COLS * RG) gdn_step_split_kernel(float* __r } } -// y = oc * rsqrt(mean(oc^2) + eps) * gamma * sigmoid(z) per head and token, with gdn_step_norm_multi_kernel's sums -__global__ void __launch_bounds__(S) gdn_out_norm_kernel(const float* __restrict__ z, const float* __restrict__ gamma, - float eps, float* __restrict__ y, int h_v, int T, - const int32_t* __restrict__ n_keep, int t_out_begin) { - __shared__ float wsum[S / 32]; - const int head = blockIdx.x, t = blockIdx.y + t_out_begin, col = threadIdx.x; + +// S26: the state-only replay (the commit) with its per-token inputs prefetched - gate, beta and the v column of every +// row up front, the next row's k / q while the current one computes. The arithmetic and its order are +// gdn_step_split_kernel's (gfx1151 harness: state bitwise equal; 44.5 -> 39.1 us at 1 row, 47.4 -> 40.5 at 2, +// 53.8 -> 42.9 at 4, h_v 48). With outputs the prefetch lost (register pressure), so the window keeps the plain split. +template +__global__ void __launch_bounds__(GS_COLS * RG) gdn_state_replay_kernel(float* __restrict__ state, + const float* __restrict__ hbuf, int C, + const float* __restrict__ gate, + const float* __restrict__ beta, int h_k, + int h_v, int T, const int32_t* __restrict__ n_keep) { + __shared__ float sk[S], sq[S]; + __shared__ float red[RG][GS_COLS]; + const int head = blockIdx.x; + const int c0 = blockIdx.y * GS_COLS; + const int lc = threadIdx.x; + const int col = c0 + lc; + const int rg = threadIdx.y; + const int tid = rg * GS_COLS + lc; + const int qh = head % h_k; + const int qk = S * h_k; + const int n = n_keep ? *n_keep : T; + float gv[MAXT], bv[MAXT], vv[MAXT]; +#pragma unroll + for (int t = 0; t < MAXT; ++t) { + if (t < n) { + gv[t] = gate[(size_t) t * h_v + head]; + bv[t] = beta[(size_t) t * h_v + head]; + vv[t] = hbuf[(size_t) t * C + 2 * qk + head * S + col]; + } + } + float kn = 0.0f, qn = 0.0f; + if (n > 0) { kn = hbuf[qk + qh * S + tid]; qn = hbuf[qh * S + tid]; } + float s[RPG]; + float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col; + const size_t row_stride = (size_t) h_v * S; +#pragma unroll + for (int r = 0; r < RPG; ++r) s[r] = base[r * row_stride]; +#pragma unroll + for (int t = 0; t < MAXT; ++t) { + if (t >= n) break; + __syncthreads(); + sk[tid] = kn; sq[tid] = qn; + __syncthreads(); + if (t + 1 < n) { + const float* hn = hbuf + (size_t) (t + 1) * C; + kn = hn[qk + qh * S + tid]; qn = hn[qh * S + tid]; + } + const float g = __expf(gv[t]); + float kv = 0.0f; +#pragma unroll + for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv); + red[rg][lc] = kv; + __syncthreads(); + const float kv_col = red[0][lc] + red[1][lc] + red[2][lc] + red[3][lc]; + const float delta = (vv[t] - g * kv_col) * bv[t]; + float o = 0.0f; // unused: kept because the measured code had it (without it: 51 us instead of 39 at 1 row) +#pragma unroll + for (int r = 0; r < RPG; ++r) { + s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta); + o = fmaf(s[r], sq[rg * RPG + r], o); + } + (void) o; + } + if (n_keep != nullptr && n > 0) { +#pragma unroll + for (int r = 0; r < RPG; ++r) base[r * row_stride] = s[r]; + } +} +// y = oc * rsqrt(mean(oc^2) + eps) * gamma * sigmoid(z) per head and token: gdn_step_norm_multi_kernel's tail with its +// code shape (S x RG threads; rg 0 holds oc, the other row groups contribute 0 to wsum), reading oc from y +template +__global__ void __launch_bounds__(S * RG) gdn_out_norm_kernel(const float* __restrict__ z, const float* __restrict__ gamma, + float eps, float* __restrict__ y, int h_v, int T, + const int32_t* __restrict__ n_keep, int t_out_begin, + GdnQ81* __restrict__ xq) { + __shared__ float wsum[S * RG / 32]; + const int head = blockIdx.x, t = blockIdx.y + t_out_begin, col = threadIdx.x, rg = threadIdx.y; + const int tid = rg * S + col; const int n = n_keep ? *n_keep : T; if (t >= n) return; const int value_dim = S * h_v; - const float oc = y[(size_t) t * value_dim + head * S + col]; - float sq_part = oc * oc; + float oc = 0.0f, sq_part = 0.0f; + if (rg == 0) { + oc = y[(size_t) t * value_dim + head * S + col]; + sq_part = oc * oc; + } for (int o2 = 16; o2 > 0; o2 >>= 1) sq_part += __shfl_xor_sync(0xffffffffu, sq_part, o2); - if ((col & 31) == 0) wsum[col >> 5] = sq_part; + if ((tid & 31) == 0) wsum[tid >> 5] = sq_part; __syncthreads(); - const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3]; - const float scale = rsqrtf(ss / (float) S + eps); - const float zz = z[(size_t) t * value_dim + head * S + col]; - y[(size_t) t * value_dim + head * S + col] = oc * scale * gamma[col] * (1.0f / (1.0f + __expf(-zz))); + if (rg == 0) { + const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3]; + const float scale = rsqrtf(ss / (float) S + eps); + const float zz = z[(size_t) t * value_dim + head * S + col]; + if constexpr (Q) { + const float yv = oc * scale * gamma[col] * (1.0f / (1.0f + __expf(-zz))); + y[(size_t) t * value_dim + head * S + col] = yv; + gdn_q8_1_store(xq, (size_t) (t - t_out_begin) * value_dim + head * S + col, yv); + } else { + y[(size_t) t * value_dim + head * S + col] = oc * scale * gamma[col] * (1.0f / (1.0f + __expf(-zz))); + } + } } __global__ void embedding_gather_dev_kernel(const uint8_t* __restrict__ codes, const float* __restrict__ scales, @@ -494,24 +610,37 @@ void gdn_ab_multi(const float* x, const uint16_t* w_alpha, const uint16_t* w_bet void gdn_step_norm_multi(float* state, const float* h, int conv_channels, const float* gate, const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, int n_tok, - const int32_t* n_keep, void* stream, int t_out_begin) { + const int32_t* n_keep, void* stream, int t_out_begin, void* xq_out) { + GdnQ81* const xq = static_cast(xq_out); // S26: non-null = also the outputs' q8_1 (STRATA_QFUSE) if (!state || !h || !gate || !beta || !z || !gamma || !y || h_k <= 0 || h_v % h_k || n_tok < 1 || n_tok > kVerifyMaxT) { std::fprintf(stderr, "gdn_step_norm_multi: invalid arguments\n"); std::exit(1); } static const bool split = [] { const char* v = std::getenv("STRATA_GDN_SPLIT"); return v && v[0] == '1'; }(); - if (split) { - gdn_step_split_kernel<<>>( - state, h, conv_channels, gate, beta, y, h_k, h_v, n_tok, n_keep, t_out_begin); - if (n_tok > t_out_begin) - gdn_out_norm_kernel<<>>( - z, gamma, eps, y, h_v, n_tok, n_keep, t_out_begin); + // S26: the split runs where it is faster (gfx1151 harness, h_v 48: the commit 8-19% per call; a window of 2+ rows + // 3-13%; one row: no gain, the old kernel stays) - bitwise equal in every case + if (split && (t_out_begin >= n_tok || n_tok - t_out_begin >= 2)) { + const dim3 grid((unsigned) h_v, S / GS_COLS), block(GS_COLS, RG); + if (t_out_begin >= n_tok) { // no outputs (the commit): the state only + gdn_state_replay_kernel<<>>( + state, h, conv_channels, gate, beta, h_k, h_v, n_tok, n_keep); + } else { + gdn_step_split_kernel<<>>( + state, h, conv_channels, gate, beta, y, h_k, h_v, n_tok, n_keep, t_out_begin); + const dim3 ng((unsigned) h_v, (unsigned) (n_tok - t_out_begin)); + if (xq) gdn_out_norm_kernel<<>>(z, gamma, eps, y, h_v, n_tok, n_keep, t_out_begin, xq); + else gdn_out_norm_kernel<<>>(z, gamma, eps, y, h_v, n_tok, n_keep, t_out_begin, nullptr); + } check("gdn_step_norm_multi (split)"); return; } - gdn_step_norm_multi_kernel<<<(unsigned) h_v, dim3(S, RG), 0, (cudaStream_t) stream>>>( - state, h, conv_channels, gate, beta, z, gamma, eps, y, h_k, h_v, n_tok, n_keep, t_out_begin); + if (xq && t_out_begin < n_tok) + gdn_step_norm_multi_kernel<<<(unsigned) h_v, dim3(S, RG), 0, (cudaStream_t) stream>>>( + state, h, conv_channels, gate, beta, z, gamma, eps, y, h_k, h_v, n_tok, n_keep, t_out_begin, xq); + else + gdn_step_norm_multi_kernel<<<(unsigned) h_v, dim3(S, RG), 0, (cudaStream_t) stream>>>( + state, h, conv_channels, gate, beta, z, gamma, eps, y, h_k, h_v, n_tok, n_keep, t_out_begin, nullptr); check("gdn_step_norm_multi"); } diff --git a/src/kernels/gr_parity.cpp b/src/kernels/gr_parity.cpp index b5ceb76c..ce119678 100644 --- a/src/kernels/gr_parity.cpp +++ b/src/kernels/gr_parity.cpp @@ -21,6 +21,7 @@ // Asserted as a property, not as a value, because that is what the source comment claims. #include "strata/kernels/gr.hpp" #include "strata/kernels/fused_gr.hpp" +#include "strata/kernels/native_mmvq.hpp" #include @@ -405,6 +406,54 @@ int fused_multi_lds_parity(const float* d_norm, const uint16_t* d_down, const ui ++bad; } + + // S26 STRATA_QFUSE: the read's own q8_1 image of `mixed` must be the bytes native_quantize_q8_1 writes from it - + // for every T (1..8), directly and through a captured graph replayed twice (the group counters must reset) + { + uint8_t *d_q = nullptr, *d_ref = nullptr; + unsigned* d_cnt = nullptr; + const size_t qbytes = (size_t) T * (N / 32) * 36; + check(cudaMalloc(&d_q, qbytes), "qfuse q8"); + check(cudaMalloc(&d_ref, qbytes), "qfuse ref"); + check(cudaMalloc(&d_cnt, (N / 32) * sizeof(unsigned)), "qfuse counters"); + check(cudaMemset(d_cnt, 0, (N / 32) * sizeof(unsigned)), "qfuse counters zero"); + int qbad = 0; + std::vector hq(qbytes), hr(qbytes); + for (int tt = 1; tt <= T && !qbad; ++tt) { + std::vector qa(args.begin(), args.begin() + tt); + for (int t = 0; t < tt; ++t) { qa[t].q8_mixed = d_q + (size_t) t * (N / 32) * 36; qa[t].q8_cnt = d_cnt; } + for (int rep = 0; rep < 3 && !qbad; ++rep) { + check(cudaMemsetAsync(d_q, 0x5a, qbytes, stream), "qfuse poison"); + bool wrote = false; + cudaGraph_t qg = nullptr; + cudaGraphExec_t qx = nullptr; + if (rep == 0) { + wrote = fused_gr_read_multi(qa.data(), tt, d_xn, stream); + } else { // a captured read, replayed (twice: rep 1 and 2 use fresh captures, each replayed twice) + check(cudaStreamBeginCapture(stream, cudaStreamCaptureModeThreadLocal), "qfuse begin"); + wrote = fused_gr_read_multi(qa.data(), tt, d_xn, stream); + check(cudaStreamEndCapture(stream, &qg), "qfuse end"); + check(cudaGraphInstantiate(&qx, qg, nullptr, nullptr, 0), "qfuse instantiate"); + check(cudaGraphLaunch(qx, stream), "qfuse replay 1"); + check(cudaMemsetAsync(d_q, 0x5a, qbytes, stream), "qfuse poison 2"); + check(cudaGraphLaunch(qx, stream), "qfuse replay 2"); + } + strata::kernels::native_quantize_q8_1(d_mixed, d_ref, N, tt, stream); + check(cudaStreamSynchronize(stream), "qfuse sync"); + if (qx) { cudaGraphExecDestroy(qx); cudaGraphDestroy(qg); } + if (v3) { std::printf(" QFUSE: the v3 read writes no q8_1 (%s)\n", wrote ? "WRONG: it says it did" : "ok"); qbad += wrote; break; } + check(cudaMemcpy(hq.data(), d_q, (size_t) tt * (N / 32) * 36, cudaMemcpyDeviceToHost), "qfuse read"); + check(cudaMemcpy(hr.data(), d_ref, (size_t) tt * (N / 32) * 36, cudaMemcpyDeviceToHost), "qfuse ref read"); + if (!wrote || std::memcmp(hq.data(), hr.data(), (size_t) tt * (N / 32) * 36) != 0) { + std::printf(" QFUSE: T=%d rep %d: %s\n", tt, rep, wrote ? "q8_1 bytes differ" : "not written"); + ++qbad; + } + } + } + std::printf(" fused GR read + q8_1 (STRATA_QFUSE), T 1..8, direct and graph replays: %s\n", qbad ? "FAIL" : "pass"); + bad += qbad; + cudaFree(d_q); cudaFree(d_ref); cudaFree(d_cnt); + } std::printf(" fused GR multi max-T=8 LDS launch and changing graph replay %s\n", bad == 0 ? "pass" : "FAIL"); check(cudaGraphExecDestroy(graph_exec), "multi graph exec destroy"); From 59a7e22fc2fc501149979e369ea32d9adab1b7c0 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 15:33:07 +0000 Subject: [PATCH 35/55] HIP: the grouped decode experts, IQ3_S gate/up + IQ4_NL down, faster and bitwise (opt-in STRATA_EXPERT_V2=1) native_expert_grouped for the UD-IQ4_XS shapes (n_embd 2560, n_ff 640): s26_gu_l_kernel / s26_down_l_kernel keep every row's lane-strided k order, Split::apply expression and warp_sum, so every output is bitwise the old one's; a warp interleaves 4 rows (more loads in flight), the chunk's activation q8_1 rows are read from LDS, and for IQ3_S the 512-entry grid table too (the same values); SwiGLU and its q8_1 run as one launch (contraction off in the quantizer). Other formats / shapes keep native_gu_multi_kernel / native_down_multi_kernel. gfx1151 harness (S26 ws3: real expert blobs, 32 experts x 4 layers = 298 MB, decode-style windows planned as resident_plan does, memcmp of every output, paired HIP events): one layer's experts T=1 140.3 -> 133.3 us, T=2 225.1 -> 204.1, T=3 300.2 -> 265.9 (166 -> 175-185 GB/s). Tried and rejected: non-temporal loads (no gain), whole rows staged in LDS (0.6-0.8x: occupancy), 8 rows per warp for down. Engine (UD-IQ4_XS, c-best3 env + the switch, same binary, S25's 18 prompts): outputs 18/18 identical; 56.6 / 57.0 -> 55.65 / 55.27 (and 55.61 with the fused SwiGLU q8_1) ms per verify window, 48.6-48.9 -> 50.3 tok/s; 59K prompts 2/2 identical, 58.65 -> 56.77 / 56.66 ms per window, 39.70 -> 41.01 / 41.09 tok/s. --- src/kernels/cuda/iq_kernels.cu | 281 +++++++++++++++++++++++++++++++++ 1 file changed, 281 insertions(+) diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index 3081c82c..4a493403 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -1306,6 +1306,280 @@ void launch_mmvq(const uint8_t* W, size_t rb, const block_q8_1* X, float* y, int else mmvq_multi_kernel<<>>(W, rb, X, y, n_in, n_out, ncols); // 8 at a time past 8 } + +// ---------------------------------------------------------------- S26 STRATA_EXPERT_V2=1 (opt-in): IQ3_S gate/up + IQ4_NL down +// Bitwise equal to native_gu_multi_kernel / native_down_multi_kernel (S26 harness, real UD-IQ4_XS expert blobs, T 1-3, +// memcmp of every output): each row's lane sums and warp_sum are the same; a warp interleaves RPW rows (more loads in +// flight) and reads the chunk's activation rows from LDS and, for IQ3_S, the grid table from LDS (the same values). +template __device__ __forceinline__ int ld16i(const uint16_t* p) { + if constexpr (NT) return (int) __builtin_nontemporal_load(p); else return (int) *p; +} +template __device__ __forceinline__ int ldb2(const void* x, int i32) { + const uint16_t* x16 = (const uint16_t*) x; + int x32 = ld16i(x16 + 2 * i32 + 0) << 0; + x32 |= ld16i(x16 + 2 * i32 + 1) << 16; + return x32; +} +template __device__ __forceinline__ int ld8i(const uint8_t* p) { + if constexpr (NT) return (int) __builtin_nontemporal_load(p); else return (int) *p; +} +template __device__ __forceinline__ float ldhalf(const half* p) { + return __half2float(__ushort_as_half((unsigned short) ld16i(reinterpret_cast(p)))); +} +template struct S26Split; +template struct S26Split<21, NT> { // IQ3_S: Split<21>::load with the loads made explicit + using W = Split<21>::W; + __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { + const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx; + const int2 qs_packed = make_int2(ldb2(bq3->qs, iqs + 0), ldb2(bq3->qs, iqs + 1)); + const uint8_t* qs = (const uint8_t*) &qs_packed; + const int qh = ld8i(bq3->qh + iqs / 2); + const int signs_packed_32 = ldb2(bq3->signs, iqs / 2); + const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32; + W r; +#pragma unroll + for (int l0 = 0; l0 < 8; l0 += 2) { + const int2 grid_pos = make_int2(iq3s_grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)], + iq3s_grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]); + const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000); + const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000); + r.g[l0 + 0] = __vsub4(grid_pos.x ^ signs0, signs0); + r.g[l0 + 1] = __vsub4(grid_pos.y ^ signs1, signs1); + } + r.ls = 1 + 2 * ((ld8i(bq3->scales + iqs / 4) >> ((iqs << 1) & 0x04)) & 0x0F); + r.dw = ldhalf(&bq3->d); + return r; + } + __device__ static float apply(const W& r, const block_q8_1* __restrict__ b, int iqs) { return Split<21>::apply(r, b, iqs); } +}; +template struct S26Split<20, NT> { // IQ4_NL + using W = Split<20>::W; + __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { + const block_iq4_nl* bq4 = (const block_iq4_nl*) vbq + kbx; + W r; +#pragma unroll + for (int l = 0; l < 2; ++l) r.v[l] = get_int_from_table_16(ldb2(bq4->qs, iqs + l), kvalues_iq4nl); + r.dw = ldhalf(&bq4->d); + return r; + } + __device__ static float apply(const W& r, const block_q8_1* __restrict__ b, int iqs) { return Split<20>::apply(r, b, iqs); } +}; + +// S26 v13+: v6 (4 interleaved rows per warp) with the IQ3_S grid table (LT) and / or the chunk's activation rows (LX) +// read from LDS: the same table values and the same q8_1 bytes, so the same arithmetic and bits. +struct S26IQ3S { // Split<21>::load with the grid from `grid` (LT) or iq3s_grid itself + using W = Split<21>::W; + template + __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* grid) { + const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx; + const int2 qs_packed = make_int2(get_int_b2(bq3->qs, iqs + 0), get_int_b2(bq3->qs, iqs + 1)); + const uint8_t* qs = (const uint8_t*) &qs_packed; + const int qh = bq3->qh[iqs / 2]; + const int signs_packed_32 = get_int_b2(bq3->signs, iqs / 2); + const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32; + W r; +#pragma unroll + for (int l0 = 0; l0 < 8; l0 += 2) { + const int i0 = qs[l0 + 0] | ((qh << (8 - l0)) & 0x100), i1 = qs[l0 + 1] | ((qh << (7 - l0)) & 0x100); + const int2 grid_pos = LT ? make_int2(grid[i0], grid[i1]) : make_int2(iq3s_grid[i0], iq3s_grid[i1]); + const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000); + const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000); + r.g[l0 + 0] = __vsub4(grid_pos.x ^ signs0, signs0); + r.g[l0 + 1] = __vsub4(grid_pos.y ^ signs1, signs1); + } + r.ls = 1 + 2 * ((bq3->scales[iqs / 4] >> ((iqs << 1) & 0x04)) & 0x0F); + r.dw = __half2float(bq3->d); + return r; + } +}; + +constexpr int S26_XMAX = 2560 / 32; // q8_1 blocks of one activation row (n_embd 2560) + +template +__global__ void __launch_bounds__(256) s26_gu_l_kernel(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_tok, + const block_q8_1* __restrict__ xq, NativeExpertLayout L, + float* __restrict__ gate, float* __restrict__ up) { + __shared__ uint32_t s_grid[LT ? 512 : 1]; + __shared__ block_q8_1 s_x[LX ? GRP_NC * S26_XMAX : 1]; + const int g = blockIdx.y; + if (g >= *n_groups) return; + if constexpr (LT) + for (int i = threadIdx.x; i < 512; i += 256) s_grid[i] = iq3s_grid[i]; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int row0 = blockIdx.x * GU_ROWS * RPW + warp; + const bool live = row0 + GU_ROWS * (RPW - 1) < 2 * L.n_ff; + const uint8_t* blob = (const uint8_t*) grp_ptr[g]; + const uint8_t* wr[RPW]; + int rr[RPW]; + bool upq[RPW]; +#pragma unroll + for (int q = 0; q < RPW; ++q) { + const int row = row0 + q * GU_ROWS; + upq[q] = row >= L.n_ff; + rr[q] = upq[q] ? row - (int) L.n_ff : row; + wr[q] = blob + (upq[q] ? L.up_off : 0) + (size_t) rr[q] * L.gu_row; + } + const uint32_t* grid = LT ? s_grid : reinterpret_cast(iq3s_grid); + const int nb = (int) (L.n_embd / 256), xb = (int) (L.n_embd / 32); + const int e0 = grp_start[g], e1 = grp_start[g + 1]; + for (int e = e0; e < e1; e += GRP_NC) { + const int n = min(GRP_NC, e1 - e); + const block_q8_1* xbase = xq; + int off[GRP_NC]; + if constexpr (LX) { + __syncthreads(); // the previous chunk is done with s_x + for (int i = threadIdx.x; i < n * xb; i += 256) { + const int c = i / xb, j = i - c * xb; + s_x[c * S26_XMAX + j] = xq[(size_t) ent_tok[e + c] * xb + j]; + } +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) off[c] = min(c, n - 1) * S26_XMAX; + xbase = s_x; + } else { +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) off[c] = ent_tok[e + min(c, n - 1)] * xb; + } + if constexpr (LT || LX) __syncthreads(); // s_grid / s_x ready + if (!live) continue; + float s[RPW][GRP_NC]; +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) s[q][c] = 0.0f; + for (int k = lane; k < nb * 8; k += 32) { + const int kbx = k / 8, iqs = 2 * (k % 8); + Split<21>::W w[RPW]; +#pragma unroll + for (int q = 0; q < RPW; ++q) { if constexpr (SL && !LT) w[q] = S26Split<21, false>::load(wr[q], kbx, iqs); else w[q] = S26IQ3S::load(wr[q], kbx, iqs, grid); } +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n) s[q][c] += Split<21>::apply(w[q], xbase + off[c] + kbx * 8, iqs); + } +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n) s[q][c] = warp_sum(s[q][c]); +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n && lane == c) (upq[q] ? up : gate)[(size_t) (e + c) * L.n_ff + rr[q]] = s[q][c]; + } +} + +constexpr int S26_HMAX = 640 / 32; // q8_1 blocks of one SwiGLU row (n_ff 640) + +template +__global__ void __launch_bounds__(256) s26_down_l_kernel(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_dst, + const block_q8_1* __restrict__ hq, NativeExpertLayout L, + float* __restrict__ out) { + __shared__ block_q8_1 s_h[LX ? GRP_NC * S26_HMAX : 1]; + const int g = blockIdx.y; + if (g >= *n_groups) return; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int r0 = blockIdx.x * 8 * RPW + warp; + const bool live = r0 + 8 * (RPW - 1) < L.n_embd; + const uint8_t* blob = (const uint8_t*) grp_ptr[g]; + const uint8_t* wr[RPW]; +#pragma unroll + for (int q = 0; q < RPW; ++q) wr[q] = blob + L.down_off + (size_t) (r0 + 8 * q) * L.d_row; + const int nb = (int) (L.n_ff / 32), hb = (int) (L.n_ff / 32); + const int e0 = grp_start[g], e1 = grp_start[g + 1]; + for (int e = e0; e < e1; e += GRP_NC) { + const int n = min(GRP_NC, e1 - e); + const block_q8_1* hbase = hq; + int off[GRP_NC]; + if constexpr (LX) { + __syncthreads(); + for (int i = threadIdx.x; i < n * hb; i += 256) { + const int c = i / hb, j = i - c * hb; + s_h[c * S26_HMAX + j] = hq[(size_t) (e + c) * hb + j]; + } + __syncthreads(); +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) off[c] = min(c, n - 1) * S26_HMAX; + hbase = s_h; + } else { +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) off[c] = (e + min(c, n - 1)) * hb; + } + if (!live) continue; + float s[RPW][GRP_NC]; +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) s[q][c] = 0.0f; + for (int k = lane; k < nb * 2; k += 32) { + const int kbx = k / 2, iqs = 2 * (k % 2); + Split<20>::W w[RPW]; +#pragma unroll + for (int q = 0; q < RPW; ++q) { if constexpr (SL) w[q] = S26Split<20, false>::load(wr[q], kbx, iqs); else w[q] = Split<20>::load(wr[q], kbx, iqs); } +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n) s[q][c] += Split<20>::apply(w[q], hbase + off[c] + kbx, iqs); + } +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n) s[q][c] = warp_sum(s[q][c]); +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n && lane == c) out[(size_t) ent_dst[e + c] * L.n_embd + r0 + 8 * q] = s[q][c]; + } +} + + +// S26: swiglu_entries_kernel + quantize_q8_1_kernel in one launch (the same h expression, then the same block quantizer, +// contraction off so the product cannot fuse into the first sum); h is still written (it is the scratch the old pair used) +__global__ void s26_swiglu_q8_1_kernel(const float* __restrict__ gate, const float* __restrict__ up, float* __restrict__ h, + block_q8_1* __restrict__ y, long long n) { +#pragma clang fp contract(off) + const long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; // n is a multiple of 32: whole warps only + const float g = gate[i]; + const float xi = (g / (1.0f + __expf(-g))) * up[i]; + h[i] = xi; + float amax = fabsf(xi), sum = xi; +#pragma unroll + for (int o = 16; o > 0; o >>= 1) { + amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o)); + sum += __shfl_xor_sync(0xffffffffu, sum, o); + } + const float d = amax / 127.0f; + const int8_t q = amax == 0.0f ? 0 : roundf(xi / d); + const long long ib = i / 32, iqs = i % 32; + y[ib].qs[iqs] = q; + if (iqs == 0) y[ib].ds = make_half2(d, sum); +} +template +void s26_launch_l(const NativeExpertLayout& L, int64_t cap_groups, cudaStream_t s, const unsigned long long* grp_ptr, + const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_dst, const int32_t* ent_tok, + const block_q8_1* X, float* gate, float* up, float* h, block_q8_1* hq, float* out, long long nh) { + const dim3 ggu((unsigned) (2 * L.n_ff / (GU_ROWS * RG)), (unsigned) cap_groups); + s26_gu_l_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); + if (FQ) { + s26_swiglu_q8_1_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(gate, up, h, hq, nh); + } else { + swiglu_entries_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(gate, up, h, nh); + quantize_q8_1_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(h, hq, nh); + } + const dim3 gd((unsigned) (L.n_embd / (8 * RD)), (unsigned) cap_groups); + s26_down_l_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); +} template void launch_gu(dim3 grid, cudaStream_t s, const unsigned long long* grp_ptr, const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_tok, const block_q8_1* X, const NativeExpertLayout& L, @@ -1450,6 +1724,13 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long float* h = (float*) ((uint8_t*) scratch + 2 * fa); block_q8_1* hq = (block_q8_1*) ((uint8_t*) scratch + 3 * fa); const auto* X = (const block_q8_1*) x_q8_1; + static const bool v2 = [] { const char* v = std::getenv("STRATA_EXPERT_V2"); return v && v[0] == '1'; }(); + if (v2 && L.gu_type == 21 && L.d_type == 20 && L.n_embd == 2560 && L.n_ff == 640) { // S26: see s26_gu_l_kernel + s26_launch_l(L, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, X, gate, up, h, + hq, out, (long long) cap_entries * L.n_ff); + check("native_expert_grouped (v2)"); + return; + } const dim3 ggu((unsigned) ((2 * L.n_ff + GU_ROWS - 1) / GU_ROWS), (unsigned) cap_groups); switch (L.gu_type) { #define STRATA_GU(T) case T: launch_gu(ggu, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; From 2a1c54e7da6809f0df60d47f7beb3b061662137f Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 22:47:42 +0000 Subject: [PATCH 36/55] HIP: several warp sums as one transposed butterfly, bitwise (opt-in STRATA_TSUM=1) A warp that ends with P independent warp sums (P tokens of a row, or rows x tokens) used P xor butterflies of 5 shuffles each. s26_tsum.cuh does them in one transposed butterfly: at offset 16 a lane keeps half of its values and adds the partner's copy of that half, at 8 half again, ... then plain xor steps. Every level adds the same pair of values the butterfly adds (fp add commutes), so each sum is bitwise the same; P - 1 + (5 - log2 P) moves instead of 5 P, as DPP row_xmask / permlanex16 on AMD (__shfl_xor_sync elsewhere). Applied under STRATA_TSUM=1 to the decode kernels that end in several sums: - HC read (STRATA_HC_Q8): gr_down_q8 / gr_up_q8 (ws4 harness, every output equal, T 1-4: 1.00 / 1.03 / 1.03 / 1.15x per read) - STRATA_EXPERT_V2 gate/up and down (ws3 harness, memcmp, T 1-3: 1.03 / 1.05 / 1.06x) - native_mmvq_multi_kernel (exact layout) and the Q8_0 / Q6_K packed kernels - bf16_f32_mmvf_rows_kernel (STRATA_MMVF_ROWS), both reduction stages Engine (gfx1151, UD-IQ4_XS, c-best3 + EXPERT_V2 + Q8_PACKED, S25's 18 prompts): 54.21 -> 52.10 ms per verify window, 51.31 -> 53.73 tok/s, all 18 outputs identical. --- src/kernels/cuda/fused_gr.cu | 234 +++++++++++++++++++++++++++++++- src/kernels/cuda/iq_kernels.cu | 46 ++++++- src/kernels/cuda/native_bf16.cu | 29 +++- src/kernels/cuda/native_mmvq.cu | 82 +++++++++-- src/kernels/cuda/s26_tsum.cuh | 69 ++++++++++ 5 files changed, 441 insertions(+), 19 deletions(-) create mode 100644 src/kernels/cuda/s26_tsum.cuh diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cu index 2d53ffde..dfca46c6 100644 --- a/src/kernels/cuda/fused_gr.cu +++ b/src/kernels/cuda/fused_gr.cu @@ -3,6 +3,7 @@ #include "strata/kernels/fused_gr.hpp" #include "strata/kernels/bf16_bits.hpp" #include "strata/kernels/verify_kernels.hpp" +#include "s26_tsum.cuh" #include #include @@ -1046,12 +1047,241 @@ __global__ void __launch_bounds__(THREADS) gr_up_q8_kernel(GrMulti m, const floa if (m.a[0].q8_mixed != nullptr) gr_q8_tail(m, d0); // S26 STRATA_QFUSE } + +// S26 STRATA_TSUM=1: gr_down_q8_kernel / gr_up_q8_kernel with each row's T per-token warp sums (and the sums of +// squares) as one transposed butterfly (s26_tsum.cuh): bitwise the same values (S26 ws4 harness, every output equal, +// T 1-4: 1.00 / 1.03 / 1.03 / 1.15x per read). PF (all rows' weights in registers before the part / lo phase) was +// slower (0.92-1.03x) and is off. +using s26ts::tsum; +using s26ts::tsum_token; +using s26ts::tsum_lane; +using s26ts::pow2_ceil; +// gr_down_q8_kernel / gr_up_q8_kernel with every per-token warp sum done as one transposed butterfly per row (tsum) +template +__global__ void __launch_bounds__(THREADS) gr_down_q8_fast_kernel(GrMulti m, float* __restrict__ part, float* __restrict__ ssg) { + constexpr int P = pow2_ceil(T); + constexpr int RG_ = LR / (WARPS * RPW); + __shared__ __align__(16) float xs[T][Q8_KC]; + __shared__ float red[WARPS][T]; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const int rg = blockIdx.x, kc = blockIdx.y, c = kc / Q8_CPS; + const bool inj = rg == RG_; + const bool inj_bf16 = inj && m.a[0].q8_inject == nullptr; + const int nrows = inj ? (((m.a[0].q8_inject != nullptr || m.a[0].w_inject != nullptr) && warp < HC) ? 1 : 0) : RPW; + const int row0 = inj ? warp : (rg * WARPS + warp) * RPW; + const uint8_t* wb = inj ? m.a[0].q8_inject : m.a[0].q8_down; + const int sub = lane & 7, bl = lane >> 3; + const int tk = tsum_token

(lane); + const bool owner = lane == tsum_lane

(tk) && tk < T; + uint32_t q[RPW][Q8_SPB]; + float dq[RPW][Q8_SPB]; +#pragma unroll + for (int r = 0; r < RPW; ++r) { + if (r >= nrows || inj_bf16) break; + const uint8_t* row = wb + (size_t) (row0 + r) * (D / 32) * Q8B + (size_t) kc * (Q8_KC / 32) * Q8B; +#pragma unroll + for (int s = 0; s < Q8_SPB; ++s) { + const uint8_t* blk = row + (4 * s + bl) * Q8B; + dq[r][s] = q8_half(q8_ld16(blk)); + q[r][s] = q8_ld16(blk + 2 + 4 * sub) | q8_ld16(blk + 4 + 4 * sub) << 16; + } + } + float ssp[P]; +#pragma unroll + for (int k = 0; k < P; ++k) ssp[k] = 0.0f; +#pragma unroll + for (int k = 0; k < T; ++k) { + const FusedGrArgs& a = m.a[k]; + const float gw = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f; + for (int i = t; i < Q8_KC / 4; i += THREADS) { + const int col = kc * Q8_KC + 4 * i; + float4 r = *reinterpret_cast(a.R + col); + if (a.apply) { + const float4 b = *reinterpret_cast(a.bo_prev + (col - c * N)); + r.x = fmaf(b.x, gw, r.x); r.y = fmaf(b.y, gw, r.y); + r.z = fmaf(b.z, gw, r.z); r.w = fmaf(b.w, gw, r.w); + } + const float4 g = *reinterpret_cast(a.w_norm + col); + ssp[k] += r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w; + *reinterpret_cast(&xs[k][4 * i]) = make_float4(r.x * g.x, r.y * g.y, r.z * g.z, r.w * g.w); + } + } + { + const float v = tsum

(ssp, lane); + if (owner) red[warp][tk] = v; + } + __syncthreads(); + if (rg == 0 && t < T) { + float s = 0.0f; + for (int w = 0; w < WARPS; ++w) s += red[w][t]; + ssg[t * Q8_NKC + kc] = s; + } + if (nrows == 0) return; +#pragma unroll + for (int r = 0; r < RPW; ++r) { + if (r >= nrows) break; + float acc[P]; +#pragma unroll + for (int k = 0; k < P; ++k) acc[k] = 0.0f; +#pragma unroll + for (int s = 0; s < Q8_SPB; ++s) { + const int v = 32 * (4 * s + bl) + 4 * sub; + float4 w; + if (inj_bf16) { + const uint2 b = *reinterpret_cast(m.a[0].w_inject + (size_t) row0 * D + (size_t) kc * Q8_KC + v); + w = make_float4(__uint_as_float(b.x << 16), __uint_as_float(b.x & 0xffff0000u), + __uint_as_float(b.y << 16), __uint_as_float(b.y & 0xffff0000u)); + } else { + w = q8_four(q[r][s], dq[r][s]); + } +#pragma unroll + for (int k = 0; k < T; ++k) { + const float4 x = *reinterpret_cast(&xs[k][v]); + acc[k] = fmaf(w.x, x.x, acc[k]); acc[k] = fmaf(w.y, x.y, acc[k]); + acc[k] = fmaf(w.z, x.z, acc[k]); acc[k] = fmaf(w.w, x.w, acc[k]); + } + } + const int prow = inj ? LR + warp : row0 + r; + const float v = tsum

(acc, lane); + if (owner) part[((size_t) tk * Q8_NKC + kc) * PR + prow] = v; + } +} + +template +__global__ void __launch_bounds__(THREADS) gr_up_q8_fast_kernel(GrMulti m, const float* __restrict__ part, + const float* __restrict__ ssg) { + constexpr int P = pow2_ceil(T); + constexpr int RPW8 = HC * UPM_COLS / WARPS; + __shared__ __align__(16) float lo[T][LR]; + __shared__ float rsS[T][HC]; + __shared__ float g[T][HC][UPM_COLS]; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const int d0 = blockIdx.x * UPM_COLS; + const int tk = tsum_token

(lane); + const bool owner = lane == tsum_lane

(tk) && tk < T; + // PF: every row's weights in registers before the part / lo phase (its latency hides the weight read) + uint32_t pq[PF ? RPW8 : 1][3]; + float pd[PF ? RPW8 : 1][3]; + if constexpr (PF) { +#pragma unroll + for (int qq = 0; qq < RPW8; ++qq) { + const int r = warp + qq * WARPS; + const int c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd; + const uint8_t* row = m.a[0].q8_up + (size_t) i * (LR / 32) * Q8B; +#pragma unroll + for (int s = 0; s < 3; ++s) { + const int v = 4 * lane + 128 * s; + if (v < LR) { + const uint8_t* blk = row + (v >> 5) * Q8B; + pq[qq][s] = q8_ld16(blk + 2 + (v & 31)) | q8_ld16(blk + 4 + (v & 31)) << 16; + pd[qq][s] = q8_half(q8_ld16(blk)); + } else { + pq[qq][s] = 0u; pd[qq][s] = 0.0f; + } + } + } + } + if (t < T * HC) { + const int k = t / HC, c = t - k * HC; + float ss = 0.0f; +#pragma unroll + for (int j = 0; j < Q8_CPS; ++j) ss += ssg[k * Q8_NKC + c * Q8_CPS + j]; + const float r = rsqrtf(ss / (float) N + m.a[k].eps); + rsS[k][c] = r; + if (blockIdx.x == 0) m.a[k].rs[c] = r; + } + __syncthreads(); + for (int i = t; i < T * PR; i += THREADS) { + const int k = i / PR, r = i - k * PR; + if (r >= LR && (blockIdx.x != 0 || m.a[k].w_inject == nullptr)) continue; + float sum = 0.0f; +#pragma unroll + for (int c = 0; c < HC; ++c) { + float p = 0.0f; +#pragma unroll + for (int j = 0; j < Q8_CPS; ++j) p += part[((size_t) k * Q8_NKC + c * Q8_CPS + j) * PR + r]; + sum = fmaf(rsS[k][c], p, sum); + } + if (r < LR) { + const float x = sum / (float) HC; + lo[k][r] = x / (1.0f + __expf(-x)); + } else { + m.a[k].inject_out[r - LR] = sum; + } + } + __syncthreads(); +#pragma unroll(PF ? RPW8 : 2) + for (int qq = 0; qq < RPW8; ++qq) { + const int r = warp + qq * WARPS; + const int c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd; + const uint8_t* row = m.a[0].q8_up + (size_t) i * (LR / 32) * Q8B; + float4 w[3]; +#pragma unroll + for (int s = 0; s < 3; ++s) { + const int v = 4 * lane + 128 * s; + if (PF) { + w[s] = v < LR ? q8_four(pq[PF ? qq : 0][s], pd[PF ? qq : 0][s]) : make_float4(0.0f, 0.0f, 0.0f, 0.0f); + } else if (v < LR) { + const uint8_t* blk = row + (v >> 5) * Q8B; + w[s] = q8_four(q8_ld16(blk + 2 + (v & 31)) | q8_ld16(blk + 4 + (v & 31)) << 16, q8_half(q8_ld16(blk))); + } else { + w[s] = make_float4(0.0f, 0.0f, 0.0f, 0.0f); + } + } + float rv = 0.0f, wn = 0.0f, bo = 0.0f, ip = 0.0f; + bool apply = false; + if (owner) { + const FusedGrArgs& a = m.a[tk]; + rv = a.R[i]; + wn = a.w_norm[i]; + apply = a.apply; + if (apply) { bo = a.bo_prev[d0 + dd]; ip = a.inj_prev[c]; } + } + float acc[P]; +#pragma unroll + for (int k = 0; k < P; ++k) acc[k] = 0.0f; +#pragma unroll + for (int k = 0; k < T; ++k) { +#pragma unroll + for (int s = 0; s < 3; ++s) { + const int v = 4 * lane + 128 * s; + if (v < LR) { + const float4 x = *reinterpret_cast(&lo[k][v]); + acc[k] = fmaf(w[s].x, x.x, acc[k]); acc[k] = fmaf(w[s].y, x.y, acc[k]); + acc[k] = fmaf(w[s].z, x.z, acc[k]); acc[k] = fmaf(w[s].w, x.w, acc[k]); + } + } + } + const float mine = tsum

(acc, lane); + if (owner) { + if (apply) { + rv = fmaf(bo, 2.0f * sigmoidf_(ip / (float) HC), rv); + m.a[tk].R_out[i] = rv; + } + const float x = rv * wn * rsS[tk][c]; + g[tk][c][dd] = x * sigmoidf_(mine); + } + } + __syncthreads(); + for (int i = t; i < T * UPM_COLS; i += THREADS) { + const int k = i / UPM_COLS, col = i - k * UPM_COLS; + float sum = 0.0f; +#pragma unroll + for (int c = 0; c < HC; ++c) sum += g[k][c][col]; + m.a[k].mixed[d0 + col] = sum / (float) HC; + } + if (m.a[0].q8_mixed != nullptr) gr_q8_tail(m, d0); // S26 STRATA_QFUSE +} + template void launch_q8_t(const GrMulti& m, float* part, float* ssg, cudaStream_t st, unsigned long long* stamp_buf, int stamp_i0) { + static const bool ts = [] { const char* v = std::getenv("STRATA_TSUM"); return v && v[0] == '1'; }(); if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, (void*) st); - gr_down_q8_kernel<<>>(m, part, ssg); + if (ts) gr_down_q8_fast_kernel<<>>(m, part, ssg); + else gr_down_q8_kernel<<>>(m, part, ssg); if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, (void*) st); - gr_up_q8_kernel<<>>(m, part, ssg); + if (ts) gr_up_q8_fast_kernel<<>>(m, part, ssg); + else gr_up_q8_kernel<<>>(m, part, ssg); } void launch_q8(const GrMulti& m, float* scratch, cudaStream_t st, unsigned long long* stamp_buf, int stamp_i0) { float* part = scratch; diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index 4a493403..eaaed00d 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -6,6 +6,7 @@ // included unchanged. #include "strata/kernels/iq_kernels.hpp" #include "strata/kernels/dp4a.hpp" +#include "s26_tsum.cuh" #include #include @@ -1395,7 +1396,7 @@ struct S26IQ3S { // Split<21>::load with the grid from `grid` (LT) or iq3s_gri constexpr int S26_XMAX = 2560 / 32; // q8_1 blocks of one activation row (n_embd 2560) -template +template __global__ void __launch_bounds__(256) s26_gu_l_kernel(const unsigned long long* __restrict__ grp_ptr, const int32_t* __restrict__ grp_start, const int32_t* __restrict__ n_groups, @@ -1460,6 +1461,21 @@ __global__ void __launch_bounds__(256) s26_gu_l_kernel(const unsigned long long* for (int c = 0; c < GRP_NC; ++c) if (c < n) s[q][c] += Split<21>::apply(w[q], xbase + off[c] + kbx * 8, iqs); } + if constexpr (TS) { // S26: all RPW x GRP_NC sums in one transposed butterfly (bitwise the same sums) + constexpr int P = s26ts::pow2_ceil(RPW * GRP_NC); + float v[P]; +#pragma unroll + for (int j = 0; j < P; ++j) v[j] = j < RPW * GRP_NC ? s[j / GRP_NC][j % GRP_NC] : 0.0f; + const float sum = s26ts::tsum

(v, lane); + const int j = s26ts::tsum_token

(lane); + if (lane == s26ts::tsum_lane

(j) && j < RPW * GRP_NC) { + const int c = j % GRP_NC; +#pragma unroll + for (int q = 0; q < RPW; ++q) + if (j / GRP_NC == q && c < n) (upq[q] ? up : gate)[(size_t) (e + c) * L.n_ff + rr[q]] = sum; + } + continue; + } #pragma unroll for (int q = 0; q < RPW; ++q) #pragma unroll @@ -1475,7 +1491,7 @@ __global__ void __launch_bounds__(256) s26_gu_l_kernel(const unsigned long long* constexpr int S26_HMAX = 640 / 32; // q8_1 blocks of one SwiGLU row (n_ff 640) -template +template __global__ void __launch_bounds__(256) s26_down_l_kernel(const unsigned long long* __restrict__ grp_ptr, const int32_t* __restrict__ grp_start, const int32_t* __restrict__ n_groups, @@ -1529,6 +1545,18 @@ __global__ void __launch_bounds__(256) s26_down_l_kernel(const unsigned long lon for (int c = 0; c < GRP_NC; ++c) if (c < n) s[q][c] += Split<20>::apply(w[q], hbase + off[c] + kbx, iqs); } + if constexpr (TS) { // S26: all RPW x GRP_NC sums in one transposed butterfly (bitwise the same sums) + constexpr int P = s26ts::pow2_ceil(RPW * GRP_NC); + float v[P]; +#pragma unroll + for (int j = 0; j < P; ++j) v[j] = j < RPW * GRP_NC ? s[j / GRP_NC][j % GRP_NC] : 0.0f; + const float sum = s26ts::tsum

(v, lane); + const int j = s26ts::tsum_token

(lane); + const int q = j / GRP_NC, c = j % GRP_NC; + if (lane == s26ts::tsum_lane

(j) && j < RPW * GRP_NC && c < n) + out[(size_t) ent_dst[e + c] * L.n_embd + r0 + 8 * q] = sum; + continue; + } #pragma unroll for (int q = 0; q < RPW; ++q) #pragma unroll @@ -1565,12 +1593,12 @@ __global__ void s26_swiglu_q8_1_kernel(const float* __restrict__ gate, const flo y[ib].qs[iqs] = q; if (iqs == 0) y[ib].ds = make_half2(d, sum); } -template +template void s26_launch_l(const NativeExpertLayout& L, int64_t cap_groups, cudaStream_t s, const unsigned long long* grp_ptr, const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_dst, const int32_t* ent_tok, const block_q8_1* X, float* gate, float* up, float* h, block_q8_1* hq, float* out, long long nh) { const dim3 ggu((unsigned) (2 * L.n_ff / (GU_ROWS * RG)), (unsigned) cap_groups); - s26_gu_l_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); + s26_gu_l_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); if (FQ) { s26_swiglu_q8_1_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(gate, up, h, hq, nh); } else { @@ -1578,7 +1606,7 @@ void s26_launch_l(const NativeExpertLayout& L, int64_t cap_groups, cudaStream_t quantize_q8_1_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(h, hq, nh); } const dim3 gd((unsigned) (L.n_embd / (8 * RD)), (unsigned) cap_groups); - s26_down_l_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); + s26_down_l_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); } template void launch_gu(dim3 grid, cudaStream_t s, const unsigned long long* grp_ptr, const int32_t* grp_start, @@ -1726,8 +1754,12 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long const auto* X = (const block_q8_1*) x_q8_1; static const bool v2 = [] { const char* v = std::getenv("STRATA_EXPERT_V2"); return v && v[0] == '1'; }(); if (v2 && L.gu_type == 21 && L.d_type == 20 && L.n_embd == 2560 && L.n_ff == 640) { // S26: see s26_gu_l_kernel - s26_launch_l(L, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, X, gate, up, h, - hq, out, (long long) cap_entries * L.n_ff); + // S26 STRATA_TSUM=1: the sums as one transposed butterfly per warp (s26_tsum.cuh; bitwise the same values) + static const bool ts = [] { const char* v = std::getenv("STRATA_TSUM"); return v && v[0] == '1'; }(); + if (ts) s26_launch_l(L, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, X, gate, up, h, + hq, out, (long long) cap_entries * L.n_ff); + else s26_launch_l(L, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, X, gate, up, h, + hq, out, (long long) cap_entries * L.n_ff); check("native_expert_grouped (v2)"); return; } diff --git a/src/kernels/cuda/native_bf16.cu b/src/kernels/cuda/native_bf16.cu index 57b89f09..ce83fd2b 100644 --- a/src/kernels/cuda/native_bf16.cu +++ b/src/kernels/cuda/native_bf16.cu @@ -1,4 +1,5 @@ #include "strata/kernels/bf16_gemv.hpp" +#include "s26_tsum.cuh" #include "strata/kernels/bf16_bits.hpp" #include @@ -123,7 +124,7 @@ __global__ void bf16_f32_mmvf_multi_kernel(const float* __restrict__ x, int64_t // rows again (n_out blocks x T x n_in floats through L2 - the part that grew with T); here a block reads the // activations once for RPB rows. Per output, thread t still walks pairs t, t + BLOCK_SIZE, ... with the same two // ordered FMAs and the same warp and block reductions: bit-identical to bf16_f32_mmvf_multi_kernel. -template +template __global__ void bf16_f32_mmvf_rows_kernel(const float* __restrict__ x, int64_t ldx, const uint16_t* __restrict__ w, float* __restrict__ y, int64_t ldy, int n_in, int n_out, int n_tok) { const int t = threadIdx.x; @@ -161,6 +162,26 @@ __global__ void bf16_f32_mmvf_rows_kernel(const float* __restrict__ x, int64_t l } } } + if constexpr (TS) { // S26 STRATA_TSUM=1: the RPB x NT warp sums (both stages) as transposed butterflies, bitwise the same + constexpr int V = RPB * NT, P = s26ts::pow2_ceil(V); + const int lane = t & 31, j = s26ts::tsum_token

(lane); + const bool own = lane == s26ts::tsum_lane

(j) && j < V; + float v[P]; +#pragma unroll + for (int q = 0; q < P; ++q) v[q] = q < V ? acc[q / NT][q % NT] : 0.0f; + float sum = s26ts::tsum

(v, lane); + if constexpr (BLOCK_SIZE > 32) { + if (own) partials[j / NT][j % NT][t / 32] = sum; + __syncthreads(); + if (t >= 32) return; +#pragma unroll + for (int q = 0; q < P; ++q) v[q] = q < V ? partials[q / NT][q % NT][t] : 0.0f; + sum = s26ts::tsum

(v, lane); + } + const int r = j / NT, k = j % NT; + if (own && o0 + r < n_out && k < n_tok) y[(size_t) k * ldy + o0 + r] = sum; + return; + } #pragma unroll for (int r = 0; r < RPB; ++r) #pragma unroll @@ -192,6 +213,12 @@ void launch_rows(const float* x, int64_t ldx, const uint16_t* w, float* y, int64 cudaStream_t st) { constexpr int RPB = 4; const unsigned nb = (unsigned) ((n_out + RPB - 1) / RPB); + static const bool ts = [] { const char* v = std::getenv("STRATA_TSUM"); return v && v[0] == '1'; }(); + if (ts) { + if (n_tok <= 4) bf16_f32_mmvf_rows_kernel<<>>(x, ldx, w, y, ldy, n_in, n_out, n_tok); + else bf16_f32_mmvf_rows_kernel<<>>(x, ldx, w, y, ldy, n_in, n_out, n_tok); + return; + } if (n_tok <= 4) bf16_f32_mmvf_rows_kernel<<>>(x, ldx, w, y, ldy, n_in, n_out, n_tok); else bf16_f32_mmvf_rows_kernel<<>>(x, ldx, w, y, ldy, n_in, n_out, n_tok); } diff --git a/src/kernels/cuda/native_mmvq.cu b/src/kernels/cuda/native_mmvq.cu index 175ca08d..673a6867 100644 --- a/src/kernels/cuda/native_mmvq.cu +++ b/src/kernels/cuda/native_mmvq.cu @@ -26,6 +26,7 @@ #include "strata/kernels/native_mmvq.hpp" #include "strata/kernels/dp4a.hpp" #include "strata/kernels/iq_kernels.hpp" +#include "s26_tsum.cuh" #include #include @@ -1002,7 +1003,13 @@ struct SmallTraits { // equal to ncols = 1 only to float rounding (the cross-warp reduction groups partial sums differently). bool g_multi_exact = true; // until the upstream layout is timed on an idle GPU (plan rule: default only what is measured) -template +// S26 STRATA_TSUM=1 (TS): warp 0's NCOLS x ROWS sums as one transposed butterfly (s26_tsum.cuh), bitwise the same +static bool s26_tsum_on() { + static const bool on = [] { const char* v = std::getenv("STRATA_TSUM"); return v && v[0] == '1'; }(); + return on; +} + +template __launch_bounds__(NW * WARP, 1) __global__ void native_mmvq_multi_kernel(const typename F::Block* __restrict__ w, const Q81Block* __restrict__ x, @@ -1036,6 +1043,25 @@ __global__ void native_mmvq_multi_kernel(const typename F::Block* __restrict__ w } __syncthreads(); if (threadIdx.y > 0) return; + if constexpr (TS) { + constexpr int V = NCOLS * ROWS, P = s26ts::pow2_ceil(V); + float v[P]; +#pragma unroll + for (int j = 0; j < NCOLS; ++j) +#pragma unroll + for (int i = 0; i < ROWS; ++i) { +#pragma unroll + for (int l = 0; l < NW - 1; ++l) tmp[j][i] += partial[l][j][i][threadIdx.x]; + v[j * ROWS + i] = tmp[j][i]; + } +#pragma unroll + for (int k = V; k < P; ++k) v[k] = 0.0f; + const float sum = s26ts::tsum

(v, int(threadIdx.x)); + const int k = s26ts::tsum_token

(int(threadIdx.x)); + const int j = k / ROWS, i = k % ROWS; + if (int(threadIdx.x) == s26ts::tsum_lane

(k) && k < V && row0 + i < n_out) y[std::size_t(j) * n_out + row0 + i] = sum; + return; + } #pragma unroll for (int j = 0; j < NCOLS; ++j) { #pragma unroll @@ -1061,9 +1087,11 @@ void launch_multi_n(const void* weights, const void* x_q8_1, float* y, int n_in, const dim3 threads(WARP, WARPS); if (n_in / F::DIV < F::BPI) { const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS); - native_mmvq_multi_kernel<<>>(w, x, y, n_in, n_out); + if (s26_tsum_on()) native_mmvq_multi_kernel<<>>(w, x, y, n_in, n_out); + else native_mmvq_multi_kernel<<>>(w, x, y, n_in, n_out); } else { - native_mmvq_multi_kernel<<>>(w, x, y, n_in, n_out); + if (s26_tsum_on()) native_mmvq_multi_kernel<<>>(w, x, y, n_in, n_out); + else native_mmvq_multi_kernel<<>>(w, x, y, n_in, n_out); } } @@ -1166,7 +1194,7 @@ void small_f32(const void* weights, const float* x, void* scratch_q8_1, constexpr int Q8P_PERSIST_GRID = 640; constexpr int Q8P_PERSIST_MAX_IN = 4096; -template +template __launch_bounds__(WARPS * WARP, 1) __global__ void native_q8_0_packed_kernel(const int8_t* __restrict__ qs, const half* __restrict__ dpl, const Q81Block* __restrict__ x, float* __restrict__ y, @@ -1200,7 +1228,21 @@ __global__ void native_q8_0_packed_kernel(const int8_t* __restrict__ qs, const h for (int j = 0; j < NCOLS; ++j) partial[buf][threadIdx.y - 1][j][threadIdx.x] = tmp[j]; } __syncthreads(); - if (threadIdx.y == 0) { + if (TS && threadIdx.y == 0) { // S26 STRATA_TSUM=1: one transposed butterfly, bitwise the same sums + constexpr int P = s26ts::pow2_ceil(NCOLS); + float v[P]; +#pragma unroll + for (int j = 0; j < NCOLS; ++j) { +#pragma unroll + for (int l = 0; l < WARPS - 1; ++l) tmp[j] += partial[buf][l][j][threadIdx.x]; + v[j] = tmp[j]; + } +#pragma unroll + for (int j = NCOLS; j < P; ++j) v[j] = 0.0f; + const float sum = s26ts::tsum

(v, int(threadIdx.x)); + const int j = s26ts::tsum_token

(int(threadIdx.x)); + if (int(threadIdx.x) == s26ts::tsum_lane

(j) && j < NCOLS) y[std::size_t(j) * n_out + row] = sum; + } else if (threadIdx.y == 0) { #pragma unroll for (int j = 0; j < NCOLS; ++j) { #pragma unroll @@ -1222,7 +1264,11 @@ template void q8_packed_launch(const Q8Packed& w, const Q81Block* x, float* y, cudaStream_t s) { const bool persist = w.n_in <= Q8P_PERSIST_MAX_IN; const int grid = persist ? (std::min)(w.n_out, Q8P_PERSIST_GRID) : w.n_out; - native_q8_0_packed_kernel<<>>(w.qs, w.d, x, y, w.n_in, w.n_out, + if (s26_tsum_on()) + native_q8_0_packed_kernel<<>>(w.qs, w.d, x, y, w.n_in, w.n_out, + persist ? grid : w.n_out); + else + native_q8_0_packed_kernel<<>>(w.qs, w.d, x, y, w.n_in, w.n_out, persist ? grid : w.n_out); } @@ -1272,7 +1318,7 @@ int q6p_grid() { return grid; } -template +template __launch_bounds__(WARPS * WARP, 1) __global__ void native_q6_k_packed_kernel(const int* __restrict__ ql, const int* __restrict__ qh, const int8_t* __restrict__ sc, const half* __restrict__ dpl, @@ -1315,7 +1361,21 @@ __global__ void native_q6_k_packed_kernel(const int* __restrict__ ql, const int* for (int j = 0; j < NCOLS; ++j) partial[buf][threadIdx.y - 1][j][threadIdx.x] = tmp[j]; } __syncthreads(); - if (threadIdx.y == 0) { + if (TS && threadIdx.y == 0) { // S26 STRATA_TSUM=1: one transposed butterfly, bitwise the same sums + constexpr int P = s26ts::pow2_ceil(NCOLS); + float v[P]; +#pragma unroll + for (int j = 0; j < NCOLS; ++j) { +#pragma unroll + for (int l = 0; l < WARPS - 1; ++l) tmp[j] += partial[buf][l][j][threadIdx.x]; + v[j] = tmp[j]; + } +#pragma unroll + for (int j = NCOLS; j < P; ++j) v[j] = 0.0f; + const float sum = s26ts::tsum

(v, int(threadIdx.x)); + const int j = s26ts::tsum_token

(int(threadIdx.x)); + if (int(threadIdx.x) == s26ts::tsum_lane

(j) && j < NCOLS) y[std::size_t(j) * n_out + row] = sum; + } else if (threadIdx.y == 0) { #pragma unroll for (int j = 0; j < NCOLS; ++j) { #pragma unroll @@ -1339,7 +1399,11 @@ std::unordered_map& q6_packed_registry() { template void q6_packed_launch(const Q6Packed& w, const Q81Block* x, float* y, cudaStream_t s) { const int grid = (std::min)(w.n_out, q6p_grid()); - native_q6_k_packed_kernel<<>>(w.ql, w.qh, w.sc, w.d, x, y, w.n_in, + if (s26_tsum_on()) + native_q6_k_packed_kernel<<>>(w.ql, w.qh, w.sc, w.d, x, y, w.n_in, + w.n_out, grid); + else + native_q6_k_packed_kernel<<>>(w.ql, w.qh, w.sc, w.d, x, y, w.n_in, w.n_out, grid); } diff --git a/src/kernels/cuda/s26_tsum.cuh b/src/kernels/cuda/s26_tsum.cuh new file mode 100644 index 00000000..38cfc97c --- /dev/null +++ b/src/kernels/cuda/s26_tsum.cuh @@ -0,0 +1,69 @@ +// S26: several warp sums at once (P per-lane values -> P sums), bitwise equal to P separate xor-butterfly warp sums +// (`for (o = 16; o > 0; o >>= 1) v += shfl_xor(v, o)`). At offset 16 a lane keeps half of its P values and adds the +// partner's copy of that half, at 8 half again, ... until one value is left, then plain xor steps for the remaining +// offsets. Every level adds the same pair of values as the butterfly does (fp add commutes, so x + y == y + x +// bitwise), only each lane carries fewer of them: P - 1 + (5 - log2 P) cross-lane moves instead of 5 P. Value j's sum +// ends in the lanes whose bits 4, 3, .. (MSB first) spell j: tsum_lane

(j) is one of them. On AMD the moves are +// DPP row_xmask / permlanex16 instead of ds_bpermute. +#pragma once + +namespace strata::kernels::s26ts { + +#if defined(__HIP_PLATFORM_AMD__) +__device__ __forceinline__ float xmov16(float v) { + return __int_as_float(__builtin_amdgcn_permlanex16(__float_as_int(v), __float_as_int(v), 0x76543210u, 0xfedcba98u, + false, false)); +} +template +__device__ __forceinline__ float xmov(float v) { + if constexpr (O == 16) return xmov16(v); + else return __int_as_float(__builtin_amdgcn_update_dpp(0, __float_as_int(v), 0x160 + O, 0xf, 0xf, false)); +} +#else +template +__device__ __forceinline__ float xmov(float v) { return __shfl_xor_sync(0xffffffffu, v, O); } +#endif + +constexpr int pow2_ceil(int t) { return t <= 1 ? 1 : t <= 2 ? 2 : t <= 4 ? 4 : t <= 8 ? 8 : t <= 16 ? 16 : 32; } +constexpr int log2c(int p) { return p <= 1 ? 0 : p == 2 ? 1 : p == 4 ? 2 : p == 8 ? 3 : p == 16 ? 4 : 5; } + +template +__device__ __forceinline__ float tplain(float x) { + if constexpr (O >= 1) { x += xmov(x); return tplain(x); } + else return x; +} +// v[0..CNT) (CNT a power of two <= 32): this lane's values; returns the sum of value tsum_token(lane) +template +__device__ __forceinline__ float tsum(float* v, int lane) { + if constexpr (CNT > 1) { + constexpr int H = CNT / 2; + const bool hi = (lane & O) != 0; +#pragma unroll + for (int j = 0; j < H; ++j) { + const float send = hi ? v[j] : v[j + H]; + const float keep = hi ? v[j + H] : v[j]; + v[j] = keep + xmov(send); + } + return tsum(v, lane); + } else { + return tplain(v[0]); + } +} +template +__device__ __forceinline__ int tsum_token(int lane) { + constexpr int L = log2c(P); + int k = 0; +#pragma unroll + for (int b = 0; b < L; ++b) k = (k << 1) | ((lane >> (4 - b)) & 1); + return k; +} +template +__device__ __forceinline__ int tsum_lane(int k) { + constexpr int L = log2c(P); + int lane = 0; +#pragma unroll + for (int b = 0; b < L; ++b) lane |= ((k >> (L - 1 - b)) & 1) << (4 - b); + return lane; +} + +} // namespace strata::kernels::s26ts From 75c9fc6baa8e87556703c8c8bab34a14b842711b Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 22:59:47 +0000 Subject: [PATCH 37/55] HIP: STRATA_TSUM also spreads the expert down rows' items evenly over the lanes, bitwise s26_down_l_kernel (STRATA_EXPERT_V2): a warp's 4 rows have 40 (block, half) items each; lane-strided per row, lanes 0-7 took 2 items of every row (8 loads) and lanes 8-31 one (4). Under STRATA_TSUM=1 the 160 items are spread 5 per lane (item p = 32 i + lane is row p / 40), all 5 loads issued before the dots. A lane's items of a row are then exactly those of the per-row layout's lane (l - 40 q) mod 32, in the same order, and an xor butterfly gives the same bits under any rotation of the lanes (each level's partner differs by +-2^j, which is +2^j modulo 2^(j+1)): every output is bitwise the same (ws3 harness, memcmp, T 1-3: 1.09 / 1.11 / 1.12x for gate/up + down with TSUM, vs 1.03 / 1.05 / 1.06x with the butterfly alone). The same spread for gate/up (80 items x 4 rows, 10 per lane in 1-3 load groups) was 0.6-0.8x and is not used. --- src/kernels/cuda/iq_kernels.cu | 48 +++++++++++++++++++++++++++++++--- 1 file changed, 44 insertions(+), 4 deletions(-) diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index eaaed00d..46a07dfe 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -16,6 +16,7 @@ #include "ggml-common.h" #include +#include #include namespace strata::kernels { @@ -1396,6 +1397,13 @@ struct S26IQ3S { // Split<21>::load with the grid from `grid` (LT) or iq3s_gri constexpr int S26_XMAX = 2560 / 32; // q8_1 blocks of one activation row (n_embd 2560) +// S26 BAL: step I of a warp's RPW x NI items (item p = 32 I + lane): rows QA / QB (lanes >= THR take QB) +template struct S26Bal { + static constexpr int P0 = 32 * I, QA = P0 / NI, QB0 = (P0 + 31) / NI, QB = QB0 < RPW ? QB0 : RPW - 1; + static constexpr int THR = (QA + 1) * NI - P0; + static_assert(NI >= 32, "a step spans at most two rows"); +}; + template __global__ void __launch_bounds__(256) s26_gu_l_kernel(const unsigned long long* __restrict__ grp_ptr, const int32_t* __restrict__ grp_start, @@ -1491,7 +1499,7 @@ __global__ void __launch_bounds__(256) s26_gu_l_kernel(const unsigned long long* constexpr int S26_HMAX = 640 / 32; // q8_1 blocks of one SwiGLU row (n_ff 640) -template +template __global__ void __launch_bounds__(256) s26_down_l_kernel(const unsigned long long* __restrict__ grp_ptr, const int32_t* __restrict__ grp_start, const int32_t* __restrict__ n_groups, @@ -1534,6 +1542,36 @@ __global__ void __launch_bounds__(256) s26_down_l_kernel(const unsigned long lon for (int q = 0; q < RPW; ++q) #pragma unroll for (int c = 0; c < GRP_NC; ++c) s[q][c] = 0.0f; + if constexpr (BAL > 0) { // S26: 5 items per lane instead of 8 / 4, in BAL groups (loads first) + constexpr int NI = 2 * S26_HMAX, IT = RPW * NI / 32; + static_assert(RPW * NI % 32 == 0, "whole steps"); + auto group = [&](std::integer_sequence) { + Split<20>::W w[sizeof...(J)]; + int kk[sizeof...(J)]; + bool hh[sizeof...(J)]; + ([&] { + using B = S26Bal; + hh[J] = B::QB != B::QA && lane >= B::THR; + kk[J] = B::P0 + lane - (hh[J] ? B::QB : B::QA) * NI; + const uint8_t* rp = hh[J] ? wr[B::QB] : wr[B::QA]; + if constexpr (SL) w[J] = S26Split<20, false>::load(rp, kk[J] / 2, 2 * (kk[J] % 2)); + else w[J] = Split<20>::load(rp, kk[J] / 2, 2 * (kk[J] % 2)); + }(), ...); + ([&] { + using B = S26Bal; +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n) { + const float v = Split<20>::apply(w[J], hbase + off[c] + kk[J] / 2, 2 * (kk[J] % 2)); + if (hh[J]) s[B::QB][c] += v; else s[B::QA][c] += v; + } + }(), ...); + }; + constexpr int G = (IT + BAL - 1) / BAL; + [&](std::integer_sequence) { + (group.template operator()(std::make_integer_sequence{}), ...); + }(std::make_integer_sequence{}); + } else for (int k = lane; k < nb * 2; k += 32) { const int kbx = k / 2, iqs = 2 * (k % 2); Split<20>::W w[RPW]; @@ -1593,7 +1631,7 @@ __global__ void s26_swiglu_q8_1_kernel(const float* __restrict__ gate, const flo y[ib].qs[iqs] = q; if (iqs == 0) y[ib].ds = make_half2(d, sum); } -template +template void s26_launch_l(const NativeExpertLayout& L, int64_t cap_groups, cudaStream_t s, const unsigned long long* grp_ptr, const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_dst, const int32_t* ent_tok, const block_q8_1* X, float* gate, float* up, float* h, block_q8_1* hq, float* out, long long nh) { @@ -1606,7 +1644,7 @@ void s26_launch_l(const NativeExpertLayout& L, int64_t cap_groups, cudaStream_t quantize_q8_1_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(h, hq, nh); } const dim3 gd((unsigned) (L.n_embd / (8 * RD)), (unsigned) cap_groups); - s26_down_l_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); + s26_down_l_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); } template void launch_gu(dim3 grid, cudaStream_t s, const unsigned long long* grp_ptr, const int32_t* grp_start, @@ -1756,7 +1794,9 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long if (v2 && L.gu_type == 21 && L.d_type == 20 && L.n_embd == 2560 && L.n_ff == 640) { // S26: see s26_gu_l_kernel // S26 STRATA_TSUM=1: the sums as one transposed butterfly per warp (s26_tsum.cuh; bitwise the same values) static const bool ts = [] { const char* v = std::getenv("STRATA_TSUM"); return v && v[0] == '1'; }(); - if (ts) s26_launch_l(L, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, X, gate, up, h, + // (+ down rows' items spread evenly over the lanes, one load group: bitwise, harness 1.09-1.12x vs 1.03-1.06x; + // the same for gate / up was 0.6-0.8x) + if (ts) s26_launch_l(L, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, X, gate, up, h, hq, out, (long long) cap_entries * L.n_ff); else s26_launch_l(L, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, X, gate, up, h, hq, out, (long long) cap_entries * L.n_ff); From b6b7a87d842fe2ad016f08c45944c1e2baed9375 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 22:43:45 +0000 Subject: [PATCH 38/55] prefill: STRATA_PF_SWITCH_MIN_T=N - the S23 rounding-level prompt switches only on chunks of N+ tokens STRATA_HC_UPMIX, STRATA_PA_FAST and STRATA_PF_GEMM change the prompt path's rounding; on short prompts their time gain is negligible but they change the generated text. With N set, chunks shorter than N keep the default arithmetic (and outputs) while long prompts keep the gain. Unset or 0: every chunk, as before. gfx1151, c-best3 + STRATA_PF_SWITCH_MIN_T=4096: S25's 18 prompts (1.0-1.9K tokens) give outputs identical to c-best2 v2 on 18 of 18 (49.28 tok/s; c-best3 without the gate 48.83 / 48.67, other texts). --- src/kernels/cuda/qsa_prompt_attn.cu | 3 ++- src/prefill/gemm.cu | 3 ++- src/prefill/prefill.cpp | 7 ++++++- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/kernels/cuda/qsa_prompt_attn.cu b/src/kernels/cuda/qsa_prompt_attn.cu index 6cfd8e43..2011a974 100644 --- a/src/kernels/cuda/qsa_prompt_attn.cu +++ b/src/kernels/cuda/qsa_prompt_attn.cu @@ -993,7 +993,8 @@ bool launch_wmma(const float* q, const QsaAttnPools& pools, const int32_t* ids, for (int64_t q0 = 0; q0 < n_q; q0 += 65535) { const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535; static const bool fast = [] { const char* e = std::getenv("STRATA_PA_FAST"); return e != nullptr && e[0] == '1'; }(); - if (fast) + static const int64_t min_t = [] { const char* e = std::getenv("STRATA_PF_SWITCH_MIN_T"); return e ? (int64_t) std::atoll(e) : (int64_t) 0; }(); + if (fast && n_q >= min_t) prompt_attn_wmma_kernel<<>>( 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); diff --git a/src/prefill/gemm.cu b/src/prefill/gemm.cu index 0e6b3758..1d425977 100644 --- a/src/prefill/gemm.cu +++ b/src/prefill/gemm.cu @@ -414,7 +414,8 @@ void Gemm::f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_ // #313 (opt-in STRATA_WMMA_GEMM=1): RDNA3 / RDNA3.5 WMMA dense GEMM, before hipBLASLt (falls through when false) static const bool wmma_on = [] { const char* v = std::getenv("STRATA_WMMA_GEMM"); return v && v[0] != 0 && v[0] != '0'; }(); static const bool pf_on = [] { const char* v = std::getenv("STRATA_PF_GEMM"); return v && v[0] == '1'; }(); - if (pf_on && strata_pf_gemm_f16(X, W, Y, T, N, K, ldy, beta, stream_)) return; // S23: opt-in + static const int64_t pf_min_t = [] { const char* v = std::getenv("STRATA_PF_SWITCH_MIN_T"); return v ? (int64_t) std::atoll(v) : (int64_t) 0; }(); + if (pf_on && T >= pf_min_t && strata_pf_gemm_f16(X, W, Y, T, N, K, ldy, beta, stream_)) return; // S23: opt-in if (wmma_on && T >= 16 && (beta == 0.0f || beta == 1.0f) && strata_wmma_gemm_f16(X, W, Y, T, N, K, ldy, beta, stream_)) { return; diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index aebc5161..8af57352 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -170,6 +170,11 @@ inline int bf16x2_mode() { inline bool bf16x2() { return bf16x2_mode() != 0; } // S23 (opt-in STRATA_HC_UPMIX=1): the hyper-connection read's up projection and gr_mix_r as one kernel (gr_upmix, gfx11); // STRATA_HC_UPMIX_CHECK=N also runs the default pair on the first N reads and reports the difference of `mixed` +static int64_t pf_switch_min_t() { // S23: STRATA_PF_SWITCH_MIN_T=N - the rounding-level prompt switches only on chunks of + // N or more tokens (shorter prompts keep the default numerics, and their outputs; the switches pay on long ones) + static const int64_t v = [] { const char* e = std::getenv("STRATA_PF_SWITCH_MIN_T"); return e ? (int64_t) std::atoll(e) : (int64_t) 0; }(); + return v; +} inline bool hc_upmix() { static const bool v = [] { const char* e = std::getenv("STRATA_HC_UPMIX"); return e != nullptr && e[0] == '1'; }(); return v; @@ -1420,7 +1425,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e if (!bf16_proj(m.gemm, wd, m.xn16, m.lo, T, sd, err, 0, m.xn16_lo)) return false; gr_silu(m.lo, m.lo16, T, m.cs, m.lo16_lo); bool upmixed = false; - if (hc_upmix() && !gr_unfused() && !m.lo16_lo && !m.mixed_bf_lo && + if (hc_upmix() && T >= pf_switch_min_t() && !gr_unfused() && !m.lo16_lo && !m.mixed_bf_lo && wu->kind == core::WeightKind::Bf16InF32 && wu->data && wu->ne0 == LR && wu->ne1 == D) { static int checks = [] { const char* e = std::getenv("STRATA_HC_UPMIX_CHECK"); return e ? std::atoi(e) : 0; }(); if (checks > 0) { // the default pair first, kept for the comparison From b08cf3e16061fef13e4da60aa6710ca918d97ecb Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 4 Oct 2026 00:41:01 +0000 Subject: [PATCH 39/55] verify: fewer launches around the shared expert and the KV append, bitwise (opt-in STRATA_LFUSE=1) Per MoE layer of a verify window (2-8 rows, resident combine path): - the shared expert's scalar gate (a 1-row BF16 GEMV, one latency-bound workgroup) rides as one more block of the router GEMV launch (bf16_gemv_fp32_mmvf_multi_aux; the rows kernel's per-output code is the multi kernel's - checked bitwise for 2-8 rows, with and without TSUM) - its sigmoid + row scale move into the combine (combine: the same sigmoid expression, the product rounded on its own with contraction off in that block only, then added as before) - shared gate and up projections in one launch (native_mmvq_pair: blocks n_out.. take the second matrix; Q8_0, exact multi layout, not packed) Per attention layer: the window's int8 KV appends in one launch (kv_append_q8_steps, blockIdx.z = token x K/V; distinct cells). -4 launches per MoE layer, -(n-1) per attention layer; STRATA_LFUSE_GATE=0 / STRATA_LFUSE_PAIR=0 turn the gate / pair parts off. Engine (gfx1151, UD-IQ4_XS, c-best3 + EXPERT_V2 + Q8_PACKED + TSUM, S25's 18 prompts, same binary): 51.29 -> 50.31 ms per verify window, 54.33 -> 55.12 tok/s; 59K prompts 54.19 -> 53.17 ms, 42.97 -> 43.79 tok/s; all outputs identical. --- include/strata/kernels/bf16_gemv.hpp | 6 +++ include/strata/kernels/kv_q8.hpp | 5 +++ include/strata/kernels/native_mmvq.hpp | 4 ++ include/strata/kernels/native_moe.hpp | 5 +++ include/strata/kernels/shared_expert.hpp | 3 +- src/core/verify.cpp | 32 ++++++++++++++- src/kernels/cuda/kv_q8.cu | 24 +++++++++++- src/kernels/cuda/native_bf16.cu | 49 +++++++++++++++++++++-- src/kernels/cuda/native_mmvq.cu | 50 ++++++++++++++++++++++-- src/kernels/cuda/native_moe.cu | 27 +++++++++++-- src/kernels/cuda/shared_expert.cu | 16 ++++++-- 11 files changed, 204 insertions(+), 17 deletions(-) diff --git a/include/strata/kernels/bf16_gemv.hpp b/include/strata/kernels/bf16_gemv.hpp index 906a8f0b..76a347c1 100644 --- a/include/strata/kernels/bf16_gemv.hpp +++ b/include/strata/kernels/bf16_gemv.hpp @@ -48,5 +48,11 @@ void bf16_gemv_fp32_mmvf(const float* x, const uint16_t* w, float* y, /// the weight read once, every output bit-identical to its own single-row call. void bf16_gemv_fp32_mmvf_multi(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy, int64_t n_in, int64_t n_out, int n_tok, void* stream); +/// S26 STRATA_LFUSE: bf16_gemv_fp32_mmvf_multi(x, ldx, w, y, ldy, n_in, n_out, n_tok) plus the 1-row +/// bf16_gemv_fp32_mmvf_multi(x, ldx, w_aux, y_aux, ldy_aux, n_in, 1, n_tok) in ONE launch, every output bitwise the +/// two calls'. Returns false (nothing launched) unless the rows path applies (STRATA_MMVF_ROWS=1, n_out >= 64, 2-8 rows). +bool bf16_gemv_fp32_mmvf_multi_aux(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy, + int64_t n_in, int64_t n_out, int n_tok, const uint16_t* w_aux, float* y_aux, + int64_t ldy_aux, void* stream); } // namespace strata::kernels diff --git a/include/strata/kernels/kv_q8.hpp b/include/strata/kernels/kv_q8.hpp index a535cc32..f8a12f39 100644 --- a/include/strata/kernels/kv_q8.hpp +++ b/include/strata/kernels/kv_q8.hpp @@ -28,6 +28,11 @@ inline uint64_t kv_q8_bytes_per_cell(const QsaShapes& s) { /// Append the cell at step[kStepPos] (graph-capturable: position and page come from device memory). With a host /// copy (KV streaming, `kv_stream.hpp`) the cell is written there too, and to VRAM only if its block is resident. +/// S26 STRATA_LFUSE: n_tok kv_append_q8_step calls (token j: step + j * step_stride, kcur / vcur + j * cur_stride) +/// in one launch, bitwise the same stores (the tokens' cells are distinct). +void kv_append_q8_steps(int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale, const int32_t* page_table, + const int32_t* step, int step_stride, const float* kcur, const float* vcur, int cur_stride, + int n_tok, const QsaShapes& s, void* stream, const KvHostPools* host); void kv_append_q8_step(int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale, const int32_t* page_table, const int32_t* step, const float* kcur, const float* vcur, const QsaShapes& s, void* stream, const KvHostPools* host = nullptr); diff --git a/include/strata/kernels/native_mmvq.hpp b/include/strata/kernels/native_mmvq.hpp index dfb8db5e..5d14c90b 100644 --- a/include/strata/kernels/native_mmvq.hpp +++ b/include/strata/kernels/native_mmvq.hpp @@ -126,5 +126,9 @@ bool native_mmvq_supported(int ggml_type) noexcept; std::size_t native_mmvq_weight_bytes(int ggml_type, int n_in, int n_out); void native_mmvq(int ggml_type, const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream); +/// S26 STRATA_LFUSE: native_mmvq(w1 -> y1) and native_mmvq(w2 -> y2), same type / shape / input, in ONE launch, +/// bitwise the two calls. Returns false (nothing launched) where that is not the case (Q8_0, 2-8 columns only). +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); } // namespace strata::kernels diff --git a/include/strata/kernels/native_moe.hpp b/include/strata/kernels/native_moe.hpp index 1e36dc11..6fc81076 100644 --- a/include/strata/kernels/native_moe.hpp +++ b/include/strata/kernels/native_moe.hpp @@ -22,4 +22,9 @@ void native_moe_combine_multi(const float* parts, const float* weights, const fl /// moe_hit_add (parts += hit) gave, without the zero fill and the add launch. void native_moe_combine_multi_hits(const float* hits, const float* weights, const float* shared, float* output, int64_t n_embd, int64_t k, int n_tok, void* stream); +/// S26 STRATA_LFUSE: the same with `shared` unscaled and shared_gate[t] the shared expert's raw gate logit: the +/// row is scaled by sigmoid(shared_gate[t]) here, bitwise what shared_expert_multi's sigmoid + scale gave. +void native_moe_combine_multi_hits_gated(const float* hits, const float* weights, const float* shared, + const float* shared_gate, float* output, int64_t n_embd, int64_t k, int n_tok, + void* stream); } diff --git a/include/strata/kernels/shared_expert.hpp b/include/strata/kernels/shared_expert.hpp index e9148a10..0ee215d8 100644 --- a/include/strata/kernels/shared_expert.hpp +++ b/include/strata/kernels/shared_expert.hpp @@ -78,7 +78,8 @@ void shared_expert(const uint8_t* x_q8_0, const uint8_t* x_q8k, const uint16_t* /// its q8_1 run as one launch (same values). Null: the separate launches. void shared_expert_multi(int n_tok, const float* x, const uint16_t* x_bf16, const NativeSharedWeights& nw, const uint16_t* gate_inp_bf16, float* gate, float* up, float* g, float* out, int64_t n_embd, - int64_t n_ff, void* stream, const void* x_q8_1_ready = nullptr); + int64_t n_ff, void* stream, const void* x_q8_1_ready = nullptr, + int lfuse = 0); // S26 STRATA_LFUSE: bit 0 gate computed + applied by the caller, bit 1 gate/up pair /// The MoE block's final combination, `ref/moe.py::moe` L156: /// diff --git a/src/core/verify.cpp b/src/core/verify.cpp index b3027cd7..0ee3d184 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -56,6 +56,9 @@ constexpr float EPS = 1e-6f; using Clock = std::chrono::steady_clock; double ms_since(Clock::time_point t) { return std::chrono::duration(Clock::now() - t).count(); } const bool g_dbg = std::getenv("STRATA_VERIFY_DEBUG") != nullptr; +const bool g_lfuse = [] { const char* v = std::getenv("STRATA_LFUSE"); return v != nullptr && v[0] == '1'; }(); +const bool g_lfuse_gate = [] { const char* v = std::getenv("STRATA_LFUSE_GATE"); return v == nullptr || v[0] != '0'; }(); +const bool g_lfuse_pair = [] { const char* v = std::getenv("STRATA_LFUSE_PAIR"); return v == nullptr || v[0] != '0'; }(); const bool g_qdedup = [] { const char* v = std::getenv("STRATA_VERIFY_QDEDUP"); return v != nullptr && std::atoi(v) != 0; }(); // S26 STRATA_QFUSE=1: activation q8_1 images written by their producers (the GDN output norm) - the same bytes const bool g_qfuse = [] { const char* v = std::getenv("STRATA_QFUSE"); return v != nullptr && std::atoi(v) != 0; }(); @@ -436,6 +439,12 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { static const bool dec_batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }(); auto stamp = [&](int64_t l, int i, int grp) { if (prof_on_ && grp == 0) gpu_stamp(prof_, (int) (l * kProfPer + i), cs); }; const int tb_[2] = {0, (T + 1) / 2}, te_[2] = {G == 2 ? (T + 1) / 2 : T, T}; + // S26 STRATA_LFUSE=1: where the shared expert's gate / scale fusions apply (the paths they replace are the ones taken) + auto lfuse_on = [&](int n) { + return g_lfuse && resident_ && native_moe_combine_enabled() && dec_batch && n > 1 && n <= 8 && + shared_expert_native_bf16(); + }; + bool sg_gated_[2] = {false, false}; // per group: the combine applies the shared gate groups_[T] = G; // ---- the window's inputs, from mapped staging @@ -644,6 +653,12 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { } stamp(l, 8, grp); if (grp == 0) copy_from_mapped(tail_snap_ + (size_t) qi * TS, st.idx_tail, TS, cs); + const bool kv_multi = g_lfuse && !st.kv_hybrid && !st.kv_q4 && st.kv_int8 && n > 1; // S26 STRATA_LFUSE + if (kv_multi) + kv_append_q8_steps(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, step_ + tb * kStepCount, + (int) kStepCount, kcur_ + tb * NKV * HD, vcur_ + tb * NKV * HD, (int) (NKV * HD), n, + s, cs, &st.host); + else for (int t = tb; t < te; ++t) { const int32_t* step_t = step_ + t * kStepCount; if (st.kv_hybrid) { // K8V4: the unused half's lanes folded onto the used pool (layer.cpp) @@ -734,8 +749,17 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { // the window's rows routed in 2 launches (one router GEMV reading the weight once, one // top-10) instead of 2 per token; every row's arithmetic is the single-token call's (STRATA_DEC_BATCH=0: old) const WeightRef* w_router = v.get("ffn_gate_inp.weight"); + // S26 STRATA_LFUSE=1: the shared expert's gate row rides in the router GEMV launch, its sigmoid + row scale + // move into the combine, gate + up share one launch (all bitwise; resident combine path, 2-8 rows only) + const WeightRef* w_sgi = lfuse_on(n) && g_lfuse_gate ? v.get("ffn_gate_inp_shexp.weight") : nullptr; + bool sg_ready = false; if (dec_batch && n > 1 && w_router != nullptr && native_router_enabled() && NE == 512 && K == 10) { try { + if (w_sgi != nullptr) + sg_ready = bf16_gemv_fp32_mmvf_multi_aux(mixed_ + tb * N, N, (const uint16_t*) w_router->data, + logits_ + tb * NE, NE, N, NE, n, + (const uint16_t*) w_sgi->data, sh_g_ + tb, 1, cs); + if (!sg_ready) bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) w_router->data, logits_ + tb * NE, NE, N, NE, n, cs); native_router_top10_multi(logits_ + tb * NE, ids_ + tb * K, w_ + tb * K, n, cs); @@ -779,7 +803,9 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { try { shared_expert_multi(n, xm, sh_bf16_ + tb * N, nsw, (const uint16_t*) wgi->data, sh_gate_ + (size_t) tb * g.n_ff, sh_up_ + (size_t) tb * g.n_ff, sh_g_ + tb, shared_ + tb * N, N, g.n_ff, cs, - qdedup ? (const void*) (nat_xq_ + (size_t) tb * (N / 32) * 36) : nullptr); + qdedup ? (const void*) (nat_xq_ + (size_t) tb * (N / 32) * 36) : nullptr, + (sg_ready ? 1 : 0) | (lfuse_on(n) && g_lfuse_pair ? 2 : 0)); + sg_gated_[grp] = sg_ready; } catch (const std::exception& e) { err = std::string("verify shared expert: ") + e.what(); return false; @@ -838,6 +864,10 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { if (resident_ && native_moe_combine_enabled()) { // every row is a hit: combine straight from hit_out as 0.0f + hit (= the zeroed row + moe_hit_add) try { + if (sg_gated_[grp]) + native_moe_combine_multi_hits_gated(hit_out, w_ + tb * K, shared_ + tb * N, sh_g_ + tb, bo_ + tb * N, + N, K, n, cs); + else native_moe_combine_multi_hits(hit_out, w_ + tb * K, shared_ + tb * N, bo_ + tb * N, N, K, n, cs); } catch (const std::exception& e) { err = "verify combine: " + std::string(e.what()); return false; } } else { diff --git a/src/kernels/cuda/kv_q8.cu b/src/kernels/cuda/kv_q8.cu index fb2ccec4..2965f233 100644 --- a/src/kernels/cuda/kv_q8.cu +++ b/src/kernels/cuda/kv_q8.cu @@ -27,14 +27,22 @@ void validate(const QsaShapes& s, const char* what) { } // One block = one 64-value group of one KV head of K (blockIdx.z = 0) or V (1); 64 threads, one value each. +// MULTI (S26 STRATA_LFUSE): blockIdx.z = 2 * token + (K / V); token j reads step + j * step_stride and its rows at +// kcur / vcur + j * cur_stride - every token's code is the single launch's +template __global__ void kv_append_q8_kernel(int8_t* __restrict__ k_q, int8_t* __restrict__ v_q, uint16_t* __restrict__ k_scale, uint16_t* __restrict__ v_scale, const int32_t* __restrict__ table, const int32_t* __restrict__ step, const float* __restrict__ kcur, const float* __restrict__ vcur, int kv_heads, - int head_dim, int page_size, KvHostPools host) { + int head_dim, int page_size, KvHostPools host, int step_stride = 0, + int cur_stride = 0) { + if constexpr (MULTI) { + const int j = blockIdx.z >> 1; + step += (size_t) j * step_stride; kcur += (size_t) j * cur_stride; vcur += (size_t) j * cur_stride; + } const long long pos = (long long) __ldg(step + kStepPos); const int h = blockIdx.x, g = blockIdx.y, t = threadIdx.x; - const bool is_v = blockIdx.z == 1; + const bool is_v = MULTI ? (blockIdx.z & 1) == 1 : blockIdx.z == 1; const int groups = head_dim / KV_Q8_GROUP; const float x = (is_v ? vcur : kcur)[h * head_dim + g * KV_Q8_GROUP + t]; // max |x| over the 64 values: two warps, then combine through shared memory in a fixed order @@ -111,6 +119,18 @@ void kv_append_q8_step(int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_ check("kv_append_q8 launch"); } +void kv_append_q8_steps(int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale, const int32_t* page_table, + const int32_t* step, int step_stride, const float* kcur, const float* vcur, int cur_stride, + int n_tok, const QsaShapes& s, void* stream, const KvHostPools* host) { + validate(s, "kv_append_q8 (steps)"); + if (n_tok < 1) return; + const dim3 grid((unsigned) s.n_head_kv, (unsigned) (s.head_dim / KV_Q8_GROUP), (unsigned) (2 * n_tok)); + kv_append_q8_kernel<<>>( + k_q, v_q, k_scale, v_scale, page_table, step, kcur, vcur, (int) s.n_head_kv, (int) s.head_dim, + (int) s.page_size, host ? *host : KvHostPools{}, step_stride, cur_stride); + check("kv_append_q8 (steps) launch"); +} + void kv_gather_q8_step(const int8_t* k_q, const int8_t* v_q, const uint16_t* k_scale, const uint16_t* v_scale, const int32_t* page_table, const int32_t* ids, const int32_t* step, int64_t max_ids, const QsaShapes& s, uint16_t* k_scratch, uint16_t* v_scratch, void* stream) { diff --git a/src/kernels/cuda/native_bf16.cu b/src/kernels/cuda/native_bf16.cu index ce83fd2b..7b2ec9e7 100644 --- a/src/kernels/cuda/native_bf16.cu +++ b/src/kernels/cuda/native_bf16.cu @@ -124,11 +124,18 @@ __global__ void bf16_f32_mmvf_multi_kernel(const float* __restrict__ x, int64_t // rows again (n_out blocks x T x n_in floats through L2 - the part that grew with T); here a block reads the // activations once for RPB rows. Per output, thread t still walks pairs t, t + BLOCK_SIZE, ... with the same two // ordered FMAs and the same warp and block reductions: bit-identical to bf16_f32_mmvf_multi_kernel. -template +// S26 STRATA_LFUSE=1 (AUX): one more block computes row 0 of w_aux into y_aux[k * ldy_aux] - the same per-output +// code, so each aux output is bitwise what its own bf16_f32_mmvf_multi_kernel launch gave (the shared expert's gate) +template __global__ void bf16_f32_mmvf_rows_kernel(const float* __restrict__ x, int64_t ldx, const uint16_t* __restrict__ w, - float* __restrict__ y, int64_t ldy, int n_in, int n_out, int n_tok) { + float* __restrict__ y, int64_t ldy, int n_in, int n_out, int n_tok, + const uint16_t* __restrict__ w_aux = nullptr, float* __restrict__ y_aux = nullptr, + int64_t ldy_aux = 0) { const int t = threadIdx.x; - const int o0 = blockIdx.x * RPB; + int o0 = blockIdx.x * RPB; + if constexpr (AUX) { + if (blockIdx.x == gridDim.x - 1) { w = w_aux; y = y_aux; ldy = ldy_aux; n_out = 1; o0 = 0; } + } __shared__ float partials[RPB][NT][32]; if constexpr (BLOCK_SIZE > 32) { if (t < 32) @@ -210,10 +217,18 @@ __global__ void bf16_f32_mmvf_rows_kernel(const float* __restrict__ x, int64_t l template void launch_rows(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy, int n_in, int n_out, int n_tok, - cudaStream_t st) { + cudaStream_t st, const uint16_t* w_aux = nullptr, float* y_aux = nullptr, int64_t ldy_aux = 0) { constexpr int RPB = 4; const unsigned nb = (unsigned) ((n_out + RPB - 1) / RPB); static const bool ts = [] { const char* v = std::getenv("STRATA_TSUM"); return v && v[0] == '1'; }(); + if (w_aux != nullptr) { // S26 STRATA_LFUSE: + one aux row block +#define S26_AUX(TSV) \ + if (n_tok <= 4) bf16_f32_mmvf_rows_kernel<<>>(x, ldx, w, y, ldy, n_in, n_out, n_tok, w_aux, y_aux, ldy_aux); \ + else bf16_f32_mmvf_rows_kernel<<>>(x, ldx, w, y, ldy, n_in, n_out, n_tok, w_aux, y_aux, ldy_aux); + if (ts) { S26_AUX(true) } else { S26_AUX(false) } +#undef S26_AUX + return; + } if (ts) { if (n_tok <= 4) bf16_f32_mmvf_rows_kernel<<>>(x, ldx, w, y, ldy, n_in, n_out, n_tok); else bf16_f32_mmvf_rows_kernel<<>>(x, ldx, w, y, ldy, n_in, n_out, n_tok); @@ -238,6 +253,32 @@ int mmvf_block_size(int64_t n_in) { } // namespace +bool bf16_gemv_fp32_mmvf_multi_aux(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy, + int64_t n_in, int64_t n_out, int n_tok, const uint16_t* w_aux, float* y_aux, + int64_t ldy_aux, void* stream) { + static const bool rows = [] { const char* v = std::getenv("STRATA_MMVF_ROWS"); return v && v[0] == '1'; }(); + // exactly the conditions under which both calls would take the rows / multi kernels at the same block size + if (!rows || n_out < 64 || n_tok < 2 || n_tok > 8 || n_in <= 0 || (n_in & 1) != 0 || (ldx & 1) != 0 || x == nullptr || + w == nullptr || y == nullptr || w_aux == nullptr || y_aux == nullptr || (reinterpret_cast(x) & 7u) != 0) + return false; + const cudaStream_t st = (cudaStream_t) stream; + const int ni = (int) n_in, no = (int) n_out; + switch (mmvf_block_size(n_in)) { + case 32: launch_rows<32>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break; + case 64: launch_rows<64>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break; + case 96: launch_rows<96>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break; + case 128: launch_rows<128>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break; + case 160: launch_rows<160>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break; + case 192: launch_rows<192>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break; + case 224: launch_rows<224>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break; + default: launch_rows<256>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break; + } + const cudaError_t result = cudaGetLastError(); + if (result != cudaSuccess) + throw std::runtime_error(std::string("bf16_gemv_fp32_mmvf_multi_aux launch: ") + cudaGetErrorString(result)); + return true; +} + void bf16_gemv_fp32_mmvf_multi(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy, int64_t n_in, int64_t n_out, int n_tok, void* stream) { if (n_tok == 1 && ldy >= n_out) { bf16_gemv_fp32_mmvf(x, w, y, n_in, n_out, stream); return; } diff --git a/src/kernels/cuda/native_mmvq.cu b/src/kernels/cuda/native_mmvq.cu index 673a6867..261ca092 100644 --- a/src/kernels/cuda/native_mmvq.cu +++ b/src/kernels/cuda/native_mmvq.cu @@ -1009,14 +1009,21 @@ static bool s26_tsum_on() { return on; } -template +// S26 STRATA_LFUSE (PAIR): blocks n_out.. compute the same rows of w2 into y2 (two matrices of one shape on one +// input in one launch; each output's code is the single matrix's) +template __launch_bounds__(NW * WARP, 1) __global__ void native_mmvq_multi_kernel(const typename F::Block* __restrict__ w, const Q81Block* __restrict__ x, - float* __restrict__ y, int n_in, int n_out) { + float* __restrict__ y, int n_in, int n_out, + const typename F::Block* __restrict__ w2 = nullptr, float* __restrict__ y2 = nullptr) { constexpr int BPI = F::BPI * NW / WARPS; // blocks per iteration scale with the warp count const int tid = WARP * int(threadIdx.y) + int(threadIdx.x); - const int row0 = ROWS * int(blockIdx.x); + int bxi = int(blockIdx.x); + if constexpr (PAIR) { + if (bxi >= n_out / ROWS) { bxi -= n_out / ROWS; w = w2; y = y2; } + } + const int row0 = ROWS * bxi; const int blocks_per_row = n_in / F::DIV; const int x_stride = n_in / Q8K; // Q8_1 blocks per activation column float tmp[NCOLS][ROWS] = {}; @@ -1874,6 +1881,43 @@ void native_q5_0_f32(const void* weights, const float* x, void* scratch_q8_1, small_f32(weights, x, scratch_q8_1, y, n_in, n_out, ncols, stream); } +template +void q8_0_pair_launch(const Q80Block* w1, const Q80Block* w2, const Q81Block* x, float* y1, float* y2, int n_in, int n_out, + cudaStream_t s) { + using F = SmallTraits; + const dim3 threads(WARP, WARPS); + if (s26_tsum_on()) + native_mmvq_multi_kernel<<>>(w1, x, y1, n_in, n_out, w2, y2); + else + native_mmvq_multi_kernel<<>>(w1, x, y1, n_in, n_out, w2, y2); +} + +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) { + using F = SmallTraits; + // only where both calls would run native_mmvq_multi_kernel (exact layout, not packed) + if (ggml_type != 8 || !g_multi_exact || ncols < 2 || ncols > 8 || n_out <= 0 || n_in <= 0 || n_in % 32 != 0 || + n_in / F::DIV < F::BPI || !w1 || !w2 || !x_q8_1 || !y1 || !y2 || !stream) + return false; + const auto& reg = q8_packed_registry(); + if (reg.count(w1) || reg.count(w2)) return false; + const auto* a = static_cast(w1); + const auto* b = static_cast(w2); + const auto* x = static_cast(x_q8_1); + const auto s = static_cast(stream); + switch (ncols) { + case 2: q8_0_pair_launch<2>(a, b, x, y1, y2, n_in, n_out, s); break; + case 3: q8_0_pair_launch<3>(a, b, x, y1, y2, n_in, n_out, s); break; + case 4: q8_0_pair_launch<4>(a, b, x, y1, y2, n_in, n_out, s); break; + case 5: q8_0_pair_launch<5>(a, b, x, y1, y2, n_in, n_out, s); break; + case 6: q8_0_pair_launch<6>(a, b, x, y1, y2, n_in, n_out, s); break; + case 7: q8_0_pair_launch<7>(a, b, x, y1, y2, n_in, n_out, s); break; + default: q8_0_pair_launch<8>(a, b, x, y1, y2, n_in, n_out, s); break; + } + launch_check(); + return true; +} + void native_q8_0_mmvq(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) { if (q8_packed_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream)) return; // STRATA_Q8_PACKED=1 tensors diff --git a/src/kernels/cuda/native_moe.cu b/src/kernels/cuda/native_moe.cu index a8fa4337..ab3950d9 100644 --- a/src/kernels/cuda/native_moe.cu +++ b/src/kernels/cuda/native_moe.cu @@ -31,10 +31,13 @@ namespace strata::kernels { namespace { std::atomic enabled{false}; -template +// GATED (S26 STRATA_LFUSE): `shared` is the shared expert's unscaled output and sg its raw gate logit per token; +// the row is scaled here as shared_expert_multi did (native_scalar_sigmoid_multi_kernel's expression, then one +// rounded multiply = scale_rows_kernel's `out *= g`), then added as before +template __global__ void combine(const float* __restrict__ parts, const float* __restrict__ weights, const float* __restrict__ shared, float* __restrict__ output, - int64_t n_embd, int k) { + int64_t n_embd, int k, const float* __restrict__ sg = nullptr) { // blockIdx.y = the token of a multi-token launch (0 for the single one) const int64_t tk = blockIdx.y; parts += tk * k * n_embd; weights += tk * k; if (shared) shared += tk * n_embd; output += tk * n_embd; @@ -49,7 +52,15 @@ __global__ void combine(const float* __restrict__ parts, const float* __restrict if (ZADD) p = 0.0f + p; sum += p * weights[expert]; } - if (shared) sum += shared[col]; + if constexpr (GATED) { + // contraction off in this block only: the product is rounded on its own (scale_rows' store), then added +#pragma clang fp contract(off) + const float g = __fdividef(1.0f, 1.0f + __expf(-sg[tk])); + const float sh = shared[col] * g; + sum += sh; + } else { + if (shared) sum += shared[col]; + } output[col] = sum; } bool valid_span(const void* p, size_t bytes) { @@ -89,6 +100,16 @@ void native_moe_combine_multi(const float* parts, const float* weights, const fl const auto error = cudaGetLastError(); if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); } +void native_moe_combine_multi_hits_gated(const float* hits, const float* weights, const float* shared, + const float* shared_gate, float* output, int64_t n_embd, int64_t k, int n_tok, + void* stream) { + if (!stream || n_embd <= 0 || k < 1 || k > 15 || n_tok < 1 || !shared || !shared_gate) + throw std::invalid_argument("native MoE combine (hits, gated) requires a stream, width, 1..15 experts, tokens"); + combine<<(stream)>>>( + hits, weights, shared, output, n_embd, int(k), shared_gate); + const auto error = cudaGetLastError(); + if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); +} void native_moe_combine_multi_hits(const float* hits, const float* weights, const float* shared, float* output, int64_t n_embd, int64_t k, int n_tok, void* stream) { if (!stream || n_embd <= 0 || k < 1 || k > 15 || n_tok < 1) diff --git a/src/kernels/cuda/shared_expert.cu b/src/kernels/cuda/shared_expert.cu index 1bb5c997..3d34c276 100644 --- a/src/kernels/cuda/shared_expert.cu +++ b/src/kernels/cuda/shared_expert.cu @@ -191,14 +191,19 @@ __global__ void scale_rows_kernel(float* __restrict__ out, const float* __restri void shared_expert_multi(int n_tok, const float* x, const uint16_t* x_bf16, const NativeSharedWeights& nw, const uint16_t* gate_inp_bf16, float* gate, float* up, float* g, float* out, int64_t n_embd, - int64_t n_ff, void* stream, const void* x_q8_1_ready) { + int64_t n_ff, void* stream, const void* x_q8_1_ready, int lfuse) { + const bool gate_deferred = (lfuse & 1) != 0, pair = (lfuse & 2) != 0; if (n_tok < 1 || n_tok > 8 || !nw.q8_1 || !nw.gate_data || !nw.up_data || !nw.down_data || !stream) throw std::invalid_argument("shared_expert_multi: needs 1..8 tokens, native weights, scratch and a stream"); cudaStream_t cs = (cudaStream_t) stream; const void* xq = x_q8_1_ready ? x_q8_1_ready : nw.q8_1; if (!x_q8_1_ready) native_quantize_q8_1(x, nw.q8_1, (int) n_embd, n_tok, stream); - native_mmvq(nw.gate_type, nw.gate_data, xq, gate, (int) n_embd, (int) n_ff, n_tok, stream); - native_mmvq(nw.up_type, nw.up_data, xq, up, (int) n_embd, (int) n_ff, n_tok, stream); + // S26 STRATA_LFUSE (gate_deferred): gate and up in one launch where the pair applies (bitwise the two calls) + if (!(pair && nw.gate_type == nw.up_type && + native_mmvq_pair(nw.gate_type, nw.gate_data, nw.up_data, xq, gate, up, (int) n_embd, (int) n_ff, n_tok, stream))) { + native_mmvq(nw.gate_type, nw.gate_data, xq, gate, (int) n_embd, (int) n_ff, n_tok, stream); + native_mmvq(nw.up_type, nw.up_data, xq, up, (int) n_embd, (int) n_ff, n_tok, stream); + } const int n = (int) (n_ff * n_tok); if (x_q8_1_ready != nullptr && (n_ff % 32) == 0) { // STRATA_VERIFY_QDEDUP: swiglu + its q8_1 in one launch native_swiglu_q8_1_kernel<<<(unsigned) ((n + 255) / 256), 256, 0, cs>>>(gate, up, gate, (SwqQ81*) nw.q8_1, n); @@ -207,6 +212,11 @@ void shared_expert_multi(int n_tok, const float* x, const uint16_t* x_bf16, cons native_quantize_q8_1(gate, nw.q8_1, (int) n_ff, n_tok, stream); } native_mmvq(nw.down_type, nw.down_data, nw.q8_1, out, (int) n_ff, (int) n_embd, n_tok, stream); + if (gate_deferred) { // the caller computed g (raw) with the router and scales `out` in the combine + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) throw std::runtime_error(std::string("shared_expert_multi: ") + cudaGetErrorString(e)); + return; + } static const bool batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }(); if (native_bf16 && batch && n_tok > 1) { // one gemv for all rows (outputs identical), one sigmoid launch bf16_gemv_fp32_mmvf_multi(x, n_embd, gate_inp_bf16, g, 1, n_embd, 1, n_tok, stream); From bedb80874196b0d4b9cefb6fcfe173ceee19122a Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 4 Oct 2026 03:00:48 +0200 Subject: [PATCH 40/55] prefill: STRATA_PF_PAD=1 - the S23 prompt GEMM rows padded to stride K + 64, bitwise A 4 KB-multiple row stride (K 2048 / 4096 / 6144 halves) camps on the memory channels: the gfx1151 WMMA prompt GEMM ran ssm_out (N 2560, K 6144) at 19 TFLOPS against 31-32 for K 2560. Padding the rows by 64 halves (gemm_probe8, M 16384): K 6144 19.1 -> 35.0 TFLOPS (W alone 29.0, X alone 23.7), K 2560 31.7 -> 36.6. With STRATA_PF_GEMM=1 on chunks of STRATA_PF_SWITCH_MIN_T+ tokens: Gemm::native dequantizes the weight into the scratch with stride K + 64 (dequant_f16_ld, non-i-quant types) and runs strata_pf_gemm_f16_ld; the FP16 activations of the two K 6144 projections (gdn_recurrence's y16 for ssm_out, gate_attn's out16 for attn_output) are written with stride 6144 + 64. The same products in the same order: the same bits. c-best3 v2 + STRATA_PF_PAD=1 (Aurora, interleaved, same generated ids): prompt 8K 954.2 / 930.7 -> 983.7 / 940.8, 64K 947.0 / 946.2 -> 974.8 / 1014.4 tok/s. --- include/strata/kernels/dequant_bf16.hpp | 5 ++++ include/strata/prefill/gemm.hpp | 5 ++-- include/strata/prefill/kernels.hpp | 7 +++-- src/kernels/cuda/dequant_bf16.cu | 19 ++++++++++--- src/prefill/gemm.cu | 22 +++++++++++++- src/prefill/kernels.cu | 38 ++++++++++++++----------- src/prefill/prefill.cpp | 36 ++++++++++++++++------- src/prefill/wmma_gemm.cu | 21 ++++++++++---- src/prefill/wmma_gemm.h | 4 +++ 9 files changed, 115 insertions(+), 42 deletions(-) diff --git a/include/strata/kernels/dequant_bf16.hpp b/include/strata/kernels/dequant_bf16.hpp index 5a8ed088..bcc7e38f 100644 --- a/include/strata/kernels/dequant_bf16.hpp +++ b/include/strata/kernels/dequant_bf16.hpp @@ -21,6 +21,11 @@ void dequant_bf16(int ggml_type, const void* blocks, int64_t row0, int64_t rows, void dequant_f16(int ggml_type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, uint16_t* out, void* stream); +/// dequant_f16 with output row stride `ld` >= cols (a multiple of 8): S23's padded weight scratch. False (nothing +/// launched) for the i-quant formats and unsupported shapes. +bool dequant_f16_ld(int ggml_type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, int64_t ld, + uint16_t* out, void* stream); + /// The same into FP32 (tests and small tensors). void dequant_f32(int ggml_type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, float* out, void* stream); diff --git a/include/strata/prefill/gemm.hpp b/include/strata/prefill/gemm.hpp index c9ddc6f4..4f3b3263 100644 --- a/include/strata/prefill/gemm.hpp +++ b/include/strata/prefill/gemm.hpp @@ -33,9 +33,10 @@ public: void f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy = 0, float beta = 0.0f); - /// W given as native GGUF blocks of `ggml_type`, dequantized to FP16 in the scratch, X in FP16. + /// W given as native GGUF blocks of `ggml_type`, dequantized to FP16 in the scratch, X in FP16. `ldx` (> K) is + /// X's padded row stride, taken only by STRATA_PF_PAD's path (0 = K). void native(const uint16_t* X, int ggml_type, const void* W_blocks, float* Y, int64_t T, int64_t N, int64_t K, - int64_t ldy = 0, float beta = 0.0f); + int64_t ldy = 0, float beta = 0.0f, int64_t ldx = 0); /// Caller-owned buffers only: the scratch and workspace moved (the prompt path laid its buffers out again). void rebind(uint16_t* scratch, int64_t scratch_elems, void* workspace, size_t ws_bytes); diff --git a/include/strata/prefill/kernels.hpp b/include/strata/prefill/kernels.hpp index f643918a..5c5fe1b6 100644 --- a/include/strata/prefill/kernels.hpp +++ b/include/strata/prefill/kernels.hpp @@ -50,13 +50,14 @@ void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, i /// The recurrence over the chunk, block per value head, state in registers; y[t] = rmsnorm(o) * gamma * sigmoid(z) /// (FP32 and FP16 bits: the out projection is quantized). void gdn_recurrence(float* state, const float* h, const float* gate, const float* beta, const float* z, - const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream); + const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream, + int64_t ld16 = 0); // ld16: y16's row stride (0 = 6144; S23 STRATA_PF_PAD pads it) /// The kernels behind gdn_recurrence, for the parity test: 0 = the column-split kernels + the norm kernel (or the /// one-block-per-head kernel under STRATA_GDN_REC_HEADS), 1 = four lanes per column (no barrier per token) + the grid-stride norm, 2 = the /// one-block-per-head kernel (its fused norm rounds differently). 0 and 1 give the same bits. void gdn_recurrence_variant(int variant, float* state, const float* h, const float* gate, const float* beta, const float* z, const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, - void* stream); + void* stream, int64_t ld16 = 0); // ---- MoE /// softmax over 512, top-10 (ties to the lower id), weights renormalised over the ten (the native router). @@ -86,7 +87,7 @@ void rope(float* x, int64_t T, int64_t heads, int64_t dim, int64_t ld, int64_t p /// q_full [T, 24, 512] (q | gate per head) -> q [T, 24, 256] void split_q(const float* q_full, float* q, int64_t T, void* stream); /// attn[t, h, d] *= sigmoid(q_full[t, h, 256 + d]) -> out16 (fp16 bits: the o-projection is quantized) -void gate_attn(const float* attn, const float* q_full, uint16_t* out16, int64_t T, void* stream); +void gate_attn(const float* attn, const float* q_full, uint16_t* out16, int64_t T, void* stream, int64_t ld16 = 0); /// K and V of T consecutive cells (positions pos0..pos0+T-1; K normed and rotated) into the paged pools: FP16 /// (`k_pool`/`v_pool`) or INT8 codes + FP16 scale per 64 (`k_q`...), the decode append's arithmetic. diff --git a/src/kernels/cuda/dequant_bf16.cu b/src/kernels/cuda/dequant_bf16.cu index 32601d60..e159a96c 100644 --- a/src/kernels/cuda/dequant_bf16.cu +++ b/src/kernels/cuda/dequant_bf16.cu @@ -167,11 +167,11 @@ __device__ __forceinline__ void group32(const uint8_t* row_blocks, int gi_in_row template __global__ void dequant_kernel(const uint8_t* __restrict__ blocks, int64_t row_bytes, int64_t row0, int64_t rows, - int64_t groups_per_row, T* __restrict__ out) { + int64_t groups_per_row, int64_t ld, T* __restrict__ out) { const int64_t g = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; if (g >= rows * groups_per_row) return; const int64_t r = g / groups_per_row, gi = g % groups_per_row; - group32(blocks + (row0 + r) * row_bytes, (int) gi, out + r * groups_per_row * 32 + gi * 32); + group32(blocks + (row0 + r) * row_bytes, (int) gi, out + r * ld + gi * 32); } bool geometry(int type, int& block_elems, int& block_bytes) { @@ -192,7 +192,8 @@ bool geometry(int type, int& block_elems, int& block_bytes) { } template -void launch(int type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, T* out, void* stream) { +void launch(int type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, T* out, void* stream, + int64_t ld = 0) { int be = 0, bb = 0; if (!geometry(type, be, bb) || cols % be != 0 || rows <= 0) { std::fprintf(stderr, "dequant: unsupported type %d or shape %lld x %lld\n", type, (long long) rows, @@ -200,10 +201,11 @@ void launch(int type, const void* blocks, int64_t row0, int64_t rows, int64_t co std::exit(1); } const int64_t row_bytes = cols / be * bb, gpr = cols / 32, total = rows * gpr; + if (ld <= 0) ld = cols; const unsigned grid = (unsigned) ((total + 255) / 256); const uint8_t* p = (const uint8_t*) blocks; cudaStream_t st = (cudaStream_t) stream; -#define STRATA_DQ(TY) dequant_kernel<<>>(p, row_bytes, row0, rows, gpr, out); break +#define STRATA_DQ(TY) dequant_kernel<<>>(p, row_bytes, row0, rows, gpr, ld, out); break switch (type) { case 2: STRATA_DQ(2); case 6: STRATA_DQ(6); @@ -249,6 +251,15 @@ void dequant_f16(int ggml_type, const void* blocks, int64_t row0, int64_t rows, launch(ggml_type, blocks, row0, rows, cols, reinterpret_cast(out), stream); } +bool dequant_f16_ld(int ggml_type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, int64_t ld, + uint16_t* out, void* stream) { + int be = 0, bb = 0; + if (iq_only(ggml_type) || !geometry(ggml_type, be, bb) || cols % be != 0 || rows <= 0 || ld < cols || ld % 8 != 0) + return false; + launch(ggml_type, blocks, row0, rows, cols, reinterpret_cast(out), stream, ld); + return true; +} + void dequant_f32(int ggml_type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, float* out, void* stream) { if (iq_only(ggml_type)) { iq_dequant_f32(ggml_type, (const uint8_t*) blocks + (size_t) row0 * iq_row_bytes(ggml_type, cols), rows * cols, diff --git a/src/prefill/gemm.cu b/src/prefill/gemm.cu index 1d425977..4858bdfb 100644 --- a/src/prefill/gemm.cu +++ b/src/prefill/gemm.cu @@ -437,7 +437,27 @@ void Gemm::f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_ } void Gemm::native(const uint16_t* X, int ggml_type, const void* W_blocks, float* Y, int64_t T, int64_t N, int64_t K, - int64_t ldy, float beta) { + int64_t ldy, float beta, int64_t ldx) { +#ifdef STRATA_USE_HIP + // S23 (opt-in STRATA_PF_PAD=1, with STRATA_PF_GEMM=1 on chunks of STRATA_PF_SWITCH_MIN_T+ tokens): the weight + // dequantized into the scratch with row stride K + 64 halves, so no 4 KB-multiple stride camps on the memory + // channels (gemm_probe8: K 6144 19 -> 29 TFLOPS from W alone, 35 with X padded too). Bitwise the same products. + static const bool pad_on = [] { const char* v = std::getenv("STRATA_PF_PAD"); return v && v[0] == '1'; }(); + static const bool pf_on = [] { const char* v = std::getenv("STRATA_PF_GEMM"); return v && v[0] == '1'; }(); + static const int64_t pf_min_t = [] { const char* v = std::getenv("STRATA_PF_SWITCH_MIN_T"); return v ? (int64_t) std::atoll(v) : (int64_t) 0; }(); + if (pad_on && pf_on && T >= pf_min_t && T >= 64 && N >= 512 && K % 32 == 0 && N * (K + 64) <= scratch_elems_) { + const int64_t ldw = K + 64; + if (strata::kernels::dequant_f16_ld(ggml_type, W_blocks, 0, N, K, ldw, scratch_, stream_) && + strata_pf_gemm_f16_ld(X, ldx > 0 ? ldx : K, scratch_, ldw, Y, T, N, K, ldy, beta, stream_)) { + return; + } + } +#endif + if (ldx > 0 && ldx != K) { + std::fprintf(stderr, "prefill gemm: a padded X (ldx %lld, K %lld) needs STRATA_PF_PAD's path\n", + (long long) ldx, (long long) K); + std::exit(1); + } if (N * K > scratch_elems_) { // Too large for the scratch at once: in row slices. const int64_t rows = scratch_elems_ / K; diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 8322b9a8..450747d1 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -280,7 +280,8 @@ __global__ void __launch_bounds__(S * RG) gdn_rec_kernel(float* __restrict__ sta const float* __restrict__ gate, const float* __restrict__ beta, const float* __restrict__ z, const float* __restrict__ gamma, float eps, - float* __restrict__ y, uint16_t* __restrict__ y16, int64_t T) { + float* __restrict__ y, uint16_t* __restrict__ y16, int64_t T, + int64_t ld16) { __shared__ float sk[S], sq[S], red[RG][S], wsum[16]; const int head = blockIdx.x, col = threadIdx.x, rg = threadIdx.y, tid = rg * S + col; const int qh = head % HK; @@ -324,7 +325,7 @@ __global__ void __launch_bounds__(S * RG) gdn_rec_kernel(float* __restrict__ sta const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3]; const float v = oc * rsqrtf(ss / (float) S + eps) * g_col * sigm(z[t * HV * S + head * S + col]); y[t * HV * S + head * S + col] = v; - y16[t * HV * S + head * S + col] = hf(v); + y16[t * ld16 + head * S + col] = hf(v); } } #pragma unroll @@ -557,7 +558,7 @@ __global__ void __launch_bounds__(QTH) gdn_rec_quad_kernel(float* __restrict__ s // per row with four values per lane rounded differently in its first xor step). __global__ void __launch_bounds__(S) gdn_out_norm_loop_kernel(const float* __restrict__ z, const float* __restrict__ gamma, float eps, float* __restrict__ y, uint16_t* __restrict__ y16, - int64_t rows) { + int64_t rows, int64_t ld16) { __shared__ float wsum[4]; const int col = threadIdx.x; for (int64_t row = blockIdx.x; row < rows; row += gridDim.x) { @@ -570,11 +571,12 @@ __global__ void __launch_bounds__(S) gdn_out_norm_loop_kernel(const float* __res const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3]; const float v = oc * rsqrtf(ss / (float) S + eps) * gamma[col] * sigm(z[at]); y[at] = v; - y16[at] = hf(v); + y16[(size_t) (row / HV) * ld16 + (size_t) (row % HV) * S + col] = hf(v); } } __global__ void __launch_bounds__(S) gdn_out_norm_kernel(const float* __restrict__ z, const float* __restrict__ gamma, - float eps, float* __restrict__ y, uint16_t* __restrict__ y16) { + float eps, float* __restrict__ y, uint16_t* __restrict__ y16, + int64_t ld16) { __shared__ float wsum[4]; const int64_t t = blockIdx.x; const int head = blockIdx.y, col = threadIdx.x; @@ -586,7 +588,7 @@ __global__ void __launch_bounds__(S) gdn_out_norm_kernel(const float* __restrict const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3]; const float v = oc * rsqrtf(ss / (float) S + eps) * gamma[col] * sigm(z[t * HV * S + head * S + col]); y[at] = v; - y16[at] = hf(v); + y16[(size_t) t * ld16 + (size_t) head * S + col] = hf(v); } // ---------------------------------------------------------------- MoE @@ -730,11 +732,11 @@ __global__ void split_q_kernel(const float* __restrict__ qf, float* __restrict__ q[i] = qf[t * 24 * 512 + h * 512 + d]; } __global__ void gate_attn_kernel(const float* __restrict__ a, const float* __restrict__ qf, uint16_t* __restrict__ o16, - int64_t T) { + int64_t T, int64_t ld16) { const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; if (i >= T * 24 * 256) return; const int64_t t = i / (24 * 256), h = (i / 256) % 24, d = i % 256; - o16[i] = hf(a[i] * (1.0f / (1.0f + expf(-qf[t * 24 * 512 + h * 512 + 256 + d])))); + o16[t * ld16 + h * 256 + d] = hf(a[i] * (1.0f / (1.0f + expf(-qf[t * 24 * 512 + h * 512 + 256 + d])))); } // one block per (token, kv head, 64-value group); 64 threads. KV streaming: the pool page only if the block is @@ -974,11 +976,12 @@ void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, i } void gdn_recurrence_variant(int variant, float* state, const float* h, const float* gate, const float* beta, const float* z, const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, - void* stream) { + void* stream, int64_t ld16) { + if (ld16 <= 0) ld16 = (int64_t) HV * S; if (variant == 3) { // diagnostics: the quad recurrence + the old norm kernel if (T > 0) { gdn_rec_quad_kernel<<>>(state, h, gate, beta, y, T); - gdn_out_norm_kernel<<>>(z, gamma, eps, y, y16); + gdn_out_norm_kernel<<>>(z, gamma, eps, y, y16, ld16); } return; } @@ -986,31 +989,31 @@ void gdn_recurrence_variant(int variant, float* state, const float* h, const flo if (T > 0) { gdn_rec_quad_kernel<<>>(state, h, gate, beta, y, T); gdn_out_norm_loop_kernel<<<(unsigned) std::min(T * HV, 4096), S, 0, (cudaStream_t) stream>>>( - z, gamma, eps, y, y16, T * HV); + z, gamma, eps, y, y16, T * HV, ld16); } check("gdn_recurrence (quad)"); return; } static const bool serial = std::getenv("STRATA_GDN_REC_HEADS") != nullptr; // the one-block-per-head kernel (A/B) if (serial || T <= 0 || variant == 2) { - gdn_rec_kernel<<>>(state, h, gate, beta, z, gamma, eps, y, y16, T); + gdn_rec_kernel<<>>(state, h, gate, beta, z, gamma, eps, y, y16, T, ld16); } else { static const bool pipe = [] { const char* v = std::getenv("STRATA_GDN_PIPELINE"); return v == nullptr || std::atoi(v) != 0; }(); if (pipe) // the software-pipelined loads (same bits) gdn_rec_cols_pipe_kernel<<>>(state, h, gate, beta, y, T); else gdn_rec_cols_kernel<<>>(state, h, gate, beta, y, T); - gdn_out_norm_kernel<<>>(z, gamma, eps, y, y16); + gdn_out_norm_kernel<<>>(z, gamma, eps, y, y16, ld16); } check("gdn_recurrence"); } void gdn_recurrence(float* state, const float* h, const float* gate, const float* beta, const float* z, - const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream) { + const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream, int64_t ld16) { // Aurora (S23): four lanes per column + the grid-stride norm, the same bits (tests/hip/gdn_rec_head.cpp); // STRATA_GDN_HEAD=0 (or STRATA_GDN_REC_HEADS) keeps the earlier kernels static const bool head = [] { const char* v = std::getenv("STRATA_GDN_HEAD"); return v == nullptr || std::atoi(v) != 0; }(); static const bool serial = std::getenv("STRATA_GDN_REC_HEADS") != nullptr; - gdn_recurrence_variant(head && !serial ? 1 : 0, state, h, gate, beta, z, gamma, eps, y, y16, T, stream); + gdn_recurrence_variant(head && !serial ? 1 : 0, state, h, gate, beta, z, gamma, eps, y, y16, T, stream, ld16); } void route(const float* logits, int32_t* ids, float* weights, int64_t T, int64_t n_expert, void* stream) { if (n_expert == 512) @@ -1090,8 +1093,9 @@ void split_q(const float* q_full, float* q, int64_t T, void* stream) { split_q_kernel<<>>(q_full, q, T); check("split_q"); } -void gate_attn(const float* attn, const float* q_full, uint16_t* out16, int64_t T, void* stream) { - gate_attn_kernel<<>>(attn, q_full, out16, T); +void gate_attn(const float* attn, const float* q_full, uint16_t* out16, int64_t T, void* stream, int64_t ld16) { + gate_attn_kernel<<>>(attn, q_full, out16, T, + ld16 > 0 ? ld16 : 24 * 256); check("gate_attn"); } diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 8af57352..7c2cf5a8 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -180,6 +180,17 @@ inline bool hc_upmix() { return v; } inline bool bf16x2_hc() { return bf16x2_mode() == 1; } +// S23 (opt-in STRATA_PF_PAD=1 with STRATA_PF_GEMM=1): the FP16 activations of the two K 6144 projections (ssm_out's +// y_h, attn_output's attn_h) with row stride 6144 + 64, so the GEMM's rows do not camp on the memory channels (the +// 4 KB-multiple stride; Gemm::native pads the weight the same way). Same bits. +inline bool pf_pad() { + static const bool v = [] { + const char* p = std::getenv("STRATA_PF_PAD"); const char* g = std::getenv("STRATA_PF_GEMM"); + return p && p[0] == '1' && g && g[0] == '1'; + }(); + return v; +} +constexpr int64_t ZV_PAD = 64; // F-1: STRATA_GR_UNFUSED=1 keeps the FP32 copy of the normalized rows (gr_norm + gr_mix), the A/B arm inline bool gr_unfused() { @@ -507,14 +518,16 @@ constexpr size_t GEMM_WS = 32u << 20; // cuBLAS workspace uint64_t gdn_set_bytes(size_t T) { Alloc a; a.count_only = true; bool ok = true; a.take(T * C, ok); a.take(T * ZV, ok); a.take(T * 2 * HV, ok); a.take(T * HV, ok); - a.take(T * HV, ok); a.take(T * C, ok); a.take(T * ZV, ok); a.take(T * ZV, ok); + a.take(T * HV, ok); a.take(T * C, ok); a.take(T * ZV, ok); + a.take(T * (ZV + (pf_pad() ? ZV_PAD : 0)), ok); return a.used; } uint64_t qsa_set_bytes(size_t T, int64_t cap, int64_t max_blocks, int64_t sel_batch, int64_t attn_batch, const strata::kernels::QsaShapes& s) { Alloc a; a.count_only = true; bool ok = true; a.take(T * 512, ok); a.take(T * 512, ok); a.take(T * 12288, ok); a.take(T * ZV, ok); - a.take(T * 128, ok); a.take(T * 512, ok); a.take(T * ZV, ok); a.take(T * ZV, ok); + a.take(T * 128, ok); a.take(T * 512, ok); a.take(T * ZV, ok); + a.take(T * (ZV + (pf_pad() ? ZV_PAD : 0)), ok); a.take(T * (size_t) cap, ok); a.take((size_t) sel_batch * (size_t) max_blocks, ok); a.take((size_t) attn_batch * strata::kernels::qsa_decode_attn_scratch_floats(cap, s), ok); @@ -744,12 +757,12 @@ bool Prefill::carve(size_t T, void* alloc) { a.base = base; a.cap = region; a.owned = &m.owned; m.qkv = a.take(T * C, ok); m.z = a.take(T * ZV, ok); m.ab = a.take(T * 2 * HV, ok); m.gate = a.take(T * HV, ok); m.beta = a.take(T * HV, ok); m.hbuf = a.take(T * C, ok); - m.y = a.take(T * ZV, ok); m.y_h = a.take(T * ZV, ok); + m.y = a.take(T * ZV, ok); m.y_h = a.take(T * (ZV + (pf_pad() ? ZV_PAD : 0)), ok); Alloc b; b.base = base; b.cap = region; b.owned = &m.owned; m.Kc = b.take(T * 512, ok); m.Vc = b.take(T * 512, ok); m.Qf = b.take(T * 12288, ok); m.q = b.take(T * ZV, ok); m.idx_raw = b.take(T * 128, ok); m.q_idx = b.take(T * 512, ok); - m.attn = b.take(T * ZV, ok); m.attn_h = b.take(T * ZV, ok); + m.attn = b.take(T * ZV, ok); m.attn_h = b.take(T * (ZV + (pf_pad() ? ZV_PAD : 0)), ok); m.sel_ids = b.take(T * (size_t) m.cap, ok); m.sel_scores = b.take((size_t) m.sel_batch * (size_t) m.max_blocks, ok); m.attn_scratch = b.take((size_t) m.attn_batch * strata::kernels::qsa_decode_attn_scratch_floats(m.cap, s), ok); @@ -1020,9 +1033,9 @@ const core::WeightRef* need(const core::LayerView& v, const char* suffix, std::s return r; } bool native_proj(Gemm& gm, const core::WeightRef* w, const uint16_t* X, float* Y, int64_t T, const std::string& name, - std::string& err, int64_t ldy = 0) { + std::string& err, int64_t ldy = 0, int64_t ldx = 0) { if (!w->native_data) { err = "prefill: " + name + " has no native GGUF blocks (run with --native)"; return false; } - gm.native(X, w->native_type, w->native_data, Y, T, w->ne1, w->ne0, ldy); + gm.native(X, w->native_type, w->native_data, Y, T, w->ne1, w->ne0, ldy, 0.0f, ldx); return true; } bool bf16_proj(Gemm& gm, const core::WeightRef* w, const uint16_t* X, float* Y, int64_t T, const std::string& name, @@ -1480,9 +1493,11 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e gdn_gates(m.ab, (const float*) wdt->data, (const float*) wsa->data, m.gate, m.beta, T, m.cs); gdn_conv(conv, m.qkv, (const float*) wc->data, m.hbuf, T, EPS, m.cs); pt.mark(kPfGdnRec, cs); - gdn_recurrence(state, m.hbuf, m.gate, m.beta, m.z, (const float*) wnm->data, EPS, m.y, m.y_h, T, m.cs); + const int64_t ld_y = pf_pad() && T >= std::max(pf_switch_min_t(), 64) ? ZV + ZV_PAD : 0; + gdn_recurrence(state, m.hbuf, m.gate, m.beta, m.z, (const float*) wnm->data, EPS, m.y, m.y_h, T, m.cs, + ld_y); pt.mark(kPfGdnOut, cs); - if (!native_proj(m.gemm, wo, m.y_h, m.bo, T, v.name("ssm_out.weight"), err)) return false; + if (!native_proj(m.gemm, wo, m.y_h, m.bo, T, v.name("ssm_out.weight"), err, 0, ld_y)) return false; ++gdn_index; } else if (half == 0) { // ======================= QSA ======================= @@ -1679,8 +1694,9 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e } if (st.kv_rot || st.kv_hybrid) 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); - if (!native_proj(m.gemm, wo, m.attn_h, m.bo, T, v.name("attn_output.weight"), err)) return false; + const int64_t ld_a = pf_pad() && T >= std::max(pf_switch_min_t(), 64) ? ZV + ZV_PAD : 0; + gate_attn(m.attn, m.Qf, m.attn_h, T, m.cs, ld_a); + if (!native_proj(m.gemm, wo, m.attn_h, m.bo, T, v.name("attn_output.weight"), err, 0, ld_a)) return false; ++qsa_index; } else { // ======================= MoE ======================= diff --git a/src/prefill/wmma_gemm.cu b/src/prefill/wmma_gemm.cu index cd379636..12579dcf 100644 --- a/src/prefill/wmma_gemm.cu +++ b/src/prefill/wmma_gemm.cu @@ -300,7 +300,8 @@ __device__ __forceinline__ h16 frag(const _Float16* p) { } template __global__ void __launch_bounds__(256) kernel(const _Float16* __restrict__ X, const _Float16* __restrict__ W, - float* __restrict__ Y, int M, int N, int K, int ldy, int accumulate) { + float* __restrict__ Y, int M, int N, int K, int ldy, int accumulate, + int ldx, int ldw) { #if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__) constexpr int TN = WN / 16, NB = BN / 64; __shared__ __align__(16) _Float16 sA[2][BM][LDK]; @@ -312,10 +313,10 @@ __global__ void __launch_bounds__(256) kernel(const _Float16* __restrict__ X, co const int m0 = (first_m + (b % (GM * num_n)) % gsize) * BM, n0 = ((b % (GM * num_n)) / gsize) * BN; const int sr = tid >> 2, sq = tid & 3; auto ldA = [&](int k0, int r) -> uint4 { - return *reinterpret_cast(X + (size_t) min(m0 + r, M - 1) * K + k0 + 8 * sq); + return *reinterpret_cast(X + (size_t) min(m0 + r, M - 1) * ldx + k0 + 8 * sq); }; auto ldB = [&](int k0, int r) -> uint4 { - return *reinterpret_cast(W + (size_t) min(n0 + r, N - 1) * K + k0 + 8 * sq); + return *reinterpret_cast(W + (size_t) min(n0 + r, N - 1) * ldw + k0 + 8 * sq); }; f8 acc[4][TN]; for (int i = 0; i < 4; ++i) for (int j = 0; j < TN; ++j) acc[i][j] = f8{0, 0, 0, 0, 0, 0, 0, 0}; @@ -374,9 +375,15 @@ __global__ void __launch_bounds__(256) kernel(const _Float16* __restrict__ X, co bool strata_pf_gemm_f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy, float beta, void* stream) { + return strata_pf_gemm_f16_ld(X, K, W, K, Y, T, N, K, ldy, beta, stream); +} + +bool strata_pf_gemm_f16_ld(const uint16_t* X, int64_t ldx, const uint16_t* W, int64_t ldw, float* Y, int64_t T, + int64_t N, int64_t K, int64_t ldy, float beta, void* stream) { if (!X || !W || !Y || T < 64 || N < 512 || K % pfg::BK != 0 || K < pfg::BK) return false; if (beta != 0.0f && beta != 1.0f) return false; if (ldy <= 0) ldy = N; + if (ldx < K || ldw < K || ldx % 8 != 0 || ldw % 8 != 0 || ldx > (1LL << 30) || ldw > (1LL << 30)) return false; if (ldy < N || T > (1LL << 30) || N > (1LL << 30) || K > (1LL << 30)) return false; static const bool gfx11 = [] { int dev = 0; @@ -391,11 +398,11 @@ bool strata_pf_gemm_f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t if (N >= 1024) { const unsigned grid = (unsigned) (mt * ((N + 255) / 256)); pfg::kernel<256, 64><<>>((const _Float16*) X, (const _Float16*) W, Y, (int) T, (int) N, (int) K, - (int) ldy, acc); + (int) ldy, acc, (int) ldx, (int) ldw); } else { const unsigned grid = (unsigned) (mt * ((N + 127) / 128)); pfg::kernel<128, 32><<>>((const _Float16*) X, (const _Float16*) W, Y, (int) T, (int) N, (int) K, - (int) ldy, acc); + (int) ldy, acc, (int) ldx, (int) ldw); } return hipGetLastError() == hipSuccess; } @@ -405,6 +412,10 @@ bool strata_pf_gemm_f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t bool strata_pf_gemm_f16(const uint16_t*, const uint16_t*, float*, int64_t, int64_t, int64_t, int64_t, float, void*) { return false; } +bool strata_pf_gemm_f16_ld(const uint16_t*, int64_t, const uint16_t*, int64_t, float*, int64_t, int64_t, int64_t, + int64_t, float, void*) { + return false; +} bool strata_wmma_gemm_f16(const uint16_t*, const uint16_t*, float*, int64_t, int64_t, int64_t, int64_t, float, void*) { diff --git a/src/prefill/wmma_gemm.h b/src/prefill/wmma_gemm.h index 1a5085ca..f8e56c91 100644 --- a/src/prefill/wmma_gemm.h +++ b/src/prefill/wmma_gemm.h @@ -21,6 +21,10 @@ bool strata_wmma_gemm_f16(const uint16_t* X, const uint16_t* W, float* Y, /// T >= 64, N >= 512; the 128 x 256 / 128 x 128 grouped-order WMMA kernel. False (nothing launched) otherwise / off gfx11. bool strata_pf_gemm_f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy, float beta, void* stream = nullptr); +/// The same with row strides ldx >= K and ldw >= K (multiples of 8): a 4 KB-multiple row stride (K 2048 / 4096 / +/// 6144) camps on the memory channels, K + 64 does not (S23 gemm_probe7/8: K 6144 19 -> 35 TFLOPS). +bool strata_pf_gemm_f16_ld(const uint16_t* X, int64_t ldx, const uint16_t* W, int64_t ldw, float* Y, int64_t T, + int64_t N, int64_t K, int64_t ldy, float beta, void* stream = nullptr); bool strata_wmma_gemm_bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy, float beta, From 20f471be73654a575442e5addfb660d6a55345a4 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 4 Oct 2026 03:55:08 +0200 Subject: [PATCH 41/55] prefill: the STRATA_PF_GEMM 128 x 256 kernel with a 64-k LDS tile, bitwise (STRATA_PF_BK64=0 keeps BK 32) With global loads removed, the BK 32 double-buffered kernel still stopped at 37-39 TFLOPS of the ~50 WMMA peak: the K loop itself (fragment reads, one barrier per 32 k) was the limiter. pfg::kernel_bk64 stages a 64-k tile in one LDS buffer (55 KB) from 12 named registers with 2 barriers per tile, half the loop trips. Every accumulator takes the same WMMAs in the same k order: the same bits (s23/gemm_probe11.hip, memcmp vs the BK 32 code). gfx1151, M 16384, both operands padded (2 runs): N 2560 K 6144 38.0 -> 41.3 TFLOPS, N 12288 K 2560 38.9 -> 40.9, N 10240 K 2560 40.3 -> 40.4. Also probed and rejected (same bits, slower): A rows read under the previous row's WMMAs (36.7-37.9; 8-16 B spills), half-wave 16 B reads + v_permlanex16 (31.7-32.4), both (32.8-33.5). Used for N >= 1024 and K % 64 == 0. c-best3 v3 on Aurora, BK 32 -> BK 64, interleaved, same ids: prompt 8K 959.8 / 947.8 -> 968.0 / 1001.9, 64K 1007.9 / 1004.0 -> 1028.0 / 1025.4 tok/s. --- src/prefill/wmma_gemm.cu | 96 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 95 insertions(+), 1 deletion(-) diff --git a/src/prefill/wmma_gemm.cu b/src/prefill/wmma_gemm.cu index 12579dcf..e029f47c 100644 --- a/src/prefill/wmma_gemm.cu +++ b/src/prefill/wmma_gemm.cu @@ -22,6 +22,7 @@ #include #include +#include #include // STRATA_WMMA_GFX11 is defined by the BUILD (CMakeLists.txt, from CMAKE_HIP_ARCHITECTURES), not inferred @@ -371,6 +372,93 @@ __global__ void __launch_bounds__(256) kernel(const _Float16* __restrict__ X, co } #endif } +// The 128 x 256 kernel with a 64-k LDS tile (single buffer, the next tile in 12 named staging registers, 2 barriers +// per tile: half the loop trips and barriers per k of the BK 32 double buffer). Each accumulator takes the same +// WMMAs in the same k order as `kernel`: the same bits (s23/gemm_probe11.hip, memcmp). gfx1151, M 16384, both +// operands padded: 38.0 -> 41.3 TFLOPS (N 2560 K 6144), 38.9 -> 40.9 (N 12288 K 2560), 40.3 -> 40.4 (N 10240). +// K a multiple of 64. +__global__ void __launch_bounds__(256) kernel_bk64(const _Float16* __restrict__ X, const _Float16* __restrict__ W, + float* __restrict__ Y, int M, int N, int K, int ldy, int accumulate, + int ldx, int ldw) { +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__) + constexpr int BN = 256, WN = 64, BK64 = 64, LDK64 = BK64 + 8; + __shared__ __align__(16) _Float16 sA[BM][LDK64]; + __shared__ __align__(16) _Float16 sB[BN][LDK64]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, l16 = lane & 15, hi = lane >> 4; + const int wm = wave & 1, wn = wave >> 1; + const int num_m = (M + BM - 1) / BM, num_n = (N + BN - 1) / BN, b = blockIdx.x; + const int group = b / (GM * num_n), first_m = group * GM, gsize = min(GM, num_m - first_m); + const int m0 = (first_m + (b % (GM * num_n)) % gsize) * BM, n0 = ((b % (GM * num_n)) / gsize) * BN; + const int sr = tid >> 3, sq = tid & 7; // 32 rows per pass, 8 x 8 halves per row + auto ldA = [&](int k0, int r) -> uint4 { + return *reinterpret_cast(X + (size_t) min(m0 + r, M - 1) * ldx + k0 + 8 * sq); + }; + auto ldB = [&](int k0, int r) -> uint4 { + return *reinterpret_cast(W + (size_t) min(n0 + r, N - 1) * ldw + k0 + 8 * sq); + }; + uint4 ra0, ra1, ra2, ra3, rb0, rb1, rb2, rb3, rb4, rb5, rb6, rb7; + auto load = [&](int k0) { + ra0 = ldA(k0, sr); ra1 = ldA(k0, sr + 32); ra2 = ldA(k0, sr + 64); ra3 = ldA(k0, sr + 96); + rb0 = ldB(k0, sr); rb1 = ldB(k0, sr + 32); rb2 = ldB(k0, sr + 64); rb3 = ldB(k0, sr + 96); + rb4 = ldB(k0, sr + 128); rb5 = ldB(k0, sr + 160); rb6 = ldB(k0, sr + 192); rb7 = ldB(k0, sr + 224); + }; + auto store = [&]() { + *reinterpret_cast(&sA[sr][8 * sq]) = ra0; *reinterpret_cast(&sA[sr + 32][8 * sq]) = ra1; + *reinterpret_cast(&sA[sr + 64][8 * sq]) = ra2; *reinterpret_cast(&sA[sr + 96][8 * sq]) = ra3; + *reinterpret_cast(&sB[sr][8 * sq]) = rb0; *reinterpret_cast(&sB[sr + 32][8 * sq]) = rb1; + *reinterpret_cast(&sB[sr + 64][8 * sq]) = rb2; *reinterpret_cast(&sB[sr + 96][8 * sq]) = rb3; + *reinterpret_cast(&sB[sr + 128][8 * sq]) = rb4; *reinterpret_cast(&sB[sr + 160][8 * sq]) = rb5; + *reinterpret_cast(&sB[sr + 192][8 * sq]) = rb6; *reinterpret_cast(&sB[sr + 224][8 * sq]) = rb7; + }; + f8 acc[4][4]; +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int j = 0; j < 4; ++j) acc[i][j] = f8{0, 0, 0, 0, 0, 0, 0, 0}; + load(0); + store(); + __syncthreads(); + const int ar = 64 * wm + l16, br = WN * wn + l16; + for (int k0 = 0; k0 < K; k0 += BK64) { + const bool more = k0 + BK64 < K; + if (more) load(k0 + BK64); +#pragma unroll + for (int ks = 0; ks < BK64; ks += 16) { + const h16 a0 = frag(&sA[ar][ks]), a1 = frag(&sA[ar + 16][ks]), a2 = frag(&sA[ar + 32][ks]), + a3 = frag(&sA[ar + 48][ks]); + const h16 b0 = frag(&sB[br][ks]), b1 = frag(&sB[br + 16][ks]), b2 = frag(&sB[br + 32][ks]), + b3 = frag(&sB[br + 48][ks]); +#define PFG_ROW(i, a) \ + acc[i][0] = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b0, acc[i][0]); \ + acc[i][1] = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b1, acc[i][1]); \ + acc[i][2] = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b2, acc[i][2]); \ + acc[i][3] = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b3, acc[i][3]); + PFG_ROW(0, a0) PFG_ROW(1, a1) PFG_ROW(2, a2) PFG_ROW(3, a3) +#undef PFG_ROW + } + if (more) { + __syncthreads(); // every wave is done reading the tile + store(); + __syncthreads(); + } + } +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int n = n0 + WN * wn + 16 * j + l16; + if (n >= N) continue; +#pragma unroll + for (int e = 0; e < 8; ++e) { + const int m = m0 + 64 * wm + 16 * i + 2 * e + hi; + if (m < M) { + float* y = Y + (size_t) m * ldy + n; + *y = accumulate ? *y + acc[i][j][e] : acc[i][j][e]; + } + } + } +#endif +} } // namespace pfg bool strata_pf_gemm_f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy, @@ -395,7 +483,13 @@ bool strata_pf_gemm_f16_ld(const uint16_t* X, int64_t ldx, const uint16_t* W, in hipStream_t s = static_cast(stream); const int acc = beta == 1.0f ? 1 : 0; const int64_t mt = (T + pfg::BM - 1) / pfg::BM; - if (N >= 1024) { + // STRATA_PF_BK64=0: the BK 32 kernel for the wide shapes too (the A/B; the same bits) + static const bool bk64 = [] { const char* v = std::getenv("STRATA_PF_BK64"); return !v || v[0] != '0'; }(); + if (N >= 1024 && bk64 && K % 64 == 0) { + const unsigned grid = (unsigned) (mt * ((N + 255) / 256)); + pfg::kernel_bk64<<>>((const _Float16*) X, (const _Float16*) W, Y, (int) T, (int) N, (int) K, + (int) ldy, acc, (int) ldx, (int) ldw); + } else if (N >= 1024) { const unsigned grid = (unsigned) (mt * ((N + 255) / 256)); pfg::kernel<256, 64><<>>((const _Float16*) X, (const _Float16*) W, Y, (int) T, (int) N, (int) K, (int) ldy, acc, (int) ldx, (int) ldw); From 6448f0f7ad633ced78505f8bf170daeddf51791f Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 4 Oct 2026 04:50:20 +0200 Subject: [PATCH 42/55] prefill: STRATA_CVEC_FUSE=1 - a steered layer's write, control vector and next norm in one pass over R, bitwise With the speed-projection control vector on, every steered layer's FFN write-back took three passes over the T x 10240 FP32 residual (gr_write, cvec_apply, the next half's gr_norm_rs) instead of the one gr_write_norm_rs of the other layers. gr_write_cvec_norm_rs does the three in one: gr_write's arithmetic, cvec_kernel's dot order and two-level reduction, gr_norm_rs's sum order and block_sum - the same bits. STRATA_CVEC_FUSE_CHECK=N runs the three-kernel path on a copy of R on the first N fused writes and compares R, the row scales and the BF16 image (Aurora, 8K prompt, layers 4-11: all identical). cvec_tables() hands out the current device's vector tables. c-best3 v3.1 on Aurora, one 64K prompt with STRATA_PREFILL_TIMING (x2): hc read + combine 13.0 / 13.1 -> 10.8 / 11.2 s, GPU timeline 64.6 / 64.9 -> 60.6 / 63.0 s; benches interleaved, same ids: 8K prompt 971.5 / 1019.9 -> 998.8 / 1045.1, 64K 1025.3 / 1012.8 -> 1039.2 / 1014.4 tok/s. --- include/strata/kernels/cvec.hpp | 4 ++ include/strata/prefill/kernels.hpp | 6 +++ src/kernels/cuda/cvec.cu | 8 ++++ src/prefill/kernels.cu | 69 ++++++++++++++++++++++++++++++ src/prefill/prefill.cpp | 56 ++++++++++++++++++++++-- 5 files changed, 139 insertions(+), 4 deletions(-) diff --git a/include/strata/kernels/cvec.hpp b/include/strata/kernels/cvec.hpp index a447eb52..c9347483 100644 --- a/include/strata/kernels/cvec.hpp +++ b/include/strata/kernels/cvec.hpp @@ -52,6 +52,10 @@ bool cvec_replicate(std::string& err); void cvec_set_enabled(bool on); bool cvec_enabled(); +/// The CURRENT device's tables (dir n_layers x n_embd, s n_layers, the request flag), for a caller that applies the +/// vector inside its own kernel (the prompt path's STRATA_CVEC_FUSE). False without a vector on this device. +bool cvec_tables(const float** dir, const float** s, const int** on); + /// Layer `layer`'s vector on T tokens' residual stacks (`R + t * r_ld`, hc streams of n_embd). With `write`, the /// pending FFN write `R += bo * 2 sigmoid(inj / hc)` (the fused read's arithmetic) is applied first, for callers /// whose writes are folded into the next layer's read; without it, R must already hold the layer's output. diff --git a/include/strata/prefill/kernels.hpp b/include/strata/prefill/kernels.hpp index 5c5fe1b6..8ce3f8ed 100644 --- a/include/strata/prefill/kernels.hpp +++ b/include/strata/prefill/kernels.hpp @@ -31,6 +31,12 @@ bool gr_upmix(const uint16_t* lo16, const uint16_t* w_up, const float* R, const float* mixed, uint16_t* mixed16, uint16_t* mixed_h, int64_t T, void* stream); void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* w_norm_next, float eps, float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo = nullptr); +/// S23 (STRATA_CVEC_FUSE=1): gr_write, then the control vector (v_l = layer l's direction row, *s_l its scale, +/// *on the request flag, mode 0 project / 1 add; cvec_kernel's arithmetic), then gr_norm_rs with the next half's +/// norm - one pass over R, the same bits as the three kernels. +void gr_write_cvec_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* v_l, + const float* s_l, const int* on, int mode, const float* w_norm_next, float eps, float* rs, + uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo = nullptr); /// lo16[t, k] = bf16(silu(lo[t, k] / hc)) void gr_silu(const float* lo, uint16_t* lo16, int64_t T, void* stream, uint16_t* lo16_lo = nullptr); /// mixed[t, d] = mean_c xn[t, c, d] * sigmoid(gated[t, c, d]); FP32, BF16 and FP16 (either image may be null). diff --git a/src/kernels/cuda/cvec.cu b/src/kernels/cuda/cvec.cu index 66829324..3f5fe764 100644 --- a/src/kernels/cuda/cvec.cu +++ b/src/kernels/cuda/cvec.cu @@ -151,6 +151,14 @@ void cvec_set_enabled(bool on) { bool cvec_enabled() { return g_cvec.loaded() && g_on_host; } +bool cvec_tables(const float** dir, const float** s, const int** on) { + if (!g_cvec.loaded()) return false; + const DevTables& t = g_dev[cur_device()]; + if (t.dir == nullptr) return false; + *dir = t.dir; *s = t.s; *on = t.on; + return true; +} + void cvec_apply(float* R, int64_t layer, int64_t T, int64_t r_ld, const float* bo, int64_t bo_ld, const float* inj, int64_t inj_ld, bool write, void* stream) { if (!g_cvec.loaded() || T < 1) return; diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 450747d1..1a09cd6f 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -159,6 +159,68 @@ __global__ void __launch_bounds__(256) gr_write_norm_rs_kernel(float* __restrict if (xn16_lo) xn16_lo[row * N + d] = bf_lo(x, h); } } +// S23 (opt-in STRATA_CVEC_FUSE=1): a steered layer's FFN write, its control vector and the next half's norm in one +// pass over R (was gr_write + cvec_apply + gr_norm_rs: three). The write is gr_write_kernel's, the vector +// cvec_kernel's (the same per-thread dot order over d = tid + 256 k, the same two-level xor reduction), the norm +// gr_norm_rs_kernel's (the same ss order and block_sum): the same bits. +__global__ void __launch_bounds__(256) gr_write_cvec_norm_rs_kernel( + float* __restrict__ R, const float* __restrict__ bo, const float* __restrict__ inj, int64_t inj_ld, + const float* __restrict__ v_l, const float* __restrict__ s_l, const int* __restrict__ on, int mode, + const float* __restrict__ w, float eps, float* __restrict__ rs_out, uint16_t* __restrict__ xn16, + uint16_t* __restrict__ xn16_lo) { + __shared__ float sh[32]; + __shared__ float part[8]; + const int64_t row = blockIdx.x; // t * 4 + c + const int64_t t = row / HC; + const int c = (int) (row % HC); + float* r = R + row * N; + const float sc = 2.0f * sigm(inj[t * inj_ld + c] / (float) HC); + const float s = *s_l; + const bool steer = *on != 0 && s != 0.0f; + float x[GRW_PER]; + float dot = 0.0f; + int k = 0; +#pragma unroll + for (int d = threadIdx.x; d < N; d += 256, ++k) { + const float xv = fmaf(bo[t * N + d], sc, r[d]); + x[k] = xv; + if (steer && mode == 0) dot = fmaf(xv, v_l[d], dot); + } + if (steer && mode == 0) { +#pragma unroll + for (int o = 16; o > 0; o >>= 1) dot += __shfl_xor_sync(0xffffffffu, dot, o); + if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = dot; + __syncthreads(); + if (threadIdx.x < 32) { + float p = threadIdx.x < 8 ? part[threadIdx.x] : 0.0f; +#pragma unroll + for (int o = 16; o > 0; o >>= 1) p += __shfl_xor_sync(0xffffffffu, p, o); + if (threadIdx.x == 0) part[0] = p; + } + __syncthreads(); + dot = part[0] * s; + } + float ss = 0.0f; + k = 0; +#pragma unroll + for (int d = threadIdx.x; d < N; d += 256, ++k) { + float xv = x[k]; + if (steer) xv = mode == 0 ? fmaf(-dot, v_l[d], xv) : xv + v_l[d]; + r[d] = xv; + x[k] = xv; + ss += xv * xv; + } + const float rs = rsqrtf(block_sum(ss, sh) / (float) N + eps); + if (threadIdx.x == 0) rs_out[row] = rs; + k = 0; +#pragma unroll + for (int d = threadIdx.x; d < N; d += 256, ++k) { + const float y = x[k] * rs * w[c * N + d]; + const uint16_t h = bf(y); + xn16[row * N + d] = h; + if (xn16_lo) xn16_lo[row * N + d] = bf_lo(y, h); + } +} __global__ void gr_silu_kernel(const float* __restrict__ lo, uint16_t* __restrict__ lo16, uint16_t* __restrict__ lo16_lo, int64_t n) { const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; @@ -941,6 +1003,13 @@ void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_l rs, xn16, xn16_lo); check("gr_write_norm_rs"); } +void gr_write_cvec_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* v_l, + const float* s_l, const int* on, int mode, const float* w_norm_next, float eps, float* rs, + uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo) { + gr_write_cvec_norm_rs_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>( + R, bo, inj, inj_ld, v_l, s_l, on, mode, w_norm_next, eps, rs, xn16, xn16_lo); + check("gr_write_cvec_norm_rs"); +} void gr_silu(const float* lo, uint16_t* lo16, int64_t T, void* stream, uint16_t* lo16_lo) { gr_silu_kernel<<>>(lo, lo16, lo16_lo, T * LR); check("gr_silu"); diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 7c2cf5a8..67997d56 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -180,6 +180,12 @@ inline bool hc_upmix() { return v; } inline bool bf16x2_hc() { return bf16x2_mode() == 1; } +// S23 (opt-in STRATA_CVEC_FUSE=1): a steered layer's FFN write + control vector + the next half's norm in one pass +// over R (gr_write_cvec_norm_rs; bitwise the gr_write + cvec_apply + gr_norm_rs it replaces) +inline bool cvec_fuse() { + static const bool v = [] { const char* e = std::getenv("STRATA_CVEC_FUSE"); return e && e[0] == '1'; }(); + return v; +} // S23 (opt-in STRATA_PF_PAD=1 with STRATA_PF_GEMM=1): the FP16 activations of the two K 6144 projections (ssm_out's // y_h, attn_output's attn_h) with row stride 6144 + 64, so the GEMM's rows do not camp on the memory channels (the // 4 KB-multiple stride; Gemm::native pads the weight the same way). Same bits. @@ -2109,22 +2115,64 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e // touches R in between (not the stage's last half, not before the PLE block of layer 1, not under a // control vector) const int64_t nl = half == 0 ? l : l + 1; - const bool fuse = !gr_unfused() && nl < LE && !(half == 1 && nl == 1 && ple_on) && - !(half == 1 && strata::kernels::cvec().covers(l)); + const bool steered = half == 1 && strata::kernels::cvec().covers(l); + const float *cv_dir = nullptr, *cv_s = nullptr; + const int* cv_on = nullptr; + const bool cv_fused = steered && cvec_fuse() && !gr_unfused() && nl < LE && !(nl == 1 && ple_on) && + strata::kernels::cvec().n_embd == N && strata::kernels::cvec().hc == HC && + strata::kernels::cvec_tables(&cv_dir, &cv_s, &cv_on); + const bool fuse = !gr_unfused() && nl < LE && !(half == 1 && nl == 1 && ple_on) && (!steered || cv_fused); const core::WeightRef* wnn = nullptr; if (fuse) { const core::LayerView vn(*m.wt, nl); wnn = need(vn, half == 0 ? "hc_ffn_norm.weight" : "hc_attn_norm.weight", err); if (!wnn) return false; } - if (wnn) { + if (wnn && cv_fused) { + // STRATA_CVEC_FUSE_CHECK=N: on the first N fused writes, also run the three-kernel path on a copy + // of R and report whether R, the row scales and the BF16 image are bit-identical + static int checks = [] { const char* e = std::getenv("STRATA_CVEC_FUSE_CHECK"); return e ? std::atoi(e) : 0; }(); + if (checks > 0) { + --checks; + float *Rc = nullptr, *rc = nullptr; + uint16_t* xc = nullptr; + cudaMalloc(&Rc, (size_t) T * D * 4); cudaMalloc(&rc, (size_t) T * HC * 4); + cudaMalloc(&xc, (size_t) T * D * 2); + cudaMemcpyAsync(Rc, m.R, (size_t) T * D * 4, cudaMemcpyDeviceToDevice, m.cs); + gr_write(Rc, m.bo, m.inj, HC, T, m.cs); + strata::kernels::cvec_apply(Rc, l, T, D, nullptr, 0, nullptr, 0, false, m.cs); + gr_norm_rs(Rc, (const float*) wnn->data, EPS, rc, xc, T, m.cs); + gr_write_cvec_norm_rs(m.R, m.bo, m.inj, HC, cv_dir + l * N, cv_s + l, cv_on, + strata::kernels::cvec().mode, (const float*) wnn->data, EPS, m.grs, + m.xn16, T, m.cs, m.xn16_lo); + std::vector a((size_t) T * D), b((size_t) T * D), ra((size_t) T * HC), rb((size_t) T * HC); + std::vector xa((size_t) T * D), xb((size_t) T * D); + cudaMemcpyAsync(a.data(), m.R, a.size() * 4, cudaMemcpyDeviceToHost, m.cs); + cudaMemcpyAsync(b.data(), Rc, b.size() * 4, cudaMemcpyDeviceToHost, m.cs); + cudaMemcpyAsync(ra.data(), m.grs, ra.size() * 4, cudaMemcpyDeviceToHost, m.cs); + cudaMemcpyAsync(rb.data(), rc, rb.size() * 4, cudaMemcpyDeviceToHost, m.cs); + cudaMemcpyAsync(xa.data(), m.xn16, xa.size() * 2, cudaMemcpyDeviceToHost, m.cs); + cudaMemcpyAsync(xb.data(), xc, xb.size() * 2, cudaMemcpyDeviceToHost, m.cs); + cudaStreamSynchronize(m.cs); + cudaFree(Rc); cudaFree(rc); cudaFree(xc); + std::fprintf(stderr, "strata: STRATA_CVEC_FUSE_CHECK layer %lld T %lld: R %s, rs %s, xn16 %s\n", + (long long) l, (long long) T, + std::memcmp(a.data(), b.data(), a.size() * 4) ? "DIFFERS" : "identical", + std::memcmp(ra.data(), rb.data(), ra.size() * 4) ? "DIFFERS" : "identical", + std::memcmp(xa.data(), xb.data(), xa.size() * 2) ? "DIFFERS" : "identical"); + } else + gr_write_cvec_norm_rs(m.R, m.bo, m.inj, HC, cv_dir + l * N, cv_s + l, cv_on, + strata::kernels::cvec().mode, (const float*) wnn->data, EPS, m.grs, m.xn16, + T, m.cs, m.xn16_lo); + normed = true; + } else if (wnn) { gr_write_norm_rs(m.R, m.bo, m.inj, HC, (const float*) wnn->data, EPS, m.grs, m.xn16, T, m.cs, m.xn16_lo); normed = true; } else { gr_write(m.R, m.bo, m.inj, HC, T, m.cs); } - if (half == 1 && strata::kernels::cvec().covers(l)) // --control-vector-scaled + if (steered && !cv_fused) // --control-vector-scaled strata::kernels::cvec_apply(m.R, l, T, D, nullptr, 0, nullptr, 0, false, m.cs); } } From 5eecc5dee6c0b82b41ba2a3a22c3444ace91cf07 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 4 Oct 2026 06:17:29 +0200 Subject: [PATCH 43/55] prefill: STRATA_PF_HCDOWN=1 - the HC read's down and inject projections as one WMMA GEMM over a padded xn16 The hyper-connection read ran two hipBLASLt BF16 GEMMs over the same T x 10240 xn16: down (N 320, 6.78 ms per 16K-token half, 15.8 TFLOPS - the 4 KB-multiple row stride) and inject (N 4, 1.81 ms). strata_pf_hcdown_bf16 does both in one 128 x 128 BK-64 WMMA GEMM: weight rows [w_down; w_inject] read from the two tensors, the epilogue splitting lo (T x 320) and inj (T x 4), so xn16 is read once; with the flag, xn16 is written with token stride 10240 + 64 (gr_norm_rs / gr_write_norm_rs / gr_write_cvec_norm_rs take an ldx; unchanged and bitwise when off). s23/hcdown_probe.hip, 16K tokens: 3.60 / 3.77 ms for both (unpadded 5.75). Opt-in, on chunks of STRATA_PF_SWITCH_MIN_T+ tokens. FP32 accumulation in another k order than hipBLASLt: rounding-level. Aurora, c-best3 v3.2: 64K timing hc read 7234 / 7253 -> 6439 / 6175 ms; prompt 8K 1048 -> 1075 / 1036, 64K 1053 / 1056 -> 1067 / 1068 tok/s. Teacher-forced KL (8192-token prefix, 2001 positions) vs the default, next to the accepted MMQ-vs-fused pair: offset 0 0.162 (mmq 0.158), 30000 0.110 (0.126), 70000 0.031 (0.033); ledger {32,17,130}, 64K retrieval 3/3. --- include/strata/prefill/kernels.hpp | 7 +- src/prefill/kernels.cu | 34 +++++---- src/prefill/prefill.cpp | 42 ++++++++--- src/prefill/wmma_gemm.cu | 117 +++++++++++++++++++++++++++++ src/prefill/wmma_gemm.h | 5 ++ 5 files changed, 178 insertions(+), 27 deletions(-) diff --git a/include/strata/prefill/kernels.hpp b/include/strata/prefill/kernels.hpp index 8ce3f8ed..da22f98b 100644 --- a/include/strata/prefill/kernels.hpp +++ b/include/strata/prefill/kernels.hpp @@ -19,7 +19,7 @@ void gr_norm(const float* R, const float* w_norm, float eps, float* xn, uint16_t uint16_t* xn16_lo = nullptr); /// F-1: gr_norm without its FP32 output: the row scales rs[t*4 + c] and the BF16 image; gr_mix_r then reads R. void gr_norm_rs(const float* R, const float* w_norm, float eps, float* rs, uint16_t* xn16, int64_t T, void* stream, - uint16_t* xn16_lo = nullptr); + uint16_t* xn16_lo = nullptr, int64_t ldx = 0); // ldx: xn16's token stride (0 = 10240) /// gr_mix with xn recomputed from R, rs and w_norm exactly as gr_norm computes it (the same bits). void gr_mix_r(const float* R, const float* rs, const float* w_norm, const float* gated, float* mixed, uint16_t* mixed16, int64_t T, void* stream, uint16_t* mixed_h = nullptr, uint16_t* mixed16_lo = nullptr); @@ -30,13 +30,14 @@ void gr_mix_r(const float* R, const float* rs, const float* w_norm, const float* bool gr_upmix(const uint16_t* lo16, const uint16_t* w_up, const float* R, const float* rs, const float* w_norm, float* mixed, uint16_t* mixed16, uint16_t* mixed_h, int64_t T, void* stream); void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* w_norm_next, float eps, - float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo = nullptr); + float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo = nullptr, + int64_t ldx = 0); /// S23 (STRATA_CVEC_FUSE=1): gr_write, then the control vector (v_l = layer l's direction row, *s_l its scale, /// *on the request flag, mode 0 project / 1 add; cvec_kernel's arithmetic), then gr_norm_rs with the next half's /// norm - one pass over R, the same bits as the three kernels. void gr_write_cvec_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* v_l, const float* s_l, const int* on, int mode, const float* w_norm_next, float eps, float* rs, - uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo = nullptr); + uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo = nullptr, int64_t ldx = 0); /// lo16[t, k] = bf16(silu(lo[t, k] / hc)) void gr_silu(const float* lo, uint16_t* lo16, int64_t T, void* stream, uint16_t* lo16_lo = nullptr); /// mixed[t, d] = mean_c xn[t, c, d] * sigmoid(gated[t, c, d]); FP32, BF16 and FP16 (either image may be null). diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 1a09cd6f..6ee42ef3 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -85,11 +85,12 @@ __global__ void gr_norm_kernel(const float* __restrict__ R, const float* __restr // so the FP32 copy of the normalized rows (T x 10240 floats) is neither written nor read __global__ void gr_norm_rs_kernel(const float* __restrict__ R, const float* __restrict__ w, float eps, float* __restrict__ rs_out, uint16_t* __restrict__ xn16, - uint16_t* __restrict__ xn16_lo) { + uint16_t* __restrict__ xn16_lo, int64_t ldx) { __shared__ float sh[32]; const int64_t row = blockIdx.x; // t * 4 + c const int c = (int) (row % HC); const float* r = R + row * N; + const int64_t xo = (row / HC) * ldx + (int64_t) c * N; // the BF16 image's row (token stride ldx) float ss = 0.0f; for (int d = threadIdx.x; d < N; d += blockDim.x) ss += r[d] * r[d]; const float rs = rsqrtf(block_sum(ss, sh) / (float) N + eps); @@ -97,8 +98,8 @@ __global__ void gr_norm_rs_kernel(const float* __restrict__ R, const float* __re for (int d = threadIdx.x; d < N; d += blockDim.x) { const float v = r[d] * rs * w[c * N + d]; const uint16_t h = bf(v); - xn16[row * N + d] = h; - if (xn16_lo) xn16_lo[row * N + d] = bf_lo(v, h); + xn16[xo + d] = h; + if (xn16_lo) xn16_lo[xo + d] = bf_lo(v, h); } } __global__ void gr_mix_r_kernel(const float* __restrict__ R, const float* __restrict__ rs, const float* __restrict__ w, @@ -131,12 +132,13 @@ __global__ void __launch_bounds__(256) gr_write_norm_rs_kernel(float* __restrict const float* __restrict__ inj, int64_t inj_ld, const float* __restrict__ w, float eps, float* __restrict__ rs_out, uint16_t* __restrict__ xn16, - uint16_t* __restrict__ xn16_lo) { + uint16_t* __restrict__ xn16_lo, int64_t ldx) { __shared__ float sh[32]; const int64_t row = blockIdx.x; // t * 4 + c const int64_t t = row / HC; const int c = (int) (row % HC); float* r = R + row * N; + const int64_t xo = t * ldx + (int64_t) c * N; const float sc = 2.0f * sigm(inj[t * inj_ld + c] / (float) HC); float v[GRW_PER]; float ss = 0.0f; @@ -155,8 +157,8 @@ __global__ void __launch_bounds__(256) gr_write_norm_rs_kernel(float* __restrict for (int d = threadIdx.x; d < N; d += 256, ++k) { const float x = v[k] * rs * w[c * N + d]; const uint16_t h = bf(x); - xn16[row * N + d] = h; - if (xn16_lo) xn16_lo[row * N + d] = bf_lo(x, h); + xn16[xo + d] = h; + if (xn16_lo) xn16_lo[xo + d] = bf_lo(x, h); } } // S23 (opt-in STRATA_CVEC_FUSE=1): a steered layer's FFN write, its control vector and the next half's norm in one @@ -167,7 +169,7 @@ __global__ void __launch_bounds__(256) gr_write_cvec_norm_rs_kernel( float* __restrict__ R, const float* __restrict__ bo, const float* __restrict__ inj, int64_t inj_ld, const float* __restrict__ v_l, const float* __restrict__ s_l, const int* __restrict__ on, int mode, const float* __restrict__ w, float eps, float* __restrict__ rs_out, uint16_t* __restrict__ xn16, - uint16_t* __restrict__ xn16_lo) { + uint16_t* __restrict__ xn16_lo, int64_t ldx) { __shared__ float sh[32]; __shared__ float part[8]; const int64_t row = blockIdx.x; // t * 4 + c @@ -217,8 +219,8 @@ __global__ void __launch_bounds__(256) gr_write_cvec_norm_rs_kernel( for (int d = threadIdx.x; d < N; d += 256, ++k) { const float y = x[k] * rs * w[c * N + d]; const uint16_t h = bf(y); - xn16[row * N + d] = h; - if (xn16_lo) xn16_lo[row * N + d] = bf_lo(y, h); + xn16[t * ldx + (int64_t) c * N + d] = h; + if (xn16_lo) xn16_lo[t * ldx + (int64_t) c * N + d] = bf_lo(y, h); } } __global__ void gr_silu_kernel(const float* __restrict__ lo, uint16_t* __restrict__ lo16, uint16_t* __restrict__ lo16_lo, @@ -967,8 +969,9 @@ void gr_norm(const float* R, const float* w_norm, float eps, float* xn, uint16_t check("gr_norm"); } void gr_norm_rs(const float* R, const float* w_norm, float eps, float* rs, uint16_t* xn16, int64_t T, void* stream, - uint16_t* xn16_lo) { - gr_norm_rs_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, w_norm, eps, rs, xn16, xn16_lo); + uint16_t* xn16_lo, int64_t ldx) { + gr_norm_rs_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, w_norm, eps, rs, xn16, xn16_lo, + ldx > 0 ? ldx : D); check("gr_norm_rs"); } void gr_mix_r(const float* R, const float* rs, const float* w_norm, const float* gated, float* mixed, uint16_t* mixed16, @@ -998,16 +1001,17 @@ bool gr_upmix(const uint16_t* lo16, const uint16_t* w_up, const float* R, const #endif } void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* w_norm_next, float eps, - float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo) { + float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo, int64_t ldx) { gr_write_norm_rs_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, bo, inj, inj_ld, w_norm_next, eps, - rs, xn16, xn16_lo); + rs, xn16, xn16_lo, + ldx > 0 ? ldx : D); check("gr_write_norm_rs"); } void gr_write_cvec_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* v_l, const float* s_l, const int* on, int mode, const float* w_norm_next, float eps, float* rs, - uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo) { + uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo, int64_t ldx) { gr_write_cvec_norm_rs_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>( - R, bo, inj, inj_ld, v_l, s_l, on, mode, w_norm_next, eps, rs, xn16, xn16_lo); + R, bo, inj, inj_ld, v_l, s_l, on, mode, w_norm_next, eps, rs, xn16, xn16_lo, ldx > 0 ? ldx : D); check("gr_write_cvec_norm_rs"); } void gr_silu(const float* lo, uint16_t* lo16, int64_t T, void* stream, uint16_t* lo16_lo) { diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 67997d56..26a860a5 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -1,6 +1,7 @@ // src/prefill/prefill.cpp - see include/strata/prefill/prefill.hpp. #include "strata/prefill/prefill.hpp" #include "mmq_resident_sort.hpp" +#include "wmma_gemm.h" #include "strata/core/mtp.hpp" #include "strata/core/progress.hpp" #include "strata/core/on_device.hpp" @@ -182,6 +183,14 @@ inline bool hc_upmix() { inline bool bf16x2_hc() { return bf16x2_mode() == 1; } // S23 (opt-in STRATA_CVEC_FUSE=1): a steered layer's FFN write + control vector + the next half's norm in one pass // over R (gr_write_cvec_norm_rs; bitwise the gr_write + cvec_apply + gr_norm_rs it replaces) +// S23 (opt-in STRATA_PF_HCDOWN=1, on chunks of STRATA_PF_SWITCH_MIN_T+ tokens): the hyper-connection read's down and +// inject projections as one WMMA GEMM over xn16 (strata_pf_hcdown_bf16), xn16 written with token stride +// 10240 + 64. Rounding-level (another k order than hipBLASLt): quality-gated. +inline bool pf_hcdown() { + static const bool v = [] { const char* e = std::getenv("STRATA_PF_HCDOWN"); return e && e[0] == '1'; }(); + return v; +} +constexpr int64_t XN_PAD = 64; inline bool cvec_fuse() { static const bool v = [] { const char* e = std::getenv("STRATA_CVEC_FUSE"); return e && e[0] == '1'; }(); return v; @@ -738,7 +747,7 @@ bool Prefill::carve(size_t T, void* alloc) { m.emb = o.take(T * N, ok); m.R = o.take(T * D, ok); m.xn = gr_unfused() ? o.take(T * D, ok) : nullptr; // F-1: not needed (gr_mix_r reads R) m.grs = o.take(T * HC, ok); - m.xn16 = o.take(T * D, ok); m.lo = o.take(T * LR, ok); m.lo16 = o.take(T * LR, ok); + m.xn16 = o.take(T * (D + (pf_hcdown() ? XN_PAD : 0)), ok); m.lo = o.take(T * LR, ok); m.lo16 = o.take(T * LR, ok); m.gated = o.take(T * D, ok); m.inj = o.take(T * HC, ok); m.mixed = o.take(T * N, ok); m.mixed_bf = o.take(T * N, ok); m.mixed_h = o.take(T * N, ok); m.bo = o.take(T * N, ok); @@ -1003,7 +1012,8 @@ uint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::Session o.take((size_t) GEMM_SCRATCH, ok); o.take(GEMM_WS, ok); auto f = [&](size_t n) { o.take(n, ok); }; - f(T * N); f(T * D); f(T * D); o.take(T * D, ok); f(T * LR); o.take(T * LR, ok); + f(T * N); f(T * D); f(T * D); o.take(T * (D + (pf_hcdown() ? XN_PAD : 0)), ok); f(T * LR); + o.take(T * LR, ok); f(T * D); f(T * HC); f(T * N); o.take(T * N, ok); o.take(T * N, ok); f(T * N); if (bf16x2_hc()) { o.take(T * D, ok); o.take(T * LR, ok); } if (bf16x2()) o.take(T * N, ok); @@ -1438,10 +1448,24 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e *wu = need(v, su.c_str(), err), *wi = need(v, si.c_str(), err); if (!wn || !wd || !wu || !wi) return false; pt.mark(kPfHc, cs); + // the xn16 token stride of this chunk (the writers of both halves and of the fused write-backs use it) + const int64_t ldx = pf_hcdown() && T >= std::max(pf_switch_min_t(), 64) && !gr_unfused() && + !m.xn16_lo ? D + XN_PAD : D; if (gr_unfused()) gr_norm(m.R, (const float*) wn->data, EPS, m.xn, m.xn16, T, m.cs, m.xn16_lo); - else if (!normed) gr_norm_rs(m.R, (const float*) wn->data, EPS, m.grs, m.xn16, T, m.cs, m.xn16_lo); + else if (!normed) gr_norm_rs(m.R, (const float*) wn->data, EPS, m.grs, m.xn16, T, m.cs, m.xn16_lo, ldx); normed = false; - if (!bf16_proj(m.gemm, wd, m.xn16, m.lo, T, sd, err, 0, m.xn16_lo)) return false; + bool hcd = false; + if (ldx != D) { + if (wd->kind != core::WeightKind::Bf16InF32 || !wd->data || wd->ne0 != D || wd->ne1 != LR || + wi->kind != core::WeightKind::Bf16InF32 || !wi->data || wi->ne0 != D || wi->ne1 != HC || + !strata_pf_hcdown_bf16(m.xn16, ldx, (const uint16_t*) wd->data, (const uint16_t*) wi->data, LR, + HC, m.lo, m.inj, T, D, m.cs)) { + err = "prefill: STRATA_PF_HCDOWN could not run the hyper-connection projections"; + return false; + } + hcd = true; + } + if (!hcd && !bf16_proj(m.gemm, wd, m.xn16, m.lo, T, sd, err, 0, m.xn16_lo)) return false; gr_silu(m.lo, m.lo16, T, m.cs, m.lo16_lo); bool upmixed = false; if (hc_upmix() && T >= pf_switch_min_t() && !gr_unfused() && !m.lo16_lo && !m.mixed_bf_lo && @@ -1471,7 +1495,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e } } if (!upmixed && !bf16_proj(m.gemm, wu, m.lo16, m.gated, T, su, err, 0, m.lo16_lo)) return false; - if (!bf16_proj(m.gemm, wi, m.xn16, m.inj, T, si, err, 0, m.xn16_lo)) return false; + if (!hcd && !bf16_proj(m.gemm, wi, m.xn16, m.inj, T, si, err, 0, m.xn16_lo)) return false; if (upmixed) { } else if (gr_unfused()) { gr_mix(m.xn, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h, m.mixed_bf_lo); @@ -2141,10 +2165,10 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e cudaMemcpyAsync(Rc, m.R, (size_t) T * D * 4, cudaMemcpyDeviceToDevice, m.cs); gr_write(Rc, m.bo, m.inj, HC, T, m.cs); strata::kernels::cvec_apply(Rc, l, T, D, nullptr, 0, nullptr, 0, false, m.cs); - gr_norm_rs(Rc, (const float*) wnn->data, EPS, rc, xc, T, m.cs); + gr_norm_rs(Rc, (const float*) wnn->data, EPS, rc, xc, T, m.cs, nullptr, D); gr_write_cvec_norm_rs(m.R, m.bo, m.inj, HC, cv_dir + l * N, cv_s + l, cv_on, strata::kernels::cvec().mode, (const float*) wnn->data, EPS, m.grs, - m.xn16, T, m.cs, m.xn16_lo); + m.xn16, T, m.cs, m.xn16_lo, ldx); std::vector a((size_t) T * D), b((size_t) T * D), ra((size_t) T * HC), rb((size_t) T * HC); std::vector xa((size_t) T * D), xb((size_t) T * D); cudaMemcpyAsync(a.data(), m.R, a.size() * 4, cudaMemcpyDeviceToHost, m.cs); @@ -2163,11 +2187,11 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e } else gr_write_cvec_norm_rs(m.R, m.bo, m.inj, HC, cv_dir + l * N, cv_s + l, cv_on, strata::kernels::cvec().mode, (const float*) wnn->data, EPS, m.grs, m.xn16, - T, m.cs, m.xn16_lo); + T, m.cs, m.xn16_lo, ldx); normed = true; } else if (wnn) { gr_write_norm_rs(m.R, m.bo, m.inj, HC, (const float*) wnn->data, EPS, m.grs, m.xn16, T, m.cs, - m.xn16_lo); + m.xn16_lo, ldx); normed = true; } else { gr_write(m.R, m.bo, m.inj, HC, T, m.cs); diff --git a/src/prefill/wmma_gemm.cu b/src/prefill/wmma_gemm.cu index e029f47c..5c88fb3c 100644 --- a/src/prefill/wmma_gemm.cu +++ b/src/prefill/wmma_gemm.cu @@ -459,8 +459,121 @@ __global__ void __launch_bounds__(256) kernel_bk64(const _Float16* __restrict__ } #endif } +// S23 (STRATA_PF_HCDOWN=1): the hyper-connection read's down (N nd = 320) and inject (N ni = 4) projections of xn16 +// (BF16, T x 10240, token stride ldx: 10240 + 64 avoids the 4 KB-multiple stride) as ONE GEMM - weight rows +// [w_down; w_inject] read from the two tensors, the epilogue splitting the columns into lo (T x nd) and inj (T x ni), +// so xn16 is read once. 128 x 128 blocks, the BK 64 single-buffer scheme of kernel_bk64. s23/hcdown_probe.hip, +// 16K tokens: 3.60 / 3.77 ms (hipBLASLt in the engine: down 6.78 + inject 1.81). FP32 accumulation in another k +// order than hipBLASLt: rounding-level. +typedef __bf16 hb16 __attribute__((ext_vector_type(16))); +__device__ __forceinline__ hb16 bfrag(const uint16_t* p) { + const uint4 a = *reinterpret_cast(p), b = *reinterpret_cast(p + 8); + const uint32_t w[8] = {a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w}; + return __builtin_bit_cast(hb16, w); +} +__global__ void __launch_bounds__(256) kernel_hcdown(const uint16_t* __restrict__ X, int ldx, + const uint16_t* __restrict__ Wd, const uint16_t* __restrict__ Wi, + int nd, int ni, float* __restrict__ lo, float* __restrict__ inj, + int M, int K) { +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__) + constexpr int BN = 128, WN = 32, TN = 2, BK64 = 64, LDK64 = BK64 + 8; + __shared__ __align__(16) uint16_t sA[BM][LDK64]; + __shared__ __align__(16) uint16_t sB[BN][LDK64]; + const int N = nd + ni; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, l16 = lane & 15, hi = lane >> 4; + const int wm = wave & 1, wn = wave >> 1; + const int num_m = (M + BM - 1) / BM, num_n = (N + BN - 1) / BN, b = blockIdx.x; + const int group = b / (GM * num_n), first_m = group * GM, gsize = min(GM, num_m - first_m); + const int m0 = (first_m + (b % (GM * num_n)) % gsize) * BM, n0 = ((b % (GM * num_n)) / gsize) * BN; + const int sr = tid >> 3, sq = tid & 7; + auto ldA = [&](int k0, int r) -> uint4 { + return *reinterpret_cast(X + (size_t) min(m0 + r, M - 1) * ldx + k0 + 8 * sq); + }; + auto ldB = [&](int k0, int r) -> uint4 { + const int n = min(n0 + r, N - 1); + const uint16_t* row = n < nd ? Wd + (size_t) n * K : Wi + (size_t) (n - nd) * K; + return *reinterpret_cast(row + k0 + 8 * sq); + }; + uint4 ra0, ra1, ra2, ra3, rb0, rb1, rb2, rb3; + auto load = [&](int k0) { + ra0 = ldA(k0, sr); ra1 = ldA(k0, sr + 32); ra2 = ldA(k0, sr + 64); ra3 = ldA(k0, sr + 96); + rb0 = ldB(k0, sr); rb1 = ldB(k0, sr + 32); rb2 = ldB(k0, sr + 64); rb3 = ldB(k0, sr + 96); + }; + auto store = [&]() { + *reinterpret_cast(&sA[sr][8 * sq]) = ra0; *reinterpret_cast(&sA[sr + 32][8 * sq]) = ra1; + *reinterpret_cast(&sA[sr + 64][8 * sq]) = ra2; *reinterpret_cast(&sA[sr + 96][8 * sq]) = ra3; + *reinterpret_cast(&sB[sr][8 * sq]) = rb0; *reinterpret_cast(&sB[sr + 32][8 * sq]) = rb1; + *reinterpret_cast(&sB[sr + 64][8 * sq]) = rb2; *reinterpret_cast(&sB[sr + 96][8 * sq]) = rb3; + }; + f8 acc[4][TN]; +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int j = 0; j < TN; ++j) acc[i][j] = f8{0, 0, 0, 0, 0, 0, 0, 0}; + load(0); + store(); + __syncthreads(); + const int ar = 64 * wm + l16, br = WN * wn + l16; + for (int k0 = 0; k0 < K; k0 += BK64) { + const bool more = k0 + BK64 < K; + if (more) load(k0 + BK64); +#pragma unroll + for (int ks = 0; ks < BK64; ks += 16) { + const hb16 a0 = bfrag(&sA[ar][ks]), a1 = bfrag(&sA[ar + 16][ks]), a2 = bfrag(&sA[ar + 32][ks]), + a3 = bfrag(&sA[ar + 48][ks]); + const hb16 b0 = bfrag(&sB[br][ks]), b1 = bfrag(&sB[br + 16][ks]); + acc[0][0] = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a0, b0, acc[0][0]); + acc[1][0] = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a1, b0, acc[1][0]); + acc[2][0] = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a2, b0, acc[2][0]); + acc[3][0] = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a3, b0, acc[3][0]); + acc[0][1] = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a0, b1, acc[0][1]); + acc[1][1] = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a1, b1, acc[1][1]); + acc[2][1] = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a2, b1, acc[2][1]); + acc[3][1] = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a3, b1, acc[3][1]); + } + if (more) { + __syncthreads(); + store(); + __syncthreads(); + } + } +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int j = 0; j < TN; ++j) { + const int n = n0 + WN * wn + 16 * j + l16; + if (n >= N) continue; +#pragma unroll + for (int e = 0; e < 8; ++e) { + const int m = m0 + 64 * wm + 16 * i + 2 * e + hi; + if (m < M) { + if (n < nd) lo[(size_t) m * nd + n] = acc[i][j][e]; + else inj[(size_t) m * ni + (n - nd)] = acc[i][j][e]; + } + } + } +#endif +} } // namespace pfg +bool strata_pf_hcdown_bf16(const uint16_t* X, int64_t ldx, const uint16_t* Wd, const uint16_t* Wi, int64_t nd, + int64_t ni, float* lo, float* inj, int64_t T, int64_t K, void* stream) { + if (!X || !Wd || !Wi || !lo || !inj || T < 64 || nd < 1 || ni < 0 || K % 64 != 0 || ldx < K || ldx % 8 != 0) return false; + if (T > (1LL << 30) || K > (1LL << 30) || ldx > (1LL << 30)) return false; + static const bool gfx11 = [] { + int dev = 0; + hipDeviceProp_t prop{}; + if (hipGetDevice(&dev) != hipSuccess || hipGetDeviceProperties(&prop, dev) != hipSuccess) return false; + return std::strncmp(prop.gcnArchName, "gfx11", 5) == 0; + }(); + if (!gfx11) return false; + const int64_t mt = (T + pfg::BM - 1) / pfg::BM; + const unsigned grid = (unsigned) (mt * ((nd + ni + 127) / 128)); + pfg::kernel_hcdown<<(stream)>>>(X, (int) ldx, Wd, Wi, (int) nd, (int) ni, + lo, inj, (int) T, (int) K); + return hipGetLastError() == hipSuccess; +} + bool strata_pf_gemm_f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy, float beta, void* stream) { return strata_pf_gemm_f16_ld(X, K, W, K, Y, T, N, K, ldy, beta, stream); @@ -510,6 +623,10 @@ bool strata_pf_gemm_f16_ld(const uint16_t*, int64_t, const uint16_t*, int64_t, f int64_t, float, void*) { return false; } +bool strata_pf_hcdown_bf16(const uint16_t*, int64_t, const uint16_t*, const uint16_t*, int64_t, int64_t, float*, float*, + int64_t, int64_t, void*) { + return false; +} bool strata_wmma_gemm_f16(const uint16_t*, const uint16_t*, float*, int64_t, int64_t, int64_t, int64_t, float, void*) { diff --git a/src/prefill/wmma_gemm.h b/src/prefill/wmma_gemm.h index f8e56c91..cfe087a0 100644 --- a/src/prefill/wmma_gemm.h +++ b/src/prefill/wmma_gemm.h @@ -23,6 +23,11 @@ bool strata_pf_gemm_f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t float beta, void* stream = nullptr); /// The same with row strides ldx >= K and ldw >= K (multiples of 8): a 4 KB-multiple row stride (K 2048 / 4096 / /// 6144) camps on the memory channels, K + 64 does not (S23 gemm_probe7/8: K 6144 19 -> 35 TFLOPS). +/// S23 (STRATA_PF_HCDOWN=1): lo[t, n] = sum_k X[t, k] Wd[n, k] (n < nd) and inj[t, n] = sum_k X[t, k] Wi[n, k] +/// (n < ni) in one BF16 WMMA GEMM over X (T x K, token stride ldx >= K, a multiple of 8; Wd / Wi row-major, stride +/// K); lo T x nd and inj T x ni, FP32. K a multiple of 64, T >= 64. False (nothing launched) otherwise / off gfx11. +bool strata_pf_hcdown_bf16(const uint16_t* X, int64_t ldx, const uint16_t* Wd, const uint16_t* Wi, int64_t nd, + int64_t ni, float* lo, float* inj, int64_t T, int64_t K, void* stream = nullptr); bool strata_pf_gemm_f16_ld(const uint16_t* X, int64_t ldx, const uint16_t* W, int64_t ldw, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy, float beta, void* stream = nullptr); From 65a48f0d57020bdbd4847b640695bd69e4b98e08 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 4 Oct 2026 09:24:45 +0200 Subject: [PATCH 44/55] prefill: STRATA_PF_PAD with a weight that cannot be padded (an i-quant dense tensor) - X read at its stride The padded activation of ssm_out / attn_output was handed to Gemm::native, whose padded-weight path needs a strided dequant; the GSQ-RCO IQ3_XXS model has IQ3_S ssm_out tensors (no strided dequant for the i-quants), so the engine exited at the first 64K chunk ("a padded X needs STRATA_PF_PAD's path"). Now such a weight is dequantized unpadded and strata_pf_gemm_f16_ld reads X at its stride: the same kernel and products as with PF_PAD off, the same bits. --- src/prefill/gemm.cu | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/prefill/gemm.cu b/src/prefill/gemm.cu index 4858bdfb..1be38082 100644 --- a/src/prefill/gemm.cu +++ b/src/prefill/gemm.cu @@ -454,6 +454,19 @@ void Gemm::native(const uint16_t* X, int ggml_type, const void* W_blocks, float* } #endif if (ldx > 0 && ldx != K) { +#ifdef STRATA_USE_HIP + // X arrived padded but the weight cannot be (an i-quant without a strided dequant, or the scratch is too + // small for N x (K + 64)): the weight unpadded, X read at its stride - the same products, the same bits + const int64_t rows = scratch_elems_ / K; + bool ok = rows > 0; + if (ldy <= 0) ldy = N; + for (int64_t r0 = 0; ok && r0 < N; r0 += rows) { + const int64_t n = (N - r0 < rows) ? N - r0 : rows; + strata::kernels::dequant_f16(ggml_type, W_blocks, r0, n, K, scratch_, stream_); + ok = strata_pf_gemm_f16_ld(X, ldx, scratch_, K, Y + r0, T, n, K, ldy, beta, stream_); + } + if (ok) return; +#endif std::fprintf(stderr, "prefill gemm: a padded X (ldx %lld, K %lld) needs STRATA_PF_PAD's path\n", (long long) ldx, (long long) K); std::exit(1); From 7440806987d9a6011b8e5fea37b4f72a2f60cf89 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 4 Oct 2026 14:16:58 +0000 Subject: [PATCH 45/55] prefill: STRATA_PF_FUSED_KQ=1 - the fused native-expert path takes UD-Q4_K_XL (gfx11): gate/up Q4_K / Q5_K, down Q5_1 / Q8_0 The formats carry a minimum, so the activation blocks' spare bytes now hold the int8 code sums per 32 values (written by every path, read by none else). Layers MMQ does not cover on HIP (Q4_K) join the fused layout through MmqPlan::fo. Opt-in (default output bit-identical). Test pairs plus an int8-rounded model check; QA_SAME probe in the attention harness. --- src/kernels/qsa_prompt_attn_parity.cpp | 11 ++ src/prefill/moe_fused_iq.cu | 164 +++++++++++++++++++++---- src/prefill/prefill.cpp | 13 +- tests/cuda/prefill_fused_iq_test.cpp | 96 +++++++++++---- 4 files changed, 235 insertions(+), 49 deletions(-) diff --git a/src/kernels/qsa_prompt_attn_parity.cpp b/src/kernels/qsa_prompt_attn_parity.cpp index 14efdc2b..80c53859 100644 --- a/src/kernels/qsa_prompt_attn_parity.cpp +++ b/src/kernels/qsa_prompt_attn_parity.cpp @@ -97,6 +97,17 @@ int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16 std::sort(v.begin(), v.end()); std::copy(v.begin(), v.end(), sel); } + // QA_SAME=1 (S23 probe): every query reads the same first-w cells - the best case of any K/V sharing between queries + // (all loads hit the caches); QA_SAME=2: query i reads a window of w cells at i / 4 * 64 (neighbours share ~90%) + if (const char* sm = std::getenv("QA_SAME")) { + const int mode = std::atoi(sm); + for (int64_t i = 0; i < nq; ++i) { + const int64_t w = steps[i * k::kStepCount + k::kStepWidth], nkv = ctx - nq + i + 1; + if (w == nkv) continue; + const int64_t base = mode == 1 ? 0 : std::min(i / 4 * 64, nkv - w); + for (int64_t c = 0; c < w; ++c) ids[i * cap + c] = (int32_t) (base + c); + } + } 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); } diff --git a/src/prefill/moe_fused_iq.cu b/src/prefill/moe_fused_iq.cu index 72c278d7..61b5be50 100644 --- a/src/prefill/moe_fused_iq.cu +++ b/src/prefill/moe_fused_iq.cu @@ -62,15 +62,28 @@ constexpr int GU_ROWS_K = 2560, D_ROWS_K = 640; // K of gate/up (n_embd) and o // the formats (ggml type ids) constexpr int T_IQ2_XXS = GGML_TYPE_IQ2_XXS, T_IQ2_XS = GGML_TYPE_IQ2_XS, T_IQ2_S = GGML_TYPE_IQ2_S, T_IQ3_XXS = GGML_TYPE_IQ3_XXS, T_IQ3_S = GGML_TYPE_IQ3_S, T_IQ4_XS = GGML_TYPE_IQ4_XS, - T_IQ4_NL = GGML_TYPE_IQ4_NL, T_Q2_0 = GGML_TYPE_Q2_0; + T_IQ4_NL = GGML_TYPE_IQ4_NL, T_Q2_0 = GGML_TYPE_Q2_0, + // Aurora (opt-in, HIP gfx11 only): Unsloth UD-Q4_K_XL's experts - gate/up Q4_K (one layer Q5_K), down Q5_1 + // (five layers Q8_0). Their weights are w = d_w q + m_w (a minimum), so a sub-block's dot is + // sum w x = d_x (d_w sum q a + m_w sum a): + // the activation blocks carry sum a per 32 values in their eight spare bytes (quant_act_nat_kernel and + // the H epilogue write it for every path; no other format reads it) + T_Q4_K = GGML_TYPE_Q4_K, T_Q5_K = GGML_TYPE_Q5_K, T_Q5_1 = GGML_TYPE_Q5_1, T_Q8_0 = GGML_TYPE_Q8_0; static_assert(sizeof(block_iq2_xxs) == 66 && sizeof(block_iq2_xs) == 74 && sizeof(block_iq2_s) == 82 && sizeof(block_iq3_xxs) == 98 && sizeof(block_iq3_s) == 110 && sizeof(block_iq4_xs) == 136 && - sizeof(block_iq4_nl) == 18 && sizeof(block_q2_0) == 18, "the block layouts this file decodes"); + sizeof(block_iq4_nl) == 18 && sizeof(block_q2_0) == 18 && sizeof(block_q4_K) == 144 && + sizeof(block_q5_K) == 176 && sizeof(block_q5_1) == 24 && sizeof(block_q8_0) == 34, + "the block layouts this file decodes"); // block bytes, scale per 16 values, codebook bytes in shared memory __host__ __device__ constexpr int block_bytes(int t) { return t == T_IQ2_XXS ? 66 : t == T_IQ2_XS ? 74 : t == T_IQ2_S ? 82 : t == T_IQ3_XXS ? 98 : t == T_IQ3_S ? 110 - : t == T_IQ4_XS ? 136 : 18; + : t == T_IQ4_XS ? 136 : t == T_Q4_K ? 144 : t == T_Q5_K ? 176 : t == T_Q5_1 ? 24 : t == T_Q8_0 ? 34 : 18; +} +// the formats with a minimum (w = d q + m), and the raw words a sub-block's load stage holds +__host__ __device__ constexpr bool has_min(int t) { return t == T_Q4_K || t == T_Q5_K || t == T_Q5_1; } +__host__ __device__ constexpr int raw_words(int t) { + return t == T_Q4_K ? 10 : t == T_Q5_K ? 18 : t == T_Q5_1 ? 6 : t == T_Q8_0 ? 9 : 5; } __host__ __device__ constexpr bool per16(int t) { return t == T_IQ2_XS || t == T_IQ2_S; } __host__ __device__ constexpr int grid_bytes(int t) { @@ -107,9 +120,16 @@ __global__ void quant_act_nat_kernel(const float* __restrict__ x, int64_t nblk, a1 = fmaxf(a1, __shfl_xor_sync(0xffffffffu, a1, o)); } uint8_t* out = xa + w * AB; - out[lane] = (uint8_t) (int8_t) (a0 > 0.0f ? __float2int_rn(v0 * (127.0f / a0)) : 0); - out[32 + lane] = (uint8_t) (int8_t) (a1 > 0.0f ? __float2int_rn(v1 * (127.0f / a1)) : 0); - if (lane == 0) *(float4*) (out + 64) = make_float4(a0 / 127.0f, a1 / 127.0f, 0.0f, 0.0f); + const int c0 = a0 > 0.0f ? __float2int_rn(v0 * (127.0f / a0)) : 0, c1 = a1 > 0.0f ? __float2int_rn(v1 * (127.0f / a1)) : 0; + out[lane] = (uint8_t) (int8_t) c0; + out[32 + lane] = (uint8_t) (int8_t) c1; + int s0 = c0, s1 = c1; // the codes' sums per 32 values (the formats with a minimum read them) +#pragma unroll + for (int o = 16; o > 0; o >>= 1) { + s0 += __shfl_xor_sync(0xffffffffu, s0, o); + s1 += __shfl_xor_sync(0xffffffffu, s1, o); + } + if (lane == 0) *(float4*) (out + 64) = make_float4(a0 / 127.0f, a1 / 127.0f, (float) s0, (float) s1); } #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 @@ -180,7 +200,12 @@ __device__ __forceinline__ void table16(uint32_t q4, const uint32_t (&t)[4], uin // Raw bytes of sub-block `ib` of the block at `bp` (IQ: the 256-value super-block, ib 0..7; Q2_0: the 64-value block, // ib 0..1; IQ4_NL: the 32-value block). -template __device__ __forceinline__ void load_unit(const uint8_t* bp, int ib, uint32_t (&w)[5]) { +// 32 bits at a 2-byte aligned address (one load when it is 4-byte aligned) +__device__ __forceinline__ uint32_t ld32a(const uint8_t* p) { + return ((uintptr_t) p & 3) == 0 ? *(const uint32_t*) p : ld32(p); +} +template __device__ __forceinline__ void load_unit(const uint8_t* bp, int ib, uint32_t (&w)[NW]) { + static_assert(NW >= raw_words(T), "raw words"); if constexpr (T == T_IQ2_XXS) { w[0] = ld32(bp + 2 + 8 * ib); w[1] = ld32(bp + 6 + 8 * ib); w[2] = ld16(bp); } else if constexpr (T == T_IQ2_XS) { @@ -202,16 +227,69 @@ template __device__ __forceinline__ void load_unit(const uint8_t* bp, in #pragma unroll for (int k = 0; k < 4; ++k) w[k] = ld32(bp + 2 + 4 * k); w[4] = ld16(bp); + } else if constexpr (T == T_Q4_K || T == T_Q5_K) { + // qs: 32 bytes of the sub-block pair (ib / 2), the nibble chosen in convert; w[8] = d | dmin << 16; w[9]: the + // scale/min bytes (get_scale_min_k4's: ib < 4: sc[ib], sc[ib + 4]; else sc[ib + 4], sc[ib - 4], sc[ib]), ib << 24 + constexpr int QS = T == T_Q4_K ? 16 : 48; + const uint8_t* q = bp + QS + 32 * (ib >> 1); +#pragma unroll + for (int k = 0; k < 8; ++k) w[k] = ld32a(q + 4 * k); + w[8] = ld32a(bp); + const uint8_t* sc = bp + 4; + w[9] = ib < 4 ? (uint32_t) sc[ib] | ((uint32_t) sc[ib + 4] << 8) + : (uint32_t) sc[ib + 4] | ((uint32_t) sc[ib - 4] << 8) | ((uint32_t) sc[ib] << 16); + w[9] |= (uint32_t) ib << 24; + if constexpr (T == T_Q5_K) { +#pragma unroll + for (int k = 0; k < 8; ++k) w[10 + k] = ld32a(bp + 16 + 4 * k); // qh + } + } else if constexpr (T == T_Q5_1) { // d, m, qh, qs[16] +#pragma unroll + for (int k = 0; k < 4; ++k) w[k] = ld32a(bp + 8 + 4 * k); + w[4] = ld32a(bp + 4); + w[5] = ld32a(bp); + } else if constexpr (T == T_Q8_0) { // d, qs[32] +#pragma unroll + for (int k = 0; k < 8; ++k) w[k] = ld32(bp + 2 + 4 * k); + w[8] = ld16(bp); } else { // Q2_0 w[0] = ld32(bp + 2 + 8 * ib); w[1] = ld32(bp + 6 + 8 * ib); w[2] = ld16(bp); } } // The sub-block as 32 int8 (q[0..7], natural order) and its scales (s0: values 0-15, s1: 16-31). -template -__device__ __forceinline__ void convert(const uint32_t (&w)[5], const uint8_t* grid, const uint32_t (&kv)[4], +template +__device__ __forceinline__ void convert(const uint32_t (&w)[NW], const uint8_t* grid, const uint32_t (&kv)[4], uint32_t (&q)[8], float& s0, float& s1) { - if constexpr (T == T_IQ2_XXS) { + if constexpr (T == T_Q4_K || T == T_Q5_K) { + const int ib = (int) (w[9] >> 24), sh = 4 * (ib & 1); + uint32_t sc, mn; + if (ib < 4) { sc = w[9] & 63; mn = (w[9] >> 8) & 63; } + else { + sc = ((w[9] & 0xF) | (((w[9] >> 8) & 0xC0) >> 2)); // sc[ib + 4] & 15 | (sc[ib - 4] >> 6) << 4 + mn = (((w[9]) >> 4) & 0xF) | (((w[9] >> 16) & 0xC0) >> 2); // sc[ib + 4] >> 4 | (sc[ib] >> 6) << 4 + } +#pragma unroll + for (int k = 0; k < 8; ++k) { + q[k] = (w[k] >> sh) & 0x0F0F0F0Fu; + if constexpr (T == T_Q5_K) q[k] |= ((w[10 + k] >> ib) & 0x01010101u) << 4; + } + s0 = half_at(w[8]) * (float) sc; + s1 = -(half_at(w[8] >> 16) * (float) mn); + } else if constexpr (T == T_Q5_1) { +#pragma unroll + for (int k = 0; k < 4; ++k) { + const uint32_t lo = ((w[4] >> (4 * k)) & 0xF) * 0x00204081u, hi = ((w[4] >> (16 + 4 * k)) & 0xF) * 0x00204081u; + q[k] = (w[k] & 0x0F0F0F0Fu) | ((lo & 0x01010101u) << 4); + q[4 + k] = ((w[k] >> 4) & 0x0F0F0F0Fu) | ((hi & 0x01010101u) << 4); + } + s0 = half_at(w[5]); + s1 = half_at(w[5] >> 16); + } else if constexpr (T == T_Q8_0) { +#pragma unroll + for (int k = 0; k < 8; ++k) q[k] = w[k]; + s0 = s1 = half_at(w[8]); + } else if constexpr (T == T_IQ2_XXS) { const uint2* g = (const uint2*) grid; #pragma unroll for (int l = 0; l < 4; ++l) { @@ -581,10 +659,10 @@ native_w11_kernel(const Batch b, const NativeGeom geo, const Tables tb, const ui : blob + geo.down_off + (size_t) (rbase + ur) * geo.d_row; auto unit = [&](int s) -> const uint8_t* { if (GU) return wrow + (s >> 2) * BS; - return WT == T_IQ4_NL ? wrow + (2 * s + uj) * BS : wrow + s * BS; + return (WT == T_IQ4_NL || WT == T_Q5_1 || WT == T_Q8_0) ? wrow + (2 * s + uj) * BS : wrow + s * BS; }; auto sub = [&](int s) { return GU ? 2 * (s & 3) + uj : uj; }; - auto put = [&](const uint32_t (&raw)[5], int buf) { + auto put = [&](const uint32_t (&raw)[raw_words(WT)], int buf) { uint32_t q[8]; float s0, s1; convert(raw, sgrid, kv, q, s0, s1); @@ -598,7 +676,7 @@ native_w11_kernel(const Batch b, const NativeGeom geo, const Tables tb, const ui const int r = row0 + min(tid, nrows - 1); // rows past the tile's end repeat its last one srow[tid] = GU ? src[r] : r; } - uint32_t raw[5] = {0, 0, 0, 0, 0}; + uint32_t raw[raw_words(WT)] = {}; load_unit(unit(0), sub(0), raw); put(raw, 0); if (NS > 1) load_unit(unit(1), sub(1), raw); @@ -615,21 +693,23 @@ native_w11_kernel(const Batch b, const NativeGeom geo, const Tables tb, const ui #pragma unroll for (int i = 0; i < 8; ++i) acc[mt][nt][i] = 0.0f; uint4 bq[2][4]; - float2 bx[2]; - auto fetch_b = [&](int s, uint4 (&q)[2][4], float2 (&x)[2]) { + float2 bx[2], bsum[2]; // the activation scales, and (the formats with a minimum) the codes' sums per 32 values + auto fetch_b = [&](int s, uint4 (&q)[2][4], float2 (&x)[2], float2 (&sm)[2]) { #pragma unroll for (int nt = 0; nt < 2; ++nt) { const uint4* p = reinterpret_cast(brow[nt] + s * AB); q[nt][0] = p[0]; q[nt][1] = p[1]; q[nt][2] = p[2]; q[nt][3] = p[3]; x[nt] = *reinterpret_cast(brow[nt] + s * AB + 64); + if constexpr (has_min(WT)) sm[nt] = *reinterpret_cast(brow[nt] + s * AB + 72); + else sm[nt] = make_float2(0.0f, 0.0f); } }; - if (on) fetch_b(0, bq, bx); + if (on) fetch_b(0, bq, bx, bsum); for (int s = 0; s < NS; ++s) { __syncthreads(); // stage s's weights are in buffer s & 1 uint4 nbq[2][4]; - float2 nbx[2]; - if (on && s + 1 < NS) fetch_b(s + 1, nbq, nbx); + float2 nbx[2], nbsum[2]; + if (on && s + 1 < NS) fetch_b(s + 1, nbq, nbx, nbsum); if (on) { const int bf = s & 1; #pragma unroll @@ -660,7 +740,10 @@ native_w11_kernel(const Batch b, const NativeGeom geo, const Tables tb, const ui } else { const nw_i8 d = nw_wmma(A1, B1, nw_wmma(A0, B0, m)); #pragma unroll - for (int i = 0; i < 8; ++i) acc[mt][nt][i] = fmaf(w0[i] * dx, dotf(d[i]), acc[mt][nt][i]); + for (int i = 0; i < 8; ++i) { + acc[mt][nt][i] = fmaf(w0[i] * dx, dotf(d[i]), acc[mt][nt][i]); + if constexpr (has_min(WT)) acc[mt][nt][i] = fmaf(w1[i] * dx, h ? bsum[nt].y : bsum[nt].x, acc[mt][nt][i]); + } } } } @@ -673,6 +756,7 @@ native_w11_kernel(const Batch b, const NativeGeom geo, const Tables tb, const ui #pragma unroll for (int nt = 0; nt < 2; ++nt) { bx[nt] = nbx[nt]; + bsum[nt] = nbsum[nt]; #pragma unroll for (int j = 0; j < 4; ++j) bq[nt][j] = nbq[nt][j]; } @@ -703,13 +787,18 @@ native_w11_kernel(const Batch b, const NativeGeom geo, const Tables tb, const ui const float inv = am > 0.0f ? 127.0f / am : 0.0f; uint8_t* o = out + (size_t) (row0 + r) * (10 * AB) + (size_t) fb * AB; uint32_t wd[8] = {}; + int csum = 0; #pragma unroll - for (int j = 0; j < 32; ++j) - wd[j >> 2] |= (uint32_t) (uint8_t) (int8_t) __float2int_rn(hs[r][32 * hh + j] * inv) << (8 * (j & 3)); + for (int j = 0; j < 32; ++j) { + const int c = __float2int_rn(hs[r][32 * hh + j] * inv); + csum += c; + wd[j >> 2] |= (uint32_t) (uint8_t) (int8_t) c << (8 * (j & 3)); + } uint4* o4 = reinterpret_cast(o + 32 * hh); o4[0] = make_uint4(wd[0], wd[1], wd[2], wd[3]); o4[1] = make_uint4(wd[4], wd[5], wd[6], wd[7]); *reinterpret_cast(o + 64 + 4 * hh) = am / 127.0f; + *reinterpret_cast(o + 72 + 4 * hh) = (float) csum; // (the formats with a minimum) } } } else { @@ -815,10 +904,29 @@ const DevInfo& dev_info() { #endif } +// opt-in on top of STRATA_PF_FUSED=1: STRATA_PF_FUSED_KQ=1 takes UD-Q4_K_XL's formats (the output differs from the FP16 +// expert path's at rounding level; KL-gated, see aurora_s23.md) +bool kq_on() { + static const bool on = [] { + const char* v = std::getenv("STRATA_PF_FUSED_KQ"); + return v != nullptr && v[0] == '1'; + }(); + return on; +} bool gu_covered(int t) { - return t == T_IQ2_XXS || t == T_IQ2_XS || t == T_IQ2_S || t == T_IQ3_XXS || t == T_IQ3_S || t == T_IQ4_XS; + return t == T_IQ2_XXS || t == T_IQ2_XS || t == T_IQ2_S || t == T_IQ3_XXS || t == T_IQ3_S || t == T_IQ4_XS +#if defined(__HIPCC__) + || ((t == T_Q4_K || t == T_Q5_K) && kq_on()) // the gfx11 kernels only +#endif + ; +} +bool d_covered(int t) { + return t == T_Q2_0 || t == T_IQ4_NL +#if defined(__HIPCC__) + || ((t == T_Q5_1 || t == T_Q8_0) && kq_on()) +#endif + ; } -bool d_covered(int t) { return t == T_Q2_0 || t == T_IQ4_NL; } template void launch(int ww, unsigned grid, const Batch& b, const NativeGeom& g, const Tables& tb, const void* act, @@ -886,11 +994,17 @@ void experts_native(const Batch& b, const NativeGeom& g, int n_expert, int64_t n case T_IQ2_S: STRATA_NW_GU(T_IQ2_S); break; case T_IQ3_XXS: STRATA_NW_GU(T_IQ3_XXS); break; case T_IQ3_S: STRATA_NW_GU(T_IQ3_S); break; + case T_Q4_K: STRATA_NW_GU(T_Q4_K); break; + case T_Q5_K: STRATA_NW_GU(T_Q5_K); break; default: STRATA_NW_GU(T_IQ4_XS); break; } #undef STRATA_NW_GU - if (g.d_type == T_Q2_0) native_w11_kernel<<>>(b, g, tb, ha8, src, nullptr, dm); - else native_w11_kernel<<>>(b, g, tb, ha8, src, nullptr, dm); +#define STRATA_NW_D(T) native_w11_kernel<<>>(b, g, tb, ha8, src, nullptr, dm) + if (g.d_type == T_Q2_0) STRATA_NW_D(T_Q2_0); + else if (g.d_type == T_Q5_1) STRATA_NW_D(T_Q5_1); + else if (g.d_type == T_Q8_0) STRATA_NW_D(T_Q8_0); + else STRATA_NW_D(T_IQ4_NL); +#undef STRATA_NW_D ck(cudaGetLastError(), "experts_native"); return; } diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 26a860a5..0f89eacd 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -559,6 +559,8 @@ constexpr size_t MMQ_TAIL = 4096; struct MmqPlan { bool any = false, fallback = true; std::vector layer; // per layer: MMQ + std::vector fo; // per layer: no MMQ here but the native fused kernels cover its formats + // (gfx11: UD-Q4_K_XL's Q4_K / Q5_K and Q5_1 / Q8_0 experts, STRATA_PF_FUSED=1) size_t gu_max = 0, d_max = 0; }; const MmqPlan& mmq_plan() { @@ -569,11 +571,17 @@ const MmqPlan& mmq_plan() { const bool on = mmq::built() && (env == nullptr || std::atoi(env) != 0); const int64_t layers = lay.native ? (int64_t) lay.fmt.size() : lay.n_layers; p.layer.assign((size_t) std::max(layers, 0), 0); + p.fo.assign(p.layer.size(), 0); p.fallback = !on || layers <= 0; for (int64_t l = 0; on && l < layers; ++l) { const int gt = lay.native ? lay.fmt[(size_t) l].gu_type : 42, dt = lay.native ? lay.fmt[(size_t) l].d_type : 42; // #420: a tile on every GPU for these shapes (gate+up: 1280 rows, down: N rows), else the FP16 path - if (!mmq::fits(gt, 1280) || !mmq::fits(dt, N)) { p.fallback = true; continue; } + if (!mmq::fits(gt, 1280) || !mmq::fits(dt, N)) { + p.fallback = true; + // the fused path's buffers (Xq, H) exist for it; a chunk it does not take (a small one) keeps the FP16 path + if (on && lay.native && fused::native_supported(gt, dt)) { p.fo[(size_t) l] = 1; p.any = true; } + continue; + } p.layer[(size_t) l] = 1; p.any = true; p.gu_max = std::max(p.gu_max, mmq::matrix_bytes(gt, 1280, N)); @@ -1758,7 +1766,8 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e const bool use_mmq = mmq_plan().any && mmq_plan().layer[(size_t) l]; const int mmq_gt = lay.native ? lay.fmt[(size_t) l].gu_type : 42; const int mmq_dt = lay.native ? lay.fmt[(size_t) l].d_type : 42; - const bool fused_nat = use_mmq && stream_all && lay.native && fused::native_supported(mmq_gt, mmq_dt); + const bool fused_only = mmq_plan().any && mmq_plan().fo[(size_t) l]; + const bool fused_nat = (use_mmq || fused_only) && stream_all && lay.native && fused::native_supported(mmq_gt, mmq_dt); const bool fused_l = (use_mmq && stream_all && !lay.native && fused::enabled()) || fused_nat; size_t n_order = 0; // the routed experts (the debug report; unknown when fused) if (fused_l) { diff --git a/tests/cuda/prefill_fused_iq_test.cpp b/tests/cuda/prefill_fused_iq_test.cpp index d436a605..7178cdad 100644 --- a/tests/cuda/prefill_fused_iq_test.cpp +++ b/tests/cuda/prefill_fused_iq_test.cpp @@ -57,6 +57,8 @@ struct Pair { ggml_type gu, d; const char* name; }; +// MMQ covers this pair (the HIP build has no Q4_K / Q5_K / Q5_1 MMQ: those pairs are checked against the reference only) +bool mmq_ok(const Pair& p) { return mmq::supported((int) p.gu) && mmq::supported((int) p.d); } struct Geo { size_t gu_row, d_row, up_off, down_off, bytes; @@ -80,13 +82,18 @@ struct Geo { void fill_matrix(uint8_t* m, ggml_type t, int64_t rows, int64_t cols, std::mt19937& rng) { const size_t bs = ggml_type_size(t), nb = (size_t) rows * (size_t) (cols / ggml_blck_size(t)); std::uniform_int_distribution byte(0, 255); - const float lo = t == GGML_TYPE_IQ3_S ? 0.0004f : t == GGML_TYPE_IQ4_XS ? 0.00005f + const float lo = t == GGML_TYPE_Q4_K || t == GGML_TYPE_Q5_K ? 0.00004f : t == GGML_TYPE_Q5_1 ? 0.0006f + : t == GGML_TYPE_Q8_0 ? 0.0001f : t == GGML_TYPE_IQ3_S ? 0.0004f : t == GGML_TYPE_IQ4_XS ? 0.00005f : t == GGML_TYPE_IQ4_NL ? 0.0002f : t == GGML_TYPE_Q2_0 ? 0.004f : 0.0008f; std::uniform_real_distribution sc(lo, 6.0f * lo); for (size_t i = 0; i < nb * bs; ++i) m[i] = (uint8_t) byte(rng); for (size_t b = 0; b < nb; ++b) { const ggml_fp16_t h = ggml_fp32_to_fp16(sc(rng)); std::memcpy(m + b * bs, &h, 2); + if (t == GGML_TYPE_Q4_K || t == GGML_TYPE_Q5_K || t == GGML_TYPE_Q5_1) { // the minimum's scale, either sign + const ggml_fp16_t h2 = ggml_fp32_to_fp16(sc(rng) * ((rng() & 1) ? 1.0f : -1.0f) * (t == GGML_TYPE_Q5_1 ? 4.0f : 1.0f)); + std::memcpy(m + b * bs + 2, &h2, 2); + } } } std::vector make_blob(const Pair& p, const Geo& g, std::mt19937& rng) { @@ -271,6 +278,16 @@ Err compare(const std::vector& a, RA row_a, const std::vector& b, return out; } +// the kernels' int8 rounding per 32 values (quant_act_nat_kernel / the H epilogue), as floats: codes * (amax / 127) +void quant32(const float* in, float* out, int n) { + for (int b = 0; b < n; b += 32) { + float am = 0.0f; + for (int j = 0; j < 32; ++j) am = std::max(am, std::fabs(in[b + j])); + const float inv = am > 0.0f ? 127.0f / am : 0.0f, d = am / 127.0f; + for (int j = 0; j < 32; ++j) out[b + j] = (float) std::nearbyint(in[b + j] * inv) * d; + } +} + std::vector download(const Dev& d, size_t n) { std::vector h(n); ck(cudaMemcpy(h.data(), d.p, n * 4, cudaMemcpyDeviceToHost), "download"); @@ -310,27 +327,30 @@ void reference_part(const Pair& p, cudaStream_t s) { // (the uploads above are on the legacy stream and the work below on a non-blocking one: a cudaMemcpy from pageable // memory may return before its DMA lands - on Windows it can wait in the queue until the next synchronous call) ck(cudaDeviceSynchronize(), "uploads"); + const bool mq = mmq_ok(p); mmq::Context ctx; - MmqBufs mb(p, rows, E); - run_mmq(p, geo, ctx, mb, r, x_dev.as(), src_dev.as(), blob, rows, s); + MmqBufs* mbp = mq ? new MmqBufs(p, rows, E) : nullptr; + if (mq) run_mmq(p, geo, ctx, *mbp, r, x_dev.as(), src_dev.as(), blob, rows, s); FusedBufs fb(T, rows, E); ck(cudaMemcpy(fb.ids.p, ids.data(), ids.size() * 4, cudaMemcpyHostToDevice), "ids"); ck(cudaMemset(fb.dm.p, 0xff, (size_t) rows * N * 4), "sentinel"); // an unwritten row is NaN ck(cudaDeviceSynchronize(), "uploads"); run_fused(p, geo, fb, x_dev.as(), T, E, {0, 1, 20, E}, blob, s); ck(cudaStreamSynchronize(s), "sync"); - const std::vector y_mmq = download(mb.dm, (size_t) rows * N), y_f = download(fb.dm, (size_t) rows * N); + const std::vector y_mmq = mq ? download(mbp->dm, (size_t) rows * N) : std::vector((size_t) rows * N, 0.0f), + y_f = download(fb.dm, (size_t) rows * N); + delete mbp; const std::vector slot = download_i(fb.slot, (size_t) rows), fsrc = download_i(fb.src, (size_t) rows); for (int64_t i = 0; i < rows; ++i) if (fsrc[(size_t) slot[(size_t) i]] != (int32_t) (i / K)) throw std::runtime_error("group: slot/src disagree"); // the reference, an expert at a time on all cores - std::vector ref((size_t) rows * N); + std::vector ref((size_t) rows * N), ref2((size_t) rows * N); // ref2: the same with the kernels' int8 rounding std::vector th; const int nth = std::max(1, std::min(16, (int) std::thread::hardware_concurrency())); for (int w = 0; w < nth; ++w) th.emplace_back([&, w] { - std::vector gu, dn, h(FF); + std::vector gu, dn, h(FF), h2(FF), hq(FF), xq(N); for (int e = w; e < E; e += nth) { if (r.cnt[(size_t) e] == 0) continue; dequant(p, geo, host[(size_t) e], gu, dn); @@ -349,6 +369,20 @@ void reference_part(const Pair& p, cudaStream_t s) { for (int f = 0; f < FF; ++f) a += (double) wd[f] * h[(size_t) f]; ref[(size_t) i * N + o] = (float) a; } + quant32(xr, xq.data(), N); + for (int f = 0; f < FF; ++f) { + double gt = 0, up = 0; + const float *wg = gu.data() + (size_t) f * N, *wu = gu.data() + (size_t) (FF + f) * N; + for (int k = 0; k < N; ++k) { gt += (double) wg[k] * xq[(size_t) k]; up += (double) wu[k] * xq[(size_t) k]; } + h2[(size_t) f] = (float) (gt / (1.0 + std::exp(-gt)) * up); + } + quant32(h2.data(), hq.data(), FF); + for (int o = 0; o < N; ++o) { + double a = 0; + const float* wd = dn.data() + (size_t) o * FF; + for (int f = 0; f < FF; ++f) a += (double) wd[f] * hq[(size_t) f]; + ref2[(size_t) i * N + o] = (float) a; + } } } }); @@ -357,17 +391,27 @@ void reference_part(const Pair& p, cudaStream_t s) { auto pair = [](size_t i) { return (int64_t) i; }; auto mrow = [&](size_t i) { return (int64_t) r.row_of[i]; }; auto frow = [&](size_t i) { return (int64_t) slot[i]; }; - const Err em = compare(y_mmq, mrow, ref, pair, (size_t) rows); + const Err em = mq ? compare(y_mmq, mrow, ref, pair, (size_t) rows) : Err{}; const Err ef = compare(y_f, frow, ref, pair, (size_t) rows); - const Err efm = compare(y_f, frow, y_mmq, mrow, (size_t) rows); - std::printf(" MMQ vs FP32 reference: rel RMS %.3e worst row max rel %.3e\n", em.rms, em.worst); + const Err efm = mq ? compare(y_f, frow, y_mmq, mrow, (size_t) rows) : Err{}; + const Err e2 = compare(y_f, frow, ref2, pair, (size_t) rows); + std::printf(" fused vs the int8-rounded model (same activation / H rounding, double sums): rel RMS %.3e worst %.3e\n", + e2.rms, e2.worst); + if (e2.rms > 2e-3 || e2.worst > 3e-2) + throw std::runtime_error(std::string(p.name) + ": the fused path differs from its own arithmetic's model"); + if (mq) std::printf(" MMQ vs FP32 reference: rel RMS %.3e worst row max rel %.3e\n", em.rms, em.worst); std::printf(" fused vs FP32 reference: rel RMS %.3e worst row max rel %.3e\n", ef.rms, ef.worst); - std::printf(" fused vs MMQ : rel RMS %.3e worst row max rel %.3e\n", efm.rms, efm.worst); + if (mq) std::printf(" fused vs MMQ : rel RMS %.3e worst row max rel %.3e\n", efm.rms, efm.worst); double zmax = 0; for (int k = 0; k < K; ++k) for (int o = 0; o < N; ++o) zmax = std::max(zmax, (double) std::fabs(y_f[(size_t) slot[(size_t) (ZERO * K + k)] * N + o])); if (zmax != 0) throw std::runtime_error(std::string(p.name) + ": the all-zero token's outputs are not zero"); + if (!mq) { // no MMQ here: the int8 activations' own error (the IQ pairs' fused path sits at ~1e-2 rel RMS) + if (ef.rms > 0.03 || ef.worst > 0.25) + throw std::runtime_error(std::string(p.name) + ": the fused path's error against the reference is too large"); + return; + } if (ef.rms > 1.5 * em.rms || ef.worst > 2.0 * em.worst) throw std::runtime_error(std::string(p.name) + ": the fused path's error is not comparable to MMQ's"); } @@ -401,8 +445,10 @@ void timing_part(const Pair& p, int T, cudaStream_t s) { Dev x_dev(x.size() * 4), src_dev((size_t) rows * 4); ck(cudaMemcpy(x_dev.p, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x"); ck(cudaMemcpy(src_dev.p, r.src.data(), r.src.size() * 4, cudaMemcpyHostToDevice), "src"); + const bool mq = mmq_ok(p); mmq::Context ctx; - MmqBufs mb(p, rows, E); + MmqBufs* mbp = mq ? new MmqBufs(p, rows, E) : nullptr; + MmqBufs& mb = *mbp; // (only used when mq) FusedBufs fb(T, rows, E); ck(cudaMemcpy(fb.ids.p, ids.data(), ids.size() * 4, cudaMemcpyHostToDevice), "ids"); ck(cudaDeviceSynchronize(), "uploads"); // (see reference_part) @@ -420,7 +466,7 @@ void timing_part(const Pair& p, int T, cudaStream_t s) { }; auto mmq_run = [&] { run_mmq(p, geo, ctx, mb, r, x_dev.as(), src_dev.as(), blob, rows, s); }; auto fused_run = [&] { run_fused(p, geo, fb, x_dev.as(), T, E, {0, E}, blob, s); }; - const bool all_routed = std::count(r.cnt.begin(), r.cnt.end(), 0) == 0; + const bool all_routed = mq && std::count(r.cnt.begin(), r.cnt.end(), 0) == 0; auto direct_run = [&] { run_mmq(p, geo, ctx, mb, r, x_dev.as(), src_dev.as(), blob, rows, s, true, stride); }; @@ -446,7 +492,7 @@ void timing_part(const Pair& p, int T, cudaStream_t s) { } } // ~1 s of both first (the clocks ramp up), then alternating rounds; the medians - const bool no_mmq = std::getenv("S20_NOMMQ") != nullptr; // (debug: the fused runs alone) + const bool no_mmq = !mq || std::getenv("S20_NOMMQ") != nullptr; // (debug: the fused runs alone) for (float spent = 0; spent < 1000.0f;) spent += (no_mmq ? 0.0f : once(mmq_run)) + once(fused_run); std::vector tm, tf, td; for (int rep = 0; rep < 8; ++rep) { @@ -467,10 +513,11 @@ void timing_part(const Pair& p, int T, cudaStream_t s) { std::sort(tf2.begin(), tf2.end()); std::printf(" (fused back to back: median %.3f ms, min %.3f; alternating min %.3f; MMQ min %.3f)\n", tf2[4], tf2[0], tf[0], tm[0]); - const std::vector y_mmq = download(mb.dm, (size_t) rows * N), y_f = download(fb.dm, (size_t) rows * N); + const std::vector y_mmq = mq ? download(mb.dm, (size_t) rows * N) : std::vector((size_t) rows * N, 0.0f), + y_f = download(fb.dm, (size_t) rows * N); const std::vector slot = download_i(fb.slot, (size_t) rows); - const Err efm = compare(y_f, [&](size_t i) { return (int64_t) slot[i]; }, y_mmq, - [&](size_t i) { return (int64_t) r.row_of[i]; }, (size_t) rows); + const Err efm = mq ? compare(y_f, [&](size_t i) { return (int64_t) slot[i]; }, y_mmq, + [&](size_t i) { return (int64_t) r.row_of[i]; }, (size_t) rows) : Err{}; std::printf("%s - timing part: %d tokens x top %d over %d experts, one layer: MMQ path %.3f ms, fused %.3f ms " "(%.2fx); fused vs MMQ rel RMS %.3e worst row %.3e\n", p.name, T, K, E, t_mmq, t_f, t_mmq / t_f, efm.rms, efm.worst); @@ -560,18 +607,19 @@ void timing_part(const Pair& p, int T, cudaStream_t s) { for (int f = 0; f < FF; ++f) a += (double) wd[f] * h[(size_t) f]; ref[j * N + o] = (float) a; } - std::copy_n(y_mmq.begin() + (ptrdiff_t) ((size_t) r.row_of[i] * N), N, ym.begin() + (ptrdiff_t) (j * N)); + if (mq) std::copy_n(y_mmq.begin() + (ptrdiff_t) ((size_t) r.row_of[i] * N), N, ym.begin() + (ptrdiff_t) (j * N)); std::copy_n(y_f.begin() + (ptrdiff_t) ((size_t) slot[i] * N), N, yf.begin() + (ptrdiff_t) (j * N)); } auto id = [](size_t j) { return (int64_t) j; }; - const Err em = compare(ym, id, ref, id, pick.size()), ef = compare(yf, id, ref, id, pick.size()); + const Err em = mq ? compare(ym, id, ref, id, pick.size()) : Err{}, ef = compare(yf, id, ref, id, pick.size()); std::printf(" sample of %zu pairs vs FP32 reference: MMQ rel RMS %.3e worst %.3e, fused rel RMS %.3e worst " "%.3e\n", pick.size(), em.rms, em.worst, ef.rms, ef.worst); - if (ef.rms > 1.5 * em.rms || ef.worst > 2.0 * em.worst) + if (!mq ? (ef.rms > 0.03 || ef.worst > 0.25) : (ef.rms > 1.5 * em.rms || ef.worst > 2.0 * em.worst)) throw std::runtime_error(std::string(p.name) + ": the fused path's error is not comparable to MMQ's (timing)"); } cudaEventDestroy(a); cudaEventDestroy(b); + delete mbp; if (efm.rms > 0.05) throw std::runtime_error(std::string(p.name) + ": the paths disagree at the real shape"); } } // namespace @@ -582,6 +630,7 @@ int main(int argc, char** argv) { _putenv_s("STRATA_PF_FUSED", "1"); #else setenv("STRATA_PF_FUSED", "1", 1); + setenv("STRATA_PF_FUSED_KQ", "1", 1); // (the HIP build's Q4_K / Q5_K / Q5_1 / Q8_0 pairs) #endif int n = 0; if (cudaGetDeviceCount(&n) != cudaSuccess || n == 0) { std::printf("no CUDA device: skipped\n"); return 77; } @@ -590,7 +639,10 @@ int main(int argc, char** argv) { const std::vector pairs = { {GGML_TYPE_IQ2_S, GGML_TYPE_Q2_0, "IQ2_S / Q2_0"}, {GGML_TYPE_IQ2_XXS, GGML_TYPE_Q2_0, "IQ2_XXS / Q2_0"}, {GGML_TYPE_IQ2_XS, GGML_TYPE_IQ4_NL, "IQ2_XS / IQ4_NL"}, {GGML_TYPE_IQ3_XXS, GGML_TYPE_IQ4_NL, "IQ3_XXS / IQ4_NL"}, - {GGML_TYPE_IQ3_S, GGML_TYPE_IQ4_NL, "IQ3_S / IQ4_NL"}, {GGML_TYPE_IQ4_XS, GGML_TYPE_Q2_0, "IQ4_XS / Q2_0"}}; + {GGML_TYPE_IQ3_S, GGML_TYPE_IQ4_NL, "IQ3_S / IQ4_NL"}, {GGML_TYPE_IQ4_XS, GGML_TYPE_Q2_0, "IQ4_XS / Q2_0"}, + // (HIP only) UD-Q4_K_XL's: 47 layers Q4_K / Q5_1, 4 Q4_K / Q8_0, and the one Q5_K layer + {GGML_TYPE_Q4_K, GGML_TYPE_Q5_1, "Q4_K / Q5_1"}, {GGML_TYPE_Q4_K, GGML_TYPE_Q8_0, "Q4_K / Q8_0"}, + {GGML_TYPE_Q5_K, GGML_TYPE_Q5_1, "Q5_K / Q5_1"}, {GGML_TYPE_Q5_K, GGML_TYPE_Q8_0, "Q5_K / Q8_0"}}; const char* only = nullptr; // --only=NAME: the pairs whose name contains NAME for (int i = 1; i < argc; ++i) if (std::strncmp(argv[i], "--only=", 7) == 0) only = argv[i] + 7; @@ -611,14 +663,14 @@ int main(int argc, char** argv) { cudaStream_t s = nullptr; ck(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking), "stream"); for (const Pair& p : pairs) { - if (only && std::string(p.name).find(only) == std::string::npos) continue; + if (only ? std::string(p.name).find(only) == std::string::npos : p.gu == GGML_TYPE_Q4_K || p.gu == GGML_TYPE_Q5_K) continue; if (!fused::native_supported((int) p.gu, (int) p.d)) throw std::runtime_error(std::string(p.name) + ": not covered by the native kernels"); if (ref) reference_part(p, s); } if (timing) { // the IQ2_XS pack's layers (34 of 48 IQ2_S / Q2_0, 11 IQ2_XXS / Q2_0), the IQ3_S pack's most common, IQ3_XXS's - for (const Pair& p : {pairs[0], pairs[1], pairs[4], pairs[3]}) { + for (const Pair& p : only ? pairs : std::vector{pairs[0], pairs[1], pairs[4], pairs[3]}) { if (only && std::string(p.name).find(only) == std::string::npos) continue; for (int T : chunks) timing_part(p, T, s); } From 48994ee7a48761c3433ca9b8db8736e6de2c6567 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 4 Oct 2026 14:27:56 +0000 Subject: [PATCH 46/55] qsa_prompt_attn_parity: probe modes (QA_SAME, QA_DUMP) for the K/V sharing question --- src/kernels/qsa_prompt_attn_parity.cpp | 45 ++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/src/kernels/qsa_prompt_attn_parity.cpp b/src/kernels/qsa_prompt_attn_parity.cpp index 80c53859..8a236529 100644 --- a/src/kernels/qsa_prompt_attn_parity.cpp +++ b/src/kernels/qsa_prompt_attn_parity.cpp @@ -104,10 +104,55 @@ int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16 for (int64_t i = 0; i < nq; ++i) { const int64_t w = steps[i * k::kStepCount + k::kStepWidth], nkv = ctx - nq + i + 1; if (w == nkv) continue; + if (mode == 3 || mode == 4) { // 3: w random cells per query (no overlap beyond chance); 4: a 4-query group shares + // one random set of w - 512 cells (the union of 4 queries = 1x), the last 512 cells recent + std::mt19937 r3((unsigned) (mode == 3 ? i : i / 4) * 2654435761u + 7); + std::vector all((size_t) (nkv - 512)); + for (int64_t c = 0; c < nkv - 512; ++c) all[c] = (int32_t) c; + std::shuffle(all.begin(), all.end(), r3); + std::vector v(all.begin(), all.begin() + (w - 512)); + for (int64_t c = nkv - 512; c < nkv; ++c) v.push_back((int32_t) c); + std::sort(v.begin(), v.end()); + std::copy(v.begin(), v.end(), ids.data() + i * cap); + continue; + } const int64_t base = mode == 1 ? 0 : std::min(i / 4 * 64, nkv - w); for (int64_t c = 0; c < w; ++c) ids[i * cap + c] = (int32_t) (base + c); } } + // QA_DUMP= QA_LAYER=n (S23 probe): the engine's own selections (STRATA_QSA_DUMP records {layer, pos0, T, cap} + + // T*cap cells): the last record of that layer, whose T must be nq and pos0 + T ctx + if (const char* df = std::getenv("QA_DUMP")) { + const int want = std::getenv("QA_LAYER") ? std::atoi(std::getenv("QA_LAYER")) : 3; + std::FILE* f = std::fopen(df, "rb"); + if (!f) { std::fprintf(stderr, "QA_DUMP: cannot open\n"); std::exit(2); } + int32_t h[4]; + long at = -1; + while (std::fread(h, 4, 4, f) == 4) { + const long data = std::ftell(f); + if (h[0] == want && h[2] == nq && h[1] + h[2] == ctx && h[3] == cap) at = data; + std::fseek(f, (long) h[2] * h[3] * 4, SEEK_CUR); + } + if (at < 0) { std::fprintf(stderr, "QA_DUMP: no record for layer %d, T %lld, ctx %lld\n", want, (long long) nq, (long long) ctx); std::exit(2); } + std::fseek(f, at, SEEK_SET); + if (std::fread(ids.data(), 4, ids.size(), f) != ids.size()) std::exit(2); + std::fclose(f); + for (int grp : {2, 4, 8, 16}) { // the union of `grp` neighbouring queries' cells against grp x the width + double su = 0, sw = 0; + for (int64_t i0 = 0; i0 + grp <= nq; i0 += grp * 16) { + std::vector u; + for (int g2 = 0; g2 < grp; ++g2) { + const int64_t w = steps[(i0 + g2) * k::kStepCount + k::kStepWidth]; + u.insert(u.end(), ids.begin() + (i0 + g2) * cap, ids.begin() + (i0 + g2) * cap + w); + sw += (double) w; + } + std::sort(u.begin(), u.end()); + su += (double) (std::unique(u.begin(), u.end()) - u.begin()); + } + std::printf("QA_DUMP overlap: %d-query groups read %.2fx the cells of one query (%.1f%% of %d x)\n", grp, + su * grp / sw, 100.0 * su / sw, grp); + } + } 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); } From 609ce5a6452bfc055e121c1a1de33c9aa3d48e8a Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 4 Oct 2026 14:33:01 +0000 Subject: [PATCH 47/55] qsa_prompt_attn_parity: print a hash of the new kernel output bits --- src/kernels/qsa_prompt_attn_parity.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/kernels/qsa_prompt_attn_parity.cpp b/src/kernels/qsa_prompt_attn_parity.cpp index 8a236529..e1edc38b 100644 --- a/src/kernels/qsa_prompt_attn_parity.cpp +++ b/src/kernels/qsa_prompt_attn_parity.cpp @@ -182,6 +182,11 @@ int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16 std::vector 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"); + { // a hash of the new kernel's output bits (bitwise A/B of two builds / switches) + uint64_t hh = 1469598103934665603ull; + for (float x : nw) { uint32_t u; std::memcpy(&u, &x, 4); hh = (hh ^ u) * 1099511628211ull; } + std::printf("NEWHASH %016llx\n", (unsigned long long) hh); + } // 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(1, nq / 16)) { From d385870f772c6f5aa1ff76f35428b4d687003dda Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 4 Oct 2026 14:39:57 +0000 Subject: [PATCH 48/55] prefill: gfx11 native fused experts - sign-table decode and a flat weight buffer (down kernel 18% faster), bitwise native_w11_kernel: the sign bytes of the IQ2 / IQ3 grids come from a shared-memory table of byte masks ((g ^ m) + c per 4 bytes; no zero byte in any grid) instead of the compare / subtract emulation; the decoded weight stages are one flat shared buffer addressed through a pointer, which changes the code the compiler makes for the down kernel (7.5 -> 6.2 ms per 128-expert launch, IQ3_S / IQ4_NL, 16384 tokens). One layer of 16384 tokens, fused experts: IQ2_S 83.8 -> 76.3 ms, IQ2_XXS 74.4 -> 68.9, IQ3_S 78.5 -> 73.8, IQ3_XXS 77.6 -> 71.8. Outputs are bit for bit the same (the test now prints a hash of the fused output in pair order). --- src/prefill/moe_fused_iq.cu | 53 ++++++++++++++++++++++++++-- tests/cuda/prefill_fused_iq_test.cpp | 6 ++++ 2 files changed, 56 insertions(+), 3 deletions(-) diff --git a/src/prefill/moe_fused_iq.cu b/src/prefill/moe_fused_iq.cu index 72c278d7..88ef0391 100644 --- a/src/prefill/moe_fused_iq.cu +++ b/src/prefill/moe_fused_iq.cu @@ -164,6 +164,25 @@ __device__ __forceinline__ void signed8(uint32_t gx, uint32_t gy, uint32_t s, ui qx = __vsub4(gx ^ m0, m0); qy = __vsub4(gy ^ m1, m1); } +#if defined(__HIPCC__) +// gfx11 (Aurora): the signs from a shared-memory table instead of the compare / subtract emulation. An entry (one per +// sign byte b; for the 7-bit sign formats per 7 bits, the parity bit folded in) is {m0, c0, m1, c1}: m = 0xFF in the +// bytes whose sign bit is set (bits 0-3 for .x, 4-7 for .y), c = m & 0x01010101. q = (g ^ m) + c is -g where the sign +// is set - the two's complement, byte-wise - and g elsewhere; no byte carries into the next, because no codebook entry +// has a zero byte (256 - g with g in 1..127; the grids' bytes are 1..62), so it is the bytes signed8 gives. +__device__ __forceinline__ void signed8t(uint32_t gx, uint32_t gy, const uint4 sg, uint32_t& qx, uint32_t& qy) { + qx = (gx ^ sg.x) + sg.y; + qy = (gy ^ sg.z) + sg.w; +} +__host__ __device__ constexpr int sign_entries(int t) { return t == T_IQ2_S || t == T_IQ3_S ? 256 : 128; } +__device__ __forceinline__ uint4 sign_entry(int i, bool parity) { + uint32_t b = (uint32_t) i; + if (parity) b ^= (__popc(b) & 1) << 7; + const uint32_t m0 = __vcmpne4(((b & 15) * 0x01010101u) & 0x08040201u, 0), + m1 = __vcmpne4(((b >> 4) * 0x01010101u) & 0x08040201u, 0); + return make_uint4(m0, m0 & 0x01010101u, m1, m1 & 0x01010101u); +} +#endif // 8 nibbles of q4 through a 16-entry int8 table (4 words): the low nibbles' values in .x, the high ones' in .y __device__ __forceinline__ void table16(uint32_t q4, const uint32_t (&t)[4], uint32_t& lo, uint32_t& hi) { uint32_t tmp[2]; @@ -210,13 +229,17 @@ template __device__ __forceinline__ void load_unit(const uint8_t* bp, in // The sub-block as 32 int8 (q[0..7], natural order) and its scales (s0: values 0-15, s1: 16-31). template __device__ __forceinline__ void convert(const uint32_t (&w)[5], const uint8_t* grid, const uint32_t (&kv)[4], - uint32_t (&q)[8], float& s0, float& s1) { + uint32_t (&q)[8], float& s0, float& s1, const uint4* sgn = nullptr) { if constexpr (T == T_IQ2_XXS) { const uint2* g = (const uint2*) grid; #pragma unroll for (int l = 0; l < 4; ++l) { const uint2 e = g[(w[0] >> (8 * l)) & 255]; +#if defined(__HIPCC__) + signed8t(e.x, e.y, sgn[(w[1] >> (7 * l)) & 127], q[2 * l], q[2 * l + 1]); +#else signed8(e.x, e.y, unpack_ksigns(w[1] >> (7 * l)), q[2 * l], q[2 * l + 1]); +#endif } s0 = s1 = half_at(w[2]) * (float) ((w[1] >> 27) | 1) * 0.125f; } else if constexpr (T == T_IQ2_XS) { @@ -225,7 +248,11 @@ __device__ __forceinline__ void convert(const uint32_t (&w)[5], const uint8_t* g for (int l = 0; l < 4; ++l) { const uint32_t c = (w[l >> 1] >> (16 * (l & 1))) & 0xFFFF; const uint2 e = g[c & 511]; +#if defined(__HIPCC__) + signed8t(e.x, e.y, sgn[(c >> 9) & 127], q[2 * l], q[2 * l + 1]); +#else signed8(e.x, e.y, unpack_ksigns(c >> 9), q[2 * l], q[2 * l + 1]); +#endif } const float d = half_at(w[2]); const uint32_t sc = w[2] >> 16; @@ -237,7 +264,11 @@ __device__ __forceinline__ void convert(const uint32_t (&w)[5], const uint8_t* g #pragma unroll for (int l = 0; l < 4; ++l) { const uint2 e = g[((w[0] >> (8 * l)) & 255) | ((qh << (8 - 2 * l)) & 0x300)]; +#if defined(__HIPCC__) + signed8t(e.x, e.y, sgn[(w[1] >> (8 * l)) & 255], q[2 * l], q[2 * l + 1]); +#else signed8(e.x, e.y, ((w[1] >> (8 * l)) & 255) * 0x01010101u, q[2 * l], q[2 * l + 1]); +#endif } const float d = half_at(w[2]); const uint32_t sc = w[2] >> 24; @@ -248,7 +279,11 @@ __device__ __forceinline__ void convert(const uint32_t (&w)[5], const uint8_t* g #pragma unroll for (int l = 0; l < 4; ++l) { const uint32_t i0 = (w[l >> 1] >> (16 * (l & 1))) & 255, i1 = (w[l >> 1] >> (16 * (l & 1) + 8)) & 255; +#if defined(__HIPCC__) + signed8t(g[i0], g[i1], sgn[(w[2] >> (7 * l)) & 127], q[2 * l], q[2 * l + 1]); +#else signed8(g[i0], g[i1], unpack_ksigns(w[2] >> (7 * l)), q[2 * l], q[2 * l + 1]); +#endif } s0 = s1 = half_at(w[3]) * (float) (2 * (w[2] >> 28) + 1) * 0.25f; } else if constexpr (T == T_IQ3_S) { @@ -257,8 +292,13 @@ __device__ __forceinline__ void convert(const uint32_t (&w)[5], const uint8_t* g #pragma unroll for (int l = 0; l < 4; ++l) { const uint32_t i0 = (w[l >> 1] >> (16 * (l & 1))) & 255, i1 = (w[l >> 1] >> (16 * (l & 1) + 8)) & 255; +#if defined(__HIPCC__) + signed8t(g[i0 | ((qh << (8 - 2 * l)) & 256)], g[i1 | ((qh << (7 - 2 * l)) & 256)], + sgn[(w[2] >> (8 * l)) & 255], q[2 * l], q[2 * l + 1]); +#else signed8(g[i0 | ((qh << (8 - 2 * l)) & 256)], g[i1 | ((qh << (7 - 2 * l)) & 256)], ((w[2] >> (8 * l)) & 255) * 0x01010101u, q[2 * l], q[2 * l + 1]); +#endif } s0 = s1 = half_at(w[3]) * (float) (1 + 2 * (w[3] >> 24)); } else if constexpr (T == T_IQ4_XS || T == T_IQ4_NL) { @@ -554,9 +594,13 @@ native_w11_kernel(const Batch b, const NativeGeom geo, const Tables tb, const ui constexpr int BS = block_bytes(WT); constexpr bool K16 = per16(WT); constexpr int GB = grid_bytes(WT) > 0 ? grid_bytes(WT) : 16; - __shared__ __align__(16) uint8_t wt[2][NW_ROWS][WLD]; // decoded int8 weights of a stage (64 + 16 pad) + __shared__ __align__(16) uint8_t wtbuf[2 * NW_ROWS * WLD]; + uint8_t(*wt)[NW_ROWS][WLD] = reinterpret_cast(wtbuf); __shared__ __align__(16) float ws[2][NW_ROWS][4]; // their scales per 16 values __shared__ __align__(16) uint8_t sgrid[GB]; + constexpr int SGN = (WT == T_IQ2_XXS || WT == T_IQ2_XS || WT == T_IQ2_S || WT == T_IQ3_XXS || WT == T_IQ3_S) + ? sign_entries(WT) : 1; + __shared__ __align__(16) uint4 ssign[SGN]; // the signs of a sign byte, as byte masks __shared__ int srow[kTileRows]; __shared__ float hs[GU ? kTileRows : 1][GU ? 65 : 1]; const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; @@ -565,6 +609,9 @@ native_w11_kernel(const Batch b, const NativeGeom geo, const Tables tb, const ui const uint32_t* gs = (const uint32_t*) grid_src(); for (int i = tid; i < grid_bytes(WT) / 4; i += NW_THREADS) ((uint32_t*) sgrid)[i] = gs[i]; } + if constexpr (SGN > 1) { + for (int i = tid; i < SGN; i += NW_THREADS) ssign[i] = sign_entry(i, SGN == 128); + } uint32_t kv[4] = {0, 0, 0, 0}; if constexpr (WT == T_IQ4_XS || WT == T_IQ4_NL) { #pragma unroll @@ -587,7 +634,7 @@ native_w11_kernel(const Batch b, const NativeGeom geo, const Tables tb, const ui auto put = [&](const uint32_t (&raw)[5], int buf) { uint32_t q[8]; float s0, s1; - convert(raw, sgrid, kv, q, s0, s1); + convert(raw, sgrid, kv, q, s0, s1, ssign); uint4* d = (uint4*) &wt[buf][ur][32 * uj]; d[0] = make_uint4(q[0], q[1], q[2], q[3]); d[1] = make_uint4(q[4], q[5], q[6], q[7]); diff --git a/tests/cuda/prefill_fused_iq_test.cpp b/tests/cuda/prefill_fused_iq_test.cpp index d436a605..bac1e979 100644 --- a/tests/cuda/prefill_fused_iq_test.cpp +++ b/tests/cuda/prefill_fused_iq_test.cpp @@ -469,6 +469,12 @@ void timing_part(const Pair& p, int T, cudaStream_t s) { tf2[0], tf[0], tm[0]); const std::vector y_mmq = download(mb.dm, (size_t) rows * N), y_f = download(fb.dm, (size_t) rows * N); const std::vector slot = download_i(fb.slot, (size_t) rows); + { // (Aurora S23) a hash of the fused output's bits, to compare two builds bit for bit + uint64_t hsh = 1469598103934665603ull; + for (size_t i = 0; i < (size_t) rows; ++i) // in pair order: the rows of an expert are placed in any order + for (size_t c = 0; c < (size_t) N; ++c) { uint32_t u; std::memcpy(&u, &y_f[(size_t) slot[i] * N + c], 4); hsh = (hsh ^ u) * 1099511628211ull; } + std::printf(" fused output bits hash %016llx\n", (unsigned long long) hsh); + } const Err efm = compare(y_f, [&](size_t i) { return (int64_t) slot[i]; }, y_mmq, [&](size_t i) { return (int64_t) r.row_of[i]; }, (size_t) rows); std::printf("%s - timing part: %d tokens x top %d over %d experts, one layer: MMQ path %.3f ms, fused %.3f ms " From 04e1e11afb45c040960e90c834e0fe85a475a4ab Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 4 Oct 2026 15:31:16 +0000 Subject: [PATCH 49/55] HIP: grouped decode experts for UD-Q4_K_XL (Q4_K/Q5_K gate/up, Q5_1/Q8_0 down), bitwise, opt-in STRATA_EXPERT_V2K=1 S26 structure (4 rows per warp, activations in LDS, fused SwiGLU+q8, optional TSUM) over S27::load/apply splits of the existing vec_dot functions. --- src/kernels/cuda/iq_kernels.cu | 333 +++++++++++++++++++++++++++++++++ 1 file changed, 333 insertions(+) diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index 46a07dfe..f7474948 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -1646,6 +1646,324 @@ void s26_launch_l(const NativeExpertLayout& L, int64_t cap_groups, cudaStream_t const dim3 gd((unsigned) (L.n_embd / (8 * RD)), (unsigned) cap_groups); s26_down_l_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); } +// ---------------------------------------------------------------- stream B: UD-Q4_K_XL grouped decode experts +// STRATA_EXPERT_V2K=1: s26_gu_l_kernel / s26_down_l_kernel's structure (4 interleaved rows per warp, the chunk's q8_1 +// activation rows in LDS, SwiGLU + q8_1 fused, optionally STRATA_TSUM's transposed butterfly) for Q4_K / Q5_K gate/up +// and Q5_1 / Q8_0 down, which otherwise run native_gu_kernel / native_down_kernel (one entry at a time, the weight +// words re-read per column). Each Fmt::dot is split into S27::load (everything that depends on the weight) and +// apply (the activation words and the same integer / float expression), the same impl functions, so a row's lane-strided +// k order, its terms and warp_sum are the old kernels': every output is bitwise the old one's (iq harness, memcmp). +template struct S27; +template<> struct S27<12> { // Q4_K + struct W { int v[2]; uint16_t aux[2]; half2 dm; }; + __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { + const block_q4_K* b = (const block_q4_K*) vbq + kbx; + W r; + const int bq8_offset = QR4_K * ((iqs / 2) / (QI8_1 / 2)); + const int* q4 = (const int*) (b->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4)); + r.v[0] = q4[0]; + r.v[1] = q4[4]; + k_scale_min(b->scales, bq8_offset, r.aux); + r.dm = b->dm; + return r; + } + __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { + const int bq8_offset = QR4_K * ((iqs / 2) / (QI8_1 / 2)); + int u[2 * QR4_K]; + float d8[QR4_K]; +#pragma unroll + for (int i = 0; i < QR4_K; ++i) { + const block_q8_1* bq8i = bq8_1 + bq8_offset + i; + d8[i] = __low2float(bq8i->ds); + const int* q8 = (const int*) bq8i->qs + ((iqs / 2) % 4); + u[2 * i + 0] = q8[0]; + u[2 * i + 1] = q8[4]; + } + const uint8_t* sc = (const uint8_t*) r.aux; + const uint8_t* m = sc + 2; + return vec_dot_q4_K_q8_1_impl_vmmq(r.v, u, sc, m, r.dm, d8); + } +}; +template<> struct S27<13> { // Q5_K + struct W { int vl[2]; int vh[2]; uint16_t aux[2]; half2 dm; }; + __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { + const block_q5_K* b = (const block_q5_K*) vbq + kbx; + W r; + const int bq8_offset = QR5_K * ((iqs / 2) / (QI8_1 / 2)); + const int* ql = (const int*) (b->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4)); + const int* qh = (const int*) (b->qh + 4 * ((iqs / 2) % 4)); + r.vl[0] = ql[0]; + r.vl[1] = ql[4]; + r.vh[0] = qh[0] >> bq8_offset; + r.vh[1] = qh[4] >> bq8_offset; + k_scale_min(b->scales, bq8_offset, r.aux); + r.dm = b->dm; + return r; + } + __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { + const int bq8_offset = QR5_K * ((iqs / 2) / (QI8_1 / 2)); + int u[2 * QR5_K]; + float d8[QR5_K]; +#pragma unroll + for (int i = 0; i < QR5_K; ++i) { + const block_q8_1* bq8i = bq8_1 + bq8_offset + i; + d8[i] = __low2float(bq8i->ds); + const int* q8 = (const int*) bq8i->qs + ((iqs / 2) % 4); + u[2 * i + 0] = q8[0]; + u[2 * i + 1] = q8[4]; + } + const uint8_t* sc = (const uint8_t*) r.aux; + const uint8_t* m = sc + 2; + return vec_dot_q5_K_q8_1_impl_vmmq(r.vl, r.vh, u, sc, m, r.dm, d8); + } +}; +template<> struct S27<7> { // Q5_1 + struct W { int vl[VDR_Q5_1]; int qh; half2 dm; }; + __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { + const block_q5_1* b = (const block_q5_1*) vbq + kbx; + W r; +#pragma unroll + for (int i = 0; i < VDR_Q5_1; ++i) r.vl[i] = get_int_b4(b->qs, iqs + i); + r.qh = get_int_b4(b->qh, 0); + r.dm = b->dm; + return r; + } + __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { + int sumi = 0, sumu = 0; +#pragma unroll + for (int i = 0; i < VDR_Q5_1; ++i) { + const int vl = r.vl[i]; + const int vh = r.qh >> (4 * (iqs + i)); + const int u0 = get_int_b4(bq8_1->qs, iqs + i), u1 = get_int_b4(bq8_1->qs, iqs + i + QI5_1); + int vi0 = (vl >> 0) & 0x0F0F0F0F; + vi0 |= (vh << 4) & 0x00000010; + vi0 |= (vh << 11) & 0x00001000; + vi0 |= (vh << 18) & 0x00100000; + vi0 |= (vh << 25) & 0x10000000; + sumi = ggml_cuda_dp4a(vi0, u0, sumi); + int vi1 = (vl >> 4) & 0x0F0F0F0F; + vi1 |= (vh >> 12) & 0x00000010; + vi1 |= (vh >> 5) & 0x00001000; + vi1 |= (vh << 2) & 0x00100000; + vi1 |= (vh << 9) & 0x10000000; + sumi = ggml_cuda_dp4a(vi1, u1, sumi); + sumu = ggml_cuda_dp4a(0x01010101, u1, ggml_cuda_dp4a(0x01010101, u0, sumu)); + } + const float2 dm5 = __half22float2(r.dm); + const float d8 = __low2float(bq8_1->ds); + return sumi * (dm5.x * d8) + sumu * (dm5.y * d8); + } +}; +template<> struct S27<8> { // Q8_0 + struct W { int q[VDR_Q8_0]; float d; }; + __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { + const block_q8_0* b = (const block_q8_0*) vbq + kbx; + W r; +#pragma unroll + for (int i = 0; i < VDR_Q8_0; ++i) r.q[i] = get_int_b2(b->qs, iqs + i); + r.d = __half2float(b->d); + return r; + } + __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { + int sumi = 0; +#pragma unroll + for (int i = 0; i < VDR_Q8_0; ++i) sumi = ggml_cuda_dp4a(r.q[i], get_int_b4(bq8_1->qs, iqs + i), sumi); + const float d8_1 = __low2float(bq8_1->ds); + return r.d * d8_1 * ((float) sumi); + } +}; + +template +__global__ void __launch_bounds__(256) s27_gu_kernel(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_tok, + const block_q8_1* __restrict__ xq, NativeExpertLayout L, + float* __restrict__ gate, float* __restrict__ up) { + using F = Fmt; + using S = S27; + __shared__ block_q8_1 s_x[LX ? GRP_NC * S26_XMAX : 1]; + const int g = blockIdx.y; + if (g >= *n_groups) return; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int row0 = blockIdx.x * GU_ROWS * RPW + warp; + const bool live = row0 + GU_ROWS * (RPW - 1) < 2 * L.n_ff; + const uint8_t* blob = (const uint8_t*) grp_ptr[g]; + const uint8_t* wr[RPW]; + int rr[RPW]; + bool upq[RPW]; +#pragma unroll + for (int q = 0; q < RPW; ++q) { + const int row = row0 + q * GU_ROWS; + upq[q] = row >= L.n_ff; + rr[q] = upq[q] ? row - (int) L.n_ff : row; + wr[q] = blob + (upq[q] ? L.up_off : 0) + (size_t) rr[q] * L.gu_row; + } + const int nb = (int) (L.n_embd / F::qk), xb = (int) (L.n_embd / 32); + const int e0 = grp_start[g], e1 = grp_start[g + 1]; + for (int e = e0; e < e1; e += GRP_NC) { + const int n = min(GRP_NC, e1 - e); + const block_q8_1* xbase = xq; + int off[GRP_NC]; + if constexpr (LX) { + __syncthreads(); // the previous chunk is done with s_x + for (int i = threadIdx.x; i < n * xb; i += 256) { + const int c = i / xb, j = i - c * xb; + s_x[c * S26_XMAX + j] = xq[(size_t) ent_tok[e + c] * xb + j]; + } +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) off[c] = min(c, n - 1) * S26_XMAX; + xbase = s_x; + __syncthreads(); + } else { +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) off[c] = ent_tok[e + min(c, n - 1)] * xb; + } + if (!live) continue; + float s[RPW][GRP_NC]; +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) s[q][c] = 0.0f; + for (int k = lane; k < nb * F::ipb; k += 32) { + const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb); + typename S::W w[RPW]; +#pragma unroll + for (int q = 0; q < RPW; ++q) w[q] = S::load(wr[q], kbx, iqs); +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n) s[q][c] += S::apply(w[q], xbase + off[c] + kbx * (F::qk / 32), iqs); + } + if constexpr (TS) { + constexpr int P = s26ts::pow2_ceil(RPW * GRP_NC); + float v[P]; +#pragma unroll + for (int j = 0; j < P; ++j) v[j] = j < RPW * GRP_NC ? s[j / GRP_NC][j % GRP_NC] : 0.0f; + const float sum = s26ts::tsum

(v, lane); + const int j = s26ts::tsum_token

(lane); + if (lane == s26ts::tsum_lane

(j) && j < RPW * GRP_NC) { + const int c = j % GRP_NC; +#pragma unroll + for (int q = 0; q < RPW; ++q) + if (j / GRP_NC == q && c < n) (upq[q] ? up : gate)[(size_t) (e + c) * L.n_ff + rr[q]] = sum; + } + continue; + } +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n) s[q][c] = warp_sum(s[q][c]); +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n && lane == c) (upq[q] ? up : gate)[(size_t) (e + c) * L.n_ff + rr[q]] = s[q][c]; + } +} + +template +__global__ void __launch_bounds__(256) s27_down_kernel(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_dst, + const block_q8_1* __restrict__ hq, NativeExpertLayout L, + float* __restrict__ out) { + using F = Fmt; + using S = S27; + __shared__ block_q8_1 s_h[LX ? GRP_NC * S26_HMAX : 1]; + const int g = blockIdx.y; + if (g >= *n_groups) return; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int r0 = blockIdx.x * 8 * RPW + warp; + const bool live = r0 + 8 * (RPW - 1) < L.n_embd; + const uint8_t* blob = (const uint8_t*) grp_ptr[g]; + const uint8_t* wr[RPW]; +#pragma unroll + for (int q = 0; q < RPW; ++q) wr[q] = blob + L.down_off + (size_t) (r0 + 8 * q) * L.d_row; + const int nb = (int) (L.n_ff / F::qk), hb = (int) (L.n_ff / 32); + const int e0 = grp_start[g], e1 = grp_start[g + 1]; + for (int e = e0; e < e1; e += GRP_NC) { + const int n = min(GRP_NC, e1 - e); + const block_q8_1* hbase = hq; + int off[GRP_NC]; + if constexpr (LX) { + __syncthreads(); + for (int i = threadIdx.x; i < n * hb; i += 256) { + const int c = i / hb, j = i - c * hb; + s_h[c * S26_HMAX + j] = hq[(size_t) (e + c) * hb + j]; + } + __syncthreads(); +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) off[c] = min(c, n - 1) * S26_HMAX; + hbase = s_h; + } else { +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) off[c] = (e + min(c, n - 1)) * hb; + } + if (!live) continue; + float s[RPW][GRP_NC]; +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) s[q][c] = 0.0f; + for (int k = lane; k < nb * F::ipb; k += 32) { + const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb); + typename S::W w[RPW]; +#pragma unroll + for (int q = 0; q < RPW; ++q) w[q] = S::load(wr[q], kbx, iqs); +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n) s[q][c] += S::apply(w[q], hbase + off[c] + kbx * (F::qk / 32), iqs); + } + if constexpr (TS) { + constexpr int P = s26ts::pow2_ceil(RPW * GRP_NC); + float v[P]; +#pragma unroll + for (int j = 0; j < P; ++j) v[j] = j < RPW * GRP_NC ? s[j / GRP_NC][j % GRP_NC] : 0.0f; + const float sum = s26ts::tsum

(v, lane); + const int j = s26ts::tsum_token

(lane); + const int q = j / GRP_NC, c = j % GRP_NC; + if (lane == s26ts::tsum_lane

(j) && j < RPW * GRP_NC && c < n) + out[(size_t) ent_dst[e + c] * L.n_embd + r0 + 8 * q] = sum; + continue; + } +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n) s[q][c] = warp_sum(s[q][c]); +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n && lane == c) out[(size_t) ent_dst[e + c] * L.n_embd + r0 + 8 * q] = s[q][c]; + } +} + +template +void s27_launch(const NativeExpertLayout& L, int64_t cap_groups, cudaStream_t s, const unsigned long long* grp_ptr, + const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_dst, const int32_t* ent_tok, + const block_q8_1* X, float* gate, float* up, float* h, block_q8_1* hq, float* out, long long nh) { + const dim3 ggu((unsigned) (2 * L.n_ff / (GU_ROWS * RG)), (unsigned) cap_groups); + s27_gu_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); + s26_swiglu_q8_1_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(gate, up, h, hq, nh); + const dim3 gd((unsigned) (L.n_embd / (8 * RD)), (unsigned) cap_groups); + s27_down_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); +} +template +void s27_launch_ts(bool ts, const NativeExpertLayout& L, int64_t cap_groups, cudaStream_t s, + const unsigned long long* grp_ptr, const int32_t* grp_start, const int32_t* n_groups, + const int32_t* ent_dst, const int32_t* ent_tok, const block_q8_1* X, float* gate, float* up, float* h, + block_q8_1* hq, float* out, long long nh) { + if (ts) s27_launch(L, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, X, gate, up, h, hq, out, nh); + else s27_launch(L, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, X, gate, up, h, hq, out, nh); +} + template void launch_gu(dim3 grid, cudaStream_t s, const unsigned long long* grp_ptr, const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_tok, const block_q8_1* X, const NativeExpertLayout& L, @@ -1803,6 +2121,21 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long check("native_expert_grouped (v2)"); return; } + // stream B: UD-Q4_K_XL's Q4_K / Q5_K gate/up and Q5_1 / Q8_0 down (see S27 above) + static const bool v2k = [] { const char* v = std::getenv("STRATA_EXPERT_V2K"); return v && v[0] == '1'; }(); + if (v2k && (L.gu_type == 12 || L.gu_type == 13) && (L.d_type == 7 || L.d_type == 8) && L.n_embd == 2560 && + L.n_ff == 640) { + static const bool ts = [] { const char* v = std::getenv("STRATA_TSUM"); return v && v[0] == '1'; }(); + const long long nh = (long long) cap_entries * L.n_ff; +#define STRATA_V2K(G, D) s27_launch_ts(ts, L, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, X, gate, up, h, hq, out, nh) + if (L.gu_type == 12 && L.d_type == 7) STRATA_V2K(12, 7); + else if (L.gu_type == 12) STRATA_V2K(12, 8); + else if (L.d_type == 7) STRATA_V2K(13, 7); + else STRATA_V2K(13, 8); +#undef STRATA_V2K + check("native_expert_grouped (v2k)"); + return; + } const dim3 ggu((unsigned) ((2 * L.n_ff + GU_ROWS - 1) / GU_ROWS), (unsigned) cap_groups); switch (L.gu_type) { #define STRATA_GU(T) case T: launch_gu(ggu, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; From 9668e32400b871bac9f36003170738723705adce Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 4 Oct 2026 17:38:17 +0000 Subject: [PATCH 50/55] prefill: STRATA_GDN_CONVL2=1 (conv + q/k L2 norm in one kernel) and STRATA_GDN_NOY=1 (no dead FP32 write), bitwise STRATA_GDN_CONVL2: gdn_conv_tiled_kernel with gdn_l2_kernel folded in (a block's 128 threads are one head's channels): the tile's conv loop verbatim, then the sum of squares spelled out as the compiler built the l2 kernel (first xor step an fma on the partner's rounded square, then adds), the four partials in the same order, the same v * rsqrtf(ss+eps). 16K chunk, per layer: 9.13 ms -> 6.95 ms. A first version keeping the values in registers differed by 1 ulp in the silu (different code shape); this one keeps the tiled loop as is. STRATA_GDN_NOY: the norm kernel does not store the FP32 y nothing reads (403 MB per 16K chunk and layer); the FP16 value is made with v_fma_mixlo_f16, the instruction the compiler used next to the store (otherwise a mul and a convert round twice and 1 ulp of the FP16 results differ). Engine ids match the unchanged binary at 8K (acd9c8328408). --- src/prefill/kernels.cu | 80 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 74 insertions(+), 6 deletions(-) diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 6ee42ef3..39dc70dd 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -315,6 +315,46 @@ __global__ void gdn_conv_tiled_kernel(const float* __restrict__ hist, const floa v0 = v1; v1 = v2; v2 = x; } } +// Aurora (S23, opt-in STRATA_GDN_CONVL2=1): gdn_conv_tiled_kernel with gdn_l2_kernel folded in. A block's 128 threads +// are the 128 channels of one head, so for the q / k heads (block < 2 HK) the norm's sum of squares is the block's: +// the same warp_sum, the same four partials added in the same order, the same v * rsqrtf(ss + eps) on the same +// stored value - the same bits, without writing h and reading it back (16 tokens per round). +__global__ void gdn_conv_l2_kernel(const float* __restrict__ hist, const float* __restrict__ qkv, + const float* __restrict__ w, float* __restrict__ h, int64_t T, float eps) { + const int c = blockIdx.x * blockDim.x + threadIdx.x; + const int64_t t0 = (int64_t) blockIdx.y * CONV_TILE; + if (t0 >= T) return; + const int64_t t1 = t0 + CONV_TILE < T ? t0 + CONV_TILE : T; + auto input = [&](int64_t t) -> float { return t >= 0 ? qkv[t * C + c] : hist[c * 3 + (int) (t + 3)]; }; + float v0 = input(t0 - 3), v1 = input(t0 - 2), v2 = input(t0 - 1); + const float w0 = w[c * 4], w1 = w[c * 4 + 1], w2 = w[c * 4 + 2], w3 = w[c * 4 + 3]; + for (int64_t t = t0; t < t1; ++t) { // gdn_conv_tiled_kernel's loop, verbatim + const float x = qkv[t * C + c]; + const float s = v0 * w0 + v1 * w1 + v2 * w2 + x * w3; + h[t * C + c] = s / (1.0f + __expf(-s)); + v0 = v1; v1 = v2; v2 = x; + } + if (blockIdx.x >= 2 * HK) return; // v channels: no norm + __shared__ float part[16][4]; + for (int64_t tb = t0; tb < t1; tb += 16) { + const int n = (int) (t1 - tb < 16 ? t1 - tb : 16); + for (int j = 0; j < n; ++j) { // (each thread reads back its own stored value) + const float v = h[(tb + j) * C + c]; + // gdn_l2_kernel as the compiler built it: the first xor step adds the partner's rounded square to an + // unrounded own one (an fma), the other steps are plain adds - spelled out so no contraction can differ + float sq = __fmaf_rn(v, v, __shfl_xor_sync(0xffffffffu, __fmul_rn(v, v), 16)); +#pragma unroll + for (int o = 8; o > 0; o >>= 1) sq = __fadd_rn(sq, __shfl_xor_sync(0xffffffffu, sq, o)); + if ((threadIdx.x & 31) == 0) part[j][threadIdx.x >> 5] = sq; + } + __syncthreads(); + for (int j = 0; j < n; ++j) { + const float ss = part[j][0] + part[j][1] + part[j][2] + part[j][3]; + h[(tb + j) * C + c] = h[(tb + j) * C + c] * rsqrtf(ss + eps); + } + __syncthreads(); + } +} // the history after the chunk: its last three inputs (the older history where the chunk is shorter than 3) __global__ void gdn_conv_hist_kernel(float* __restrict__ hist, const float* __restrict__ qkv, int64_t T) { const int c = blockIdx.x * blockDim.x + threadIdx.x; @@ -620,6 +660,7 @@ __global__ void __launch_bounds__(QTH) gdn_rec_quad_kernel(float* __restrict__ s // gdn_out_norm_kernel's body over a grid-stride walk of the (token, head) rows: the old kernel launched a 128-thread // block per row (T * 48 blocks; ~45 GB/s on the 8060S). The same code per row (the same compiled arithmetic: a wave // per row with four values per lane rounded differently in its first xor step). +template __global__ void __launch_bounds__(S) gdn_out_norm_loop_kernel(const float* __restrict__ z, const float* __restrict__ gamma, float eps, float* __restrict__ y, uint16_t* __restrict__ y16, int64_t rows, int64_t ld16) { @@ -628,14 +669,28 @@ __global__ void __launch_bounds__(S) gdn_out_norm_loop_kernel(const float* __res for (int64_t row = blockIdx.x; row < rows; row += gridDim.x) { const size_t at = (size_t) row * S + col; const float oc = y[at]; - float sp = warp_sum(oc * oc); + // (warp_sum as the compiler built it: the first xor step adds the partner's rounded square to an unrounded own + // one, an fma; spelled out so neither instance's contraction can differ) + float sp = __fmaf_rn(oc, oc, __shfl_xor_sync(0xffffffffu, __fmul_rn(oc, oc), 16)); +#pragma unroll + for (int o = 8; o > 0; o >>= 1) sp = __fadd_rn(sp, __shfl_xor_sync(0xffffffffu, sp, o)); __syncthreads(); // the previous row's sums are read if ((col & 31) == 0) wsum[col >> 5] = sp; __syncthreads(); const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3]; - const float v = oc * rsqrtf(ss / (float) S + eps) * gamma[col] * sigm(z[at]); - y[at] = v; - y16[(size_t) (row / HV) * ld16 + (size_t) (row % HV) * S + col] = hf(v); + const float bp = oc * rsqrtf(ss / (float) S + eps) * gamma[col], sg = sigm(z[at]); + const size_t o16 = (size_t) (row / HV) * ld16 + (size_t) (row % HV) * S + col; + if constexpr (WY) { + const float v = bp * sg; + y[at] = v; + y16[o16] = hf(v); + } else { + // STRATA_GDN_NOY=1: nothing reads the FP32 result (403 MB per 16K chunk). The FP16 value is what the + // compiler makes of hf(v) next to the store: v_fma_mixlo_f16, the product rounded to FP16 once + unsigned r; + asm("v_fma_mixlo_f16 %0, %1, %2, 0" : "=v"(r) : "v"(sg), "v"(bp)); + y16[o16] = (uint16_t) r; + } } } __global__ void __launch_bounds__(S) gdn_out_norm_kernel(const float* __restrict__ z, const float* __restrict__ gamma, @@ -1040,6 +1095,14 @@ void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, i if (serial || T <= CONV_TILE) { gdn_conv_kernel<<>>(history, qkv, conv_w, h, T); } else { + static const bool fused = [] { const char* v = std::getenv("STRATA_GDN_CONVL2"); return v && std::atoi(v) != 0; }(); + if (fused) { + gdn_conv_l2_kernel<<>>(history, qkv, conv_w, h, T, eps); + gdn_conv_hist_kernel<<>>(history, qkv, T); + check("gdn_conv"); + return; + } gdn_conv_tiled_kernel<<>>(history, qkv, conv_w, h, T); gdn_conv_hist_kernel<<>>(history, qkv, T); @@ -1061,8 +1124,13 @@ void gdn_recurrence_variant(int variant, float* state, const float* h, const flo if (variant == 1) { if (T > 0) { gdn_rec_quad_kernel<<>>(state, h, gate, beta, y, T); - gdn_out_norm_loop_kernel<<<(unsigned) std::min(T * HV, 4096), S, 0, (cudaStream_t) stream>>>( - z, gamma, eps, y, y16, T * HV, ld16); + static const bool noy = [] { const char* v = std::getenv("STRATA_GDN_NOY"); return v && std::atoi(v) != 0; }(); + if (noy) + gdn_out_norm_loop_kernel<<<(unsigned) std::min(T * HV, 4096), S, 0, (cudaStream_t) stream>>>( + z, gamma, eps, y, y16, T * HV, ld16); + else + gdn_out_norm_loop_kernel<<<(unsigned) std::min(T * HV, 4096), S, 0, (cudaStream_t) stream>>>( + z, gamma, eps, y, y16, T * HV, ld16); } check("gdn_recurrence (quad)"); return; From 2f510316ec31b424ef29b46223514a20c1323445 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 4 Oct 2026 19:23:07 +0000 Subject: [PATCH 51/55] prefill: STRATA_GDN_PP=1 - the GDN recurrence at 10 waves a SIMD, no state copies, bitwise gdn_rec_quad_kernel needed 196 VGPRs = 7 waves a SIMD, but its 192 blocks of 4 waves need 9.6: a second round of blocks ran after the first (half the heads took exactly half the time). Cause: the 32 state-row addresses of the first loads were CSE'd with the final stores and kept live across the whole walk (64 VGPRs); the stores' lane offset now goes through an empty asm, so the addresses are made again - 133 VGPRs. A full chunk's four tokens also run with the state alternating between two register sets (the update writes the other one), which drops the 32 register copies the compiler made after each update (131 VALU a token instead of ~178). The same arithmetic in the same order. One 16K chunk-layer 25.4 -> 20.5 ms (gdn_probe12.hip, bitwise vs the old kernel); 64K prompt 1233.7 -> 1249.0 tok/s, -0.66 s; engine output ids identical at 8K and 64K. --- src/prefill/kernels.cu | 132 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 131 insertions(+), 1 deletion(-) diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 39dc70dd..70f2a0f4 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -657,6 +657,132 @@ __global__ void __launch_bounds__(QTH) gdn_rec_quad_kernel(float* __restrict__ s for (int r = 0; r < 32; ++r) base[(size_t) r * HV * S] = s[r]; } } +// Aurora (S23, opt-in STRATA_GDN_PP=1): gdn_rec_quad_kernel with the same arithmetic in the same order, two changes in +// how it is compiled. (1) The VGPR count: the 32 state-row addresses of the first loads were kept live across the +// whole walk to be reused by the final stores (64 VGPRs, 196 in all = 7 waves a SIMD for the 192 blocks of 4 waves +// that need 9.6): the stores' lane offset goes through an asm so the addresses are made again, 133 VGPRs, all blocks +// resident. (2) A full chunk's four tokens run with the state alternating between two register sets (the update +// writes the other set), so the compiler emits no 32 register copies after the update. +__global__ void __launch_bounds__(QTH) gdn_rec_quad_pp_kernel(float* __restrict__ state, const float* __restrict__ h, + const float* __restrict__ gate, const float* __restrict__ beta, + float* __restrict__ oc_out, int64_t T) { + __shared__ __align__(16) float sqk[2][HT][2][4 * QRS]; // [buffer][token][q | k][group][row (padded)] + __shared__ float sgb[2][2][HT]; // [buffer][gate | beta][token] + __shared__ float sv[2][HT][QCB]; // [buffer][token][column] v + const int head = blockIdx.x / (S / QCB), cb = blockIdx.x % (S / QCB); + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int g = lane >> 3, cl = wave * 8 + (lane & 7), col = cb * QCB + cl; // row group, column in block / head + const int qh = head % HK; + float s[32]; + { + const float* sb = state + (size_t) head * S; + const uint32_t voff = (uint32_t) ((g * 32) * HV * S + col); +#pragma unroll + for (int r = 0; r < 32; ++r) s[r] = sb[(size_t) r * HV * S + voff]; + } + float4 pf[QPF]; + float pv[HT], pgb = 0.0f; + // chunk c's inputs into registers: q/k (float4 i of the chunk's [token][q|k][S/4] block), the column's v (lanes of + // group 0) and gate (threads 0..HT-1) / beta (HT..2HT-1) of token `tid % HT` + auto fetch = [&](int64_t c) { + const int64_t t0 = c * HT; +#pragma unroll + for (int u = 0; u < QPF; ++u) { + const int i = tid + u * QTH; + const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4); + const int64_t t = t0 + tt; + pf[u] = t < T ? *reinterpret_cast(h + t * C + part * HK * S + qh * S + r4 * 4) + : make_float4(0.f, 0.f, 0.f, 0.f); + } + if (g == 0) { +#pragma unroll + for (int tt = 0; tt < HT; ++tt) { + const int64_t t = t0 + tt; + pv[tt] = t < T ? h[t * C + 2 * HK * S + head * S + col] : 0.0f; + } + } + if (tid < 2 * HT) { + const int64_t t = t0 + (tid % HT); + pgb = t < T ? (tid < HT ? gate : beta)[t * HV + head] : 0.0f; + } + }; + const float rs_s = rsqrtf((float) S); + const int src0 = lane & 7; // lane of group 0 for this column; group j is src0 + 8 j + const int64_t nch = (T + HT - 1) / HT; + if (nch > 0) fetch(0); + for (int64_t c = 0; c < nch; ++c) { + const int b = (int) (c & 1); + if (g == 0) { +#pragma unroll + for (int tt = 0; tt < HT; ++tt) sv[b][tt][cl] = pv[tt]; + } +#pragma unroll + for (int u = 0; u < QPF; ++u) { + const int i = tid + u * QTH; + const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4); + const int row = r4 * 4; + *reinterpret_cast(&sqk[b][tt][part][(row >> 5) * QRS + (row & 31)]) = pf[u]; + } + if (tid < 2 * HT) sgb[b][tid / HT][tid % HT] = pgb; + __syncthreads(); // chunk c staged (buffer b was last read two chunks ago) + if (c + 1 < nch) fetch(c + 1); + const int64_t t0 = c * HT; + const int nt = (int) (T - t0 < HT ? T - t0 : HT); + auto token = [&](int tt, float (&sin)[32], float (&sout)[32]) { + float k[32], q[32]; + { + const float4* k4 = reinterpret_cast(&sqk[b][tt][1][g * QRS]); + const float4* q4 = reinterpret_cast(&sqk[b][tt][0][g * QRS]); +#pragma unroll + for (int j = 0; j < 8; ++j) { + const float4 kk = k4[j], qq = q4[j]; + k[4 * j] = kk.x; k[4 * j + 1] = kk.y; k[4 * j + 2] = kk.z; k[4 * j + 3] = kk.w; + q[4 * j] = qq.x; q[4 * j + 1] = qq.y; q[4 * j + 2] = qq.z; q[4 * j + 3] = qq.w; + } + } + const float g_exp = __expf(sgb[b][0][tt]); + float kv = 0.0f; +#pragma unroll + for (int r = 0; r < 32; ++r) kv = fmaf(sin[r], k[r], kv); + const float p0 = __shfl_sync(0xffffffffu, kv, src0), p1 = __shfl_sync(0xffffffffu, kv, src0 + 8), + p2 = __shfl_sync(0xffffffffu, kv, src0 + 16), p3 = __shfl_sync(0xffffffffu, kv, src0 + 24); + const float kv_col = p0 + p1 + p2 + p3; + const float cvt = sv[b][tt][cl], cbt = sgb[b][1][tt]; + const float delta = (cvt - g_exp * kv_col) * cbt; + float o = 0.0f; +#pragma unroll + for (int r = 0; r < 32; ++r) { + sout[r] = fmaf(g_exp, sin[r], k[r] * delta); + o = fmaf(sout[r], q[r], o); + } + const float o0 = __shfl_sync(0xffffffffu, o, src0), o1 = __shfl_sync(0xffffffffu, o, src0 + 8), + o2 = __shfl_sync(0xffffffffu, o, src0 + 16), o3 = __shfl_sync(0xffffffffu, o, src0 + 24); + if (g == 0) oc_out[(t0 + tt) * HV * S + head * S + col] = (o0 + o1 + o2 + o3) * rs_s; + }; + if (nt == HT) { // the state alternates between two register sets: no copy after the update + float s2[32]; + token(0, s, s2); + token(1, s2, s); + token(2, s, s2); + token(3, s2, s); + } else { + for (int tt = 0; tt < nt; ++tt) { + float s2[32]; + token(tt, s, s2); +#pragma unroll + for (int r = 0; r < 32; ++r) s[r] = s2[r]; + } + } + } + { + float* sb = state + (size_t) head * S; + uint32_t voff = (uint32_t) ((g * 32) * HV * S + col); + asm volatile("" : "+v"(voff)); // (so the loads' 32 addresses are not kept alive across the whole loop) +#pragma unroll + for (int r = 0; r < 32; ++r) sb[(size_t) r * HV * S + voff] = s[r]; + } +} + // gdn_out_norm_kernel's body over a grid-stride walk of the (token, head) rows: the old kernel launched a 128-thread // block per row (T * 48 blocks; ~45 GB/s on the 8060S). The same code per row (the same compiled arithmetic: a wave // per row with four values per lane rounded differently in its first xor step). @@ -1123,7 +1249,11 @@ void gdn_recurrence_variant(int variant, float* state, const float* h, const flo } if (variant == 1) { if (T > 0) { - gdn_rec_quad_kernel<<>>(state, h, gate, beta, y, T); + static const bool pp = [] { const char* v = std::getenv("STRATA_GDN_PP"); return v && std::atoi(v) != 0; }(); + if (pp) + gdn_rec_quad_pp_kernel<<>>(state, h, gate, beta, y, T); + else + gdn_rec_quad_kernel<<>>(state, h, gate, beta, y, T); static const bool noy = [] { const char* v = std::getenv("STRATA_GDN_NOY"); return v && std::atoi(v) != 0; }(); if (noy) gdn_out_norm_loop_kernel<<<(unsigned) std::min(T * HV, 4096), S, 0, (cudaStream_t) stream>>>( From a4c30dc5c6326e241d63802dfe51af347e705357 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 4 Oct 2026 20:13:02 +0000 Subject: [PATCH 52/55] prefill: STRATA_GDN_PP=2 - the GDN recurrence with two columns per lane, bitwise gdn_rec_quad_kernel's limit was shared memory: every wave re-read the 64 k / q floats of its row group per token and the shuffles went through the same unit (probe: no k / q reads 9.8 ms, no shuffles 16.9 ms, of 21 ms). A lane now carries two columns (8 lanes x 2 columns x 4 row groups = 16 columns a wave, 64 a block, 96 blocks, 384 waves in one round at 230 VGPRs): the two columns share the k / q reads, and each wave has two independent dependency chains. Per column the same arithmetic in the same order. One 16K chunk-layer 25.4 -> 16.9 ms (gdn_probe14.hip, bitwise vs the old kernel); 64K prompt 1232.4 -> 1267.6 tok/s (-1.47 s, interleaved, 2 runs), ids identical at 8K and 64K. STRATA_GDN_PP=1 is the one-column kernel with the register fixes only (-0.66 s). --- src/prefill/kernels.cu | 133 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 131 insertions(+), 2 deletions(-) diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 70f2a0f4..c547b27e 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -783,6 +783,133 @@ __global__ void __launch_bounds__(QTH) gdn_rec_quad_pp_kernel(float* __restrict_ } } +// Aurora (S23, opt-in STRATA_GDN_PP=2): gdn_rec_quad_kernel with two columns per lane (a wave: 4 row groups x 8 lanes x +// 2 columns = 16 columns; a block of 4 waves 64 columns, 96 blocks). A lane's two columns share the k / q rows it +// reads from shared memory (half the LDS reads and shuffles per column, the kernel's limit) and give each wave two +// independent dependency chains; the 384 waves fit in one round at 230 VGPRs. Per column the same arithmetic in +// the same order (the same bits as gdn_rec_quad_kernel). The store of the state goes through an asm for the reason +// given at gdn_rec_quad_pp_kernel. + +// ---- C2: two columns per lane (a wave: 4 row groups x 8 lanes x 2 columns = 16 columns; a block of 4 waves 64 +// columns). A lane's two columns share the k / q rows it reads from LDS (half the LDS reads and shuffles per column +// and two independent dependency chains in each wave). Per column the same arithmetic in the same order. +constexpr int C2CB = 64; // columns per block +constexpr int C2PF = HT * 2 * S / 4 / QTH; // float4 of q/k each thread prefetches per chunk (2) +__global__ void __launch_bounds__(QTH) gdn_rec_quad2c_kernel(float* __restrict__ state, const float* __restrict__ h, + const float* __restrict__ gate, const float* __restrict__ beta, + float* __restrict__ oc_out, int64_t T) { + __shared__ __align__(16) float sqk[2][HT][2][4 * QRS]; + __shared__ float sgb[2][2][HT]; + __shared__ float sv[2][HT][C2CB]; + const int head = blockIdx.x / (S / C2CB), cb = blockIdx.x % (S / C2CB); + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int g = lane >> 3, cl0 = wave * 16 + (lane & 7), cl1 = cl0 + 8; // the lane's two columns in the block + const int col0 = cb * C2CB + cl0, col1 = cb * C2CB + cl1; + const int qh = head % HK; + float s0[32], s1[32]; + { + const float* sb = state + (size_t) head * S; + const uint32_t voff = (uint32_t) ((g * 32) * HV * S); +#pragma unroll + for (int r = 0; r < 32; ++r) { s0[r] = sb[(size_t) r * HV * S + voff + col0]; s1[r] = sb[(size_t) r * HV * S + voff + col1]; } + } + float4 pf[C2PF]; + float pv[2][HT], pgb = 0.0f; + auto fetch = [&](int64_t c) { + const int64_t t0 = c * HT; +#pragma unroll + for (int u = 0; u < C2PF; ++u) { + const int i = tid + u * QTH; + const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4); + const int64_t t = t0 + tt; + pf[u] = t < T ? *reinterpret_cast(h + t * C + part * HK * S + qh * S + r4 * 4) + : make_float4(0.f, 0.f, 0.f, 0.f); + } + if (g == 0) { +#pragma unroll + for (int tt = 0; tt < HT; ++tt) { + const int64_t t = t0 + tt; + pv[0][tt] = t < T ? h[t * C + 2 * HK * S + head * S + col0] : 0.0f; + pv[1][tt] = t < T ? h[t * C + 2 * HK * S + head * S + col1] : 0.0f; + } + } + if (tid < 2 * HT) { + const int64_t t = t0 + (tid % HT); + pgb = t < T ? (tid < HT ? gate : beta)[t * HV + head] : 0.0f; + } + }; + const float rs_s = rsqrtf((float) S); + const int src0 = lane & 7; + const int64_t nch = (T + HT - 1) / HT; + if (nch > 0) fetch(0); + for (int64_t c = 0; c < nch; ++c) { + const int b = (int) (c & 1); + if (g == 0) { +#pragma unroll + for (int tt = 0; tt < HT; ++tt) { sv[b][tt][cl0] = pv[0][tt]; sv[b][tt][cl1] = pv[1][tt]; } + } +#pragma unroll + for (int u = 0; u < C2PF; ++u) { + const int i = tid + u * QTH; + const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4); + const int row = r4 * 4; + *reinterpret_cast(&sqk[b][tt][part][(row >> 5) * QRS + (row & 31)]) = pf[u]; + } + if (tid < 2 * HT) sgb[b][tid / HT][tid % HT] = pgb; + __syncthreads(); + if (c + 1 < nch) fetch(c + 1); + const int64_t t0 = c * HT; + const int nt = (int) (T - t0 < HT ? T - t0 : HT); + for (int tt = 0; tt < nt; ++tt) { + float k[32], q[32]; + { + const float4* k4 = reinterpret_cast(&sqk[b][tt][1][g * QRS]); + const float4* q4 = reinterpret_cast(&sqk[b][tt][0][g * QRS]); +#pragma unroll + for (int j = 0; j < 8; ++j) { + const float4 kk = k4[j], qq = q4[j]; + k[4 * j] = kk.x; k[4 * j + 1] = kk.y; k[4 * j + 2] = kk.z; k[4 * j + 3] = kk.w; + q[4 * j] = qq.x; q[4 * j + 1] = qq.y; q[4 * j + 2] = qq.z; q[4 * j + 3] = qq.w; + } + } + const float g_exp = __expf(sgb[b][0][tt]); + float kv0 = 0.0f, kv1 = 0.0f; +#pragma unroll + for (int r = 0; r < 32; ++r) { kv0 = fmaf(s0[r], k[r], kv0); kv1 = fmaf(s1[r], k[r], kv1); } + const float a0 = __shfl_sync(0xffffffffu, kv0, src0), a1 = __shfl_sync(0xffffffffu, kv0, src0 + 8), + a2 = __shfl_sync(0xffffffffu, kv0, src0 + 16), a3 = __shfl_sync(0xffffffffu, kv0, src0 + 24); + const float b0 = __shfl_sync(0xffffffffu, kv1, src0), b1 = __shfl_sync(0xffffffffu, kv1, src0 + 8), + b2 = __shfl_sync(0xffffffffu, kv1, src0 + 16), b3 = __shfl_sync(0xffffffffu, kv1, src0 + 24); + const float kvc0 = a0 + a1 + a2 + a3, kvc1 = b0 + b1 + b2 + b3; + const float cbt = sgb[b][1][tt]; + const float d0 = (sv[b][tt][cl0] - g_exp * kvc0) * cbt, d1 = (sv[b][tt][cl1] - g_exp * kvc1) * cbt; + float o0 = 0.0f, o1 = 0.0f; +#pragma unroll + for (int r = 0; r < 32; ++r) { + s0[r] = fmaf(g_exp, s0[r], k[r] * d0); + s1[r] = fmaf(g_exp, s1[r], k[r] * d1); + o0 = fmaf(s0[r], q[r], o0); + o1 = fmaf(s1[r], q[r], o1); + } + const float x0 = __shfl_sync(0xffffffffu, o0, src0), x1 = __shfl_sync(0xffffffffu, o0, src0 + 8), + x2 = __shfl_sync(0xffffffffu, o0, src0 + 16), x3 = __shfl_sync(0xffffffffu, o0, src0 + 24); + const float y0 = __shfl_sync(0xffffffffu, o1, src0), y1 = __shfl_sync(0xffffffffu, o1, src0 + 8), + y2 = __shfl_sync(0xffffffffu, o1, src0 + 16), y3 = __shfl_sync(0xffffffffu, o1, src0 + 24); + if (g == 0) { + oc_out[(t0 + tt) * HV * S + head * S + col0] = (x0 + x1 + x2 + x3) * rs_s; + oc_out[(t0 + tt) * HV * S + head * S + col1] = (y0 + y1 + y2 + y3) * rs_s; + } + } + } + { + float* sb = state + (size_t) head * S; + uint32_t voff = (uint32_t) ((g * 32) * HV * S); + asm volatile("" : "+v"(voff)); +#pragma unroll + for (int r = 0; r < 32; ++r) { sb[(size_t) r * HV * S + voff + col0] = s0[r]; sb[(size_t) r * HV * S + voff + col1] = s1[r]; } + } +} + // gdn_out_norm_kernel's body over a grid-stride walk of the (token, head) rows: the old kernel launched a 128-thread // block per row (T * 48 blocks; ~45 GB/s on the 8060S). The same code per row (the same compiled arithmetic: a wave // per row with four values per lane rounded differently in its first xor step). @@ -1249,8 +1376,10 @@ void gdn_recurrence_variant(int variant, float* state, const float* h, const flo } if (variant == 1) { if (T > 0) { - static const bool pp = [] { const char* v = std::getenv("STRATA_GDN_PP"); return v && std::atoi(v) != 0; }(); - if (pp) + static const int pp = [] { const char* v = std::getenv("STRATA_GDN_PP"); return v ? std::atoi(v) : 0; }(); + if (pp == 2) + gdn_rec_quad2c_kernel<<>>(state, h, gate, beta, y, T); + else if (pp) gdn_rec_quad_pp_kernel<<>>(state, h, gate, beta, y, T); else gdn_rec_quad_kernel<<>>(state, h, gate, beta, y, T); From e58d7fc84994206f2fcaf7a097115e83d734a7f7 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 4 Oct 2026 20:26:01 +0000 Subject: [PATCH 53/55] tests: gdn_rec_head also compares the PP (variant 4) and two-column (variant 5) recurrence kernels, bitwise T = 1, 7, 8, 9, 17, 100, 2048, 2051 (full and partial chunks), y, its FP16 bits and the final state: 0 values differ. --- src/prefill/kernels.cu | 12 ++++++++++++ tests/hip/gdn_rec_head.cpp | 2 +- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index c547b27e..ef5d4a19 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -1374,6 +1374,18 @@ void gdn_recurrence_variant(int variant, float* state, const float* h, const flo } return; } + if (variant == 4 || variant == 5) { // diagnostics: the quad recurrence's PP / two-column kernels + the norm + if (T > 0) { + if (variant == 5) + gdn_rec_quad2c_kernel<<>>(state, h, gate, beta, y, T); + else + gdn_rec_quad_pp_kernel<<>>(state, h, gate, beta, y, T); + gdn_out_norm_loop_kernel<<<(unsigned) std::min(T * HV, 4096), S, 0, (cudaStream_t) stream>>>( + z, gamma, eps, y, y16, T * HV, ld16); + } + check("gdn_recurrence (quad pp)"); + return; + } if (variant == 1) { if (T > 0) { static const int pp = [] { const char* v = std::getenv("STRATA_GDN_PP"); return v ? std::atoi(v) : 0; }(); diff --git a/tests/hip/gdn_rec_head.cpp b/tests/hip/gdn_rec_head.cpp index 80ed5fe2..0e3a6cc9 100644 --- a/tests/hip/gdn_rec_head.cpp +++ b/tests/hip/gdn_rec_head.cpp @@ -61,7 +61,7 @@ int main() { const float* dgm = dev(gamma); std::vector y_ref, st_ref; std::vector y16_ref; - for (int variant : {0, 3, 1}) { + for (int variant : {0, 3, 1, 4, 5}) { float* dst = dev(state); float* dy = nullptr; uint16_t* dy16 = nullptr; From 203ec5cdf7a7c53a880708d33517d92525b55459 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 5 Oct 2026 03:52:38 +0000 Subject: [PATCH 54/55] prefill: STRATA_HCD_EXACT=1 - the HC down projection by a WMMA kernel with hipBLASLt solution 1176/1177 k order (StaggerU included), bitwise --- include/strata/prefill/gemm.hpp | 7 ++- src/prefill/gemm.cu | 40 +++++++++++--- src/prefill/prefill.cpp | 28 +++++++--- src/prefill/wmma_gemm.cu | 96 +++++++++++++++++++++++++++++++++ src/prefill/wmma_gemm.h | 5 ++ 5 files changed, 159 insertions(+), 17 deletions(-) diff --git a/include/strata/prefill/gemm.hpp b/include/strata/prefill/gemm.hpp index 4f3b3263..7a17ec10 100644 --- a/include/strata/prefill/gemm.hpp +++ b/include/strata/prefill/gemm.hpp @@ -27,7 +27,12 @@ public: /// Y[T, N] (fp32, row stride ldy) = X[T, K] (bf16, row-major) . W[N, K]^T (bf16, row-major). `beta` = 1 adds. void bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy = 0, - float beta = 0.0f); + float beta = 0.0f, int64_t ldx = 0); + + /// S (STRATA_HCD_EXACT): the HC down projection (N 320, K 10240) by the WMMA kernel that reproduces hipBLASLt's + /// solution 1176 / 1177 bit for bit; false (nothing launched) unless hipBLASLt would take one of those for this + /// shape (so the caller falls back to bf16(), with the same ldx). + bool bf16_hcd_exact(const uint16_t* X, int64_t ldx, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K); /// Y = X . W^T with both in FP16 (bits). void f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy = 0, diff --git a/src/prefill/gemm.cu b/src/prefill/gemm.cu index 1be38082..a752371e 100644 --- a/src/prefill/gemm.cu +++ b/src/prefill/gemm.cu @@ -127,7 +127,7 @@ struct HipLtDescriptors { if (c) hipblasLtMatrixLayoutDestroy(c); } - bool init(hipDataType type, int t, int n, int k, int ldy) { + bool init(hipDataType type, int t, int n, int k, int ldy, int ldb = 0) { const hipblasOperation_t trans_a = HIPBLAS_OP_T; const hipblasOperation_t trans_b = HIPBLAS_OP_N; if (hipblasLtMatmulDescCreate(&op, HIPBLAS_COMPUTE_32F, HIP_R_32F) != HIPBLAS_STATUS_SUCCESS || @@ -136,7 +136,7 @@ struct HipLtDescriptors { hipblasLtMatmulDescSetAttribute(op, HIPBLASLT_MATMUL_DESC_TRANSB, &trans_b, sizeof(trans_b)) != HIPBLAS_STATUS_SUCCESS || hipblasLtMatrixLayoutCreate(&a, type, k, n, k) != HIPBLAS_STATUS_SUCCESS || - hipblasLtMatrixLayoutCreate(&b, type, k, t, k) != HIPBLAS_STATUS_SUCCESS || + hipblasLtMatrixLayoutCreate(&b, type, k, t, ldb > k ? ldb : k) != HIPBLAS_STATUS_SUCCESS || hipblasLtMatrixLayoutCreate(&c, HIP_R_32F, n, t, ldy) != HIPBLAS_STATUS_SUCCESS) { return false; } @@ -243,9 +243,20 @@ HipLtCachedAlgo resolve_hipblaslt_algo(HipLtState& state, strata::prefill::hipbl return state.cache.emplace(key, resolved).first->second; } +// the hipBLASLt solution index the tuning table gives this call (-1: none / unsupported) +int hipblaslt_solution_for(void* opaque_state, strata::prefill::hipblaslt::InputType type, int64_t t, int64_t n, int64_t k, + int64_t ldy, float beta) { + auto* state = static_cast(opaque_state); + if (!state || t <= 0 || n <= 0 || k <= 0 || t > INT_MAX || n > INT_MAX || k > INT_MAX || ldy > INT_MAX || ldy < n) return -1; + const auto resolved = resolve_hipblaslt_algo(*state, type, (int) t, (int) n, (int) k, (int) ldy, beta); + if (!resolved.supported || resolved.workspace_bytes > state->workspace_bytes) return -1; + auto algo = resolved.algo; + return hipblaslt_ext::getIndexFromAlgo(algo); +} + bool try_hipblaslt(void* opaque_state, strata::prefill::hipblaslt::InputType type, const uint16_t* x, const uint16_t* w, float* y, int64_t t, int64_t n, int64_t k, int64_t ldy, float beta, - void* stream) { + void* stream, int64_t ldx = 0) { auto* state = static_cast(opaque_state); if (!state || t <= 0 || n <= 0 || k <= 0 || t > INT_MAX || n > INT_MAX || k > INT_MAX || ldy > INT_MAX || ldy < n) { @@ -269,7 +280,7 @@ bool try_hipblaslt(void* opaque_state, strata::prefill::hipblaslt::InputType typ HipLtDescriptors desc; const hipDataType input_type = type == strata::prefill::hipblaslt::InputType::bf16 ? HIP_R_16BF : HIP_R_16F; - if (!desc.init(input_type, (int) t, (int) n, (int) k, (int) ldy)) return false; + if (!desc.init(input_type, (int) t, (int) n, (int) k, (int) ldy, (int) ldx)) return false; const float alpha = 1.0f; const hipblasStatus_t status = hipblasLtMatmul(state->handle, desc.op, &alpha, w, desc.a, x, desc.b, &beta, y, desc.c, y, desc.c, &resolved.algo, state->workspace, @@ -376,16 +387,29 @@ bool Gemm::init(void* stream, int64_t scratch_elems, std::string& err) { return true; } +bool Gemm::bf16_hcd_exact(const uint16_t* X, int64_t ldx, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K) { +#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) + if (!hipblaslt_state_ || N != 320 || K != 10240 || T < 1) return false; + const int id = hipblaslt_solution_for(hipblaslt_state_, strata::prefill::hipblaslt::InputType::bf16, T, N, K, N, 0.0f); + if (id != 1176 && id != 1177) return false; + return strata_pf_hcdown_exact_bf16(X, ldx, W, Y, T, N, K, stream_); +#else + (void) X; (void) ldx; (void) W; (void) Y; (void) T; (void) N; (void) K; + return false; +#endif +} + void Gemm::bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy, - float beta) { + float beta, int64_t ldx) { if (T <= 0 || N <= 0) return; if (ldy <= 0) ldy = N; + if (ldx <= K) ldx = 0; #ifdef STRATA_USE_HIP // #313 (opt-in STRATA_WMMA_GEMM=1; STRATA_WMMA_BF16=0 excludes bf16): RDNA3 / RDNA3.5 WMMA dense GEMM, before // hipBLASLt; it returns false for shapes it does not take (and off gfx11) and this falls through static const bool wmma_on = [] { const char* v = std::getenv("STRATA_WMMA_GEMM"); return v && v[0] != 0 && v[0] != '0'; }(); static const bool bf16_on = [] { const char* v = std::getenv("STRATA_WMMA_BF16"); return !v || (v[0] != 0 && v[0] != '0'); }(); - if (wmma_on && bf16_on && T >= 16 && (beta == 0.0f || beta == 1.0f) && + if (wmma_on && bf16_on && ldx == 0 && T >= 16 && (beta == 0.0f || beta == 1.0f) && strata_wmma_gemm_bf16(X, W, Y, T, N, K, ldy, beta, stream_)) { return; } @@ -393,14 +417,14 @@ void Gemm::bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64 const float alpha = 1.0f; #if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) if (try_hipblaslt(hipblaslt_state_, strata::prefill::hipblaslt::InputType::bf16, X, W, Y, T, N, K, ldy, - beta, stream_)) { + beta, stream_, ldx)) { STRATA_ABSORB_HIPBLAS_STICKY("hipBLASLt bf16"); return; } #endif // Column-major view: Y^T[N, T] = W[N, K] (stored K x N col-major, transposed) . X^T[K, T]. ck(cublasGemmEx((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) T, (int) K, &alpha, W, - CUDA_R_16BF, (int) K, X, CUDA_R_16BF, (int) K, &beta, Y, CUDA_R_32F, (int) ldy, + CUDA_R_16BF, (int) K, X, CUDA_R_16BF, (int) (ldx ? ldx : K), &beta, Y, CUDA_R_32F, (int) ldy, CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT), "cublasGemmEx"); STRATA_ABSORB_HIPBLAS_STICKY("cublasGemmEx"); diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 0f89eacd..13d273d0 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -191,6 +191,14 @@ inline bool pf_hcdown() { return v; } constexpr int64_t XN_PAD = 64; +// S (opt-in STRATA_HCD_EXACT=1, on chunks of STRATA_PF_SWITCH_MIN_T+ tokens): the HC down projection by a WMMA kernel with +// hipBLASLt's own k order (bitwise: strata_pf_hcdown_exact_bf16), xn16 written with token stride 10240 + 64 (the inject +// projection stays on hipBLASLt, reading that stride) +inline bool hcd_exact() { + static const bool v = [] { const char* e = std::getenv("STRATA_HCD_EXACT"); return e && e[0] == '1'; }(); + return v; +} +inline bool hc_pad() { return pf_hcdown() || hcd_exact(); } inline bool cvec_fuse() { static const bool v = [] { const char* e = std::getenv("STRATA_CVEC_FUSE"); return e && e[0] == '1'; }(); return v; @@ -755,7 +763,7 @@ bool Prefill::carve(size_t T, void* alloc) { m.emb = o.take(T * N, ok); m.R = o.take(T * D, ok); m.xn = gr_unfused() ? o.take(T * D, ok) : nullptr; // F-1: not needed (gr_mix_r reads R) m.grs = o.take(T * HC, ok); - m.xn16 = o.take(T * (D + (pf_hcdown() ? XN_PAD : 0)), ok); m.lo = o.take(T * LR, ok); m.lo16 = o.take(T * LR, ok); + m.xn16 = o.take(T * (D + (hc_pad() ? XN_PAD : 0)), ok); m.lo = o.take(T * LR, ok); m.lo16 = o.take(T * LR, ok); m.gated = o.take(T * D, ok); m.inj = o.take(T * HC, ok); m.mixed = o.take(T * N, ok); m.mixed_bf = o.take(T * N, ok); m.mixed_h = o.take(T * N, ok); m.bo = o.take(T * N, ok); @@ -1020,7 +1028,7 @@ uint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::Session o.take((size_t) GEMM_SCRATCH, ok); o.take(GEMM_WS, ok); auto f = [&](size_t n) { o.take(n, ok); }; - f(T * N); f(T * D); f(T * D); o.take(T * (D + (pf_hcdown() ? XN_PAD : 0)), ok); f(T * LR); + f(T * N); f(T * D); f(T * D); o.take(T * (D + (hc_pad() ? XN_PAD : 0)), ok); f(T * LR); o.take(T * LR, ok); f(T * D); f(T * HC); f(T * N); o.take(T * N, ok); o.take(T * N, ok); f(T * N); if (bf16x2_hc()) { o.take(T * D, ok); o.take(T * LR, ok); } @@ -1063,9 +1071,9 @@ bool native_proj(Gemm& gm, const core::WeightRef* w, const uint16_t* X, float* Y return true; } bool bf16_proj(Gemm& gm, const core::WeightRef* w, const uint16_t* X, float* Y, int64_t T, const std::string& name, - std::string& err, int64_t ldy = 0, const uint16_t* X_lo = nullptr) { + std::string& err, int64_t ldy = 0, const uint16_t* X_lo = nullptr, int64_t ldx = 0) { if (w->kind != core::WeightKind::Bf16InF32 || !w->data) { err = "prefill: " + name + " is not a resident BF16 tensor"; return false; } - gm.bf16(X, (const uint16_t*) w->data, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy); + gm.bf16(X, (const uint16_t*) w->data, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy, 0.0f, ldx); if (X_lo) gm.bf16(X_lo, (const uint16_t*) w->data, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy, 1.0f); return true; } @@ -1457,13 +1465,17 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e if (!wn || !wd || !wu || !wi) return false; pt.mark(kPfHc, cs); // the xn16 token stride of this chunk (the writers of both halves and of the fused write-backs use it) - const int64_t ldx = pf_hcdown() && T >= std::max(pf_switch_min_t(), 64) && !gr_unfused() && + const int64_t ldx = hc_pad() && T >= std::max(pf_switch_min_t(), 64) && !gr_unfused() && !m.xn16_lo ? D + XN_PAD : D; if (gr_unfused()) gr_norm(m.R, (const float*) wn->data, EPS, m.xn, m.xn16, T, m.cs, m.xn16_lo); else if (!normed) gr_norm_rs(m.R, (const float*) wn->data, EPS, m.grs, m.xn16, T, m.cs, m.xn16_lo, ldx); normed = false; bool hcd = false; - if (ldx != D) { + bool hdown = false; + if (ldx != D && !pf_hcdown()) { // STRATA_HCD_EXACT: the exact-order down kernel when hipBLASLt would take 1176 / 1177 + hdown = wd->kind == core::WeightKind::Bf16InF32 && wd->data && wd->ne0 == D && wd->ne1 == LR && + m.gemm.bf16_hcd_exact(m.xn16, ldx, (const uint16_t*) wd->data, m.lo, T, LR, D); + } else if (ldx != D) { if (wd->kind != core::WeightKind::Bf16InF32 || !wd->data || wd->ne0 != D || wd->ne1 != LR || wi->kind != core::WeightKind::Bf16InF32 || !wi->data || wi->ne0 != D || wi->ne1 != HC || !strata_pf_hcdown_bf16(m.xn16, ldx, (const uint16_t*) wd->data, (const uint16_t*) wi->data, LR, @@ -1473,7 +1485,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e } hcd = true; } - if (!hcd && !bf16_proj(m.gemm, wd, m.xn16, m.lo, T, sd, err, 0, m.xn16_lo)) return false; + if (!hcd && !hdown && !bf16_proj(m.gemm, wd, m.xn16, m.lo, T, sd, err, 0, m.xn16_lo, ldx != D ? ldx : 0)) return false; gr_silu(m.lo, m.lo16, T, m.cs, m.lo16_lo); bool upmixed = false; if (hc_upmix() && T >= pf_switch_min_t() && !gr_unfused() && !m.lo16_lo && !m.mixed_bf_lo && @@ -1503,7 +1515,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e } } if (!upmixed && !bf16_proj(m.gemm, wu, m.lo16, m.gated, T, su, err, 0, m.lo16_lo)) return false; - if (!hcd && !bf16_proj(m.gemm, wi, m.xn16, m.inj, T, si, err, 0, m.xn16_lo)) return false; + if (!hcd && !bf16_proj(m.gemm, wi, m.xn16, m.inj, T, si, err, 0, m.xn16_lo, ldx != D ? ldx : 0)) return false; if (upmixed) { } else if (gr_unfused()) { gr_mix(m.xn, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h, m.mixed_bf_lo); diff --git a/src/prefill/wmma_gemm.cu b/src/prefill/wmma_gemm.cu index 5c88fb3c..9547596a 100644 --- a/src/prefill/wmma_gemm.cu +++ b/src/prefill/wmma_gemm.cu @@ -554,6 +554,82 @@ __global__ void __launch_bounds__(256) kernel_hcdown(const uint16_t* __restrict_ } #endif } + +// S23/S (STRATA_HCD_EXACT=1): the HC down projection (N 320, K 10240, BF16 in, FP32 out) bitwise equal to hipBLASLt +// solution 1176 / 1177 (MT32x96 / MT96x96, StaggerU 32, stride 256 B): every output is the k tiles of 32 accumulated in +// order, 16 per WMMA, starting at k tile 4 * (token tile of 96 % 32) and wrapping (hcd_bit / hcd_perm probes: 0 of +// 5.2 M outputs differ at T 16384). 96 x 160 blocks (two per token tile), 6 waves of 32 x 80. +typedef uint32_t hx_u4 __attribute__((ext_vector_type(4))); +constexpr int HX_N = 320, HX_BN = 160, HX_BM = 96, HX_BK = 64, HX_LDK = HX_BK + 8, HX_NT = 192, HX_K = 10240; +__device__ __forceinline__ hb16 hx_frag(const uint16_t* p) { + const hx_u4 a = *reinterpret_cast(p), b = *reinterpret_cast(p + 8); + const uint32_t w[8] = {a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w}; + return __builtin_bit_cast(hb16, w); +} +__global__ void __launch_bounds__(HX_NT) kernel_hcd_exact(const uint16_t* __restrict__ X, int ldx, + const uint16_t* __restrict__ W, float* __restrict__ Y, int M) { +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__) + constexpr int K = HX_K, BN = HX_BN, BMT = HX_BM, BK = HX_BK, NT = HX_NT; + __shared__ __align__(16) uint16_t sA[BMT][HX_LDK]; + __shared__ __align__(16) uint16_t sB[BN][HX_LDK]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, l16 = lane & 15, hi = lane >> 4; + const int wm = wave % 3, wn = wave / 3, nbase = BN * (blockIdx.x & 1); + const int tt = blockIdx.x >> 1, m0 = tt * BMT; + constexpr int nslab = K / BK; + const int rot = (2 * (tt & 31)) % nslab; // 4 k tiles of 32 = 2 slabs of 64 + hx_u4 ra0, ra1, ra2, ra3, rb0, rb1, rb2, rb3, rb4, rb5, rb6; +#define HX_LDA(v, i) { const int idx = tid + NT * (i), r = idx >> 3, q = idx & 7; v = *reinterpret_cast(X + (size_t) min(m0 + r, M - 1) * ldx + k0 + 8 * q); } +#define HX_LDB(v, i) { const int idx = min(tid + NT * (i), BN * 8 - 1), r = idx >> 3, q = idx & 7; v = *reinterpret_cast(W + (size_t) (nbase + r) * K + k0 + 8 * q); } +#define HX_STA(v, i) { const int idx = tid + NT * (i); *reinterpret_cast(&sA[idx >> 3][8 * (idx & 7)]) = v; } +#define HX_STB(v, i) { const int idx = tid + NT * (i); if (idx < BN * 8) *reinterpret_cast(&sB[idx >> 3][8 * (idx & 7)]) = v; } +#define HX_LOAD(k0v) { const int k0 = (k0v); HX_LDA(ra0, 0) HX_LDA(ra1, 1) HX_LDA(ra2, 2) HX_LDA(ra3, 3) HX_LDB(rb0, 0) HX_LDB(rb1, 1) HX_LDB(rb2, 2) HX_LDB(rb3, 3) HX_LDB(rb4, 4) HX_LDB(rb5, 5) HX_LDB(rb6, 6) } +#define HX_STORE() { HX_STA(ra0, 0) HX_STA(ra1, 1) HX_STA(ra2, 2) HX_STA(ra3, 3) HX_STB(rb0, 0) HX_STB(rb1, 1) HX_STB(rb2, 2) HX_STB(rb3, 3) HX_STB(rb4, 4) HX_STB(rb5, 5) HX_STB(rb6, 6) } + f8 acc[2][5]; +#pragma unroll + for (int i = 0; i < 2; ++i) +#pragma unroll + for (int j = 0; j < 5; ++j) acc[i][j] = f8{0, 0, 0, 0, 0, 0, 0, 0}; + HX_LOAD(rot * BK); + HX_STORE(); + __syncthreads(); + const int ar = 32 * wm + l16, br = 80 * wn + l16; + for (int s = 0; s < nslab; ++s) { + const bool more = s + 1 < nslab; + if (more) HX_LOAD(((s + 1 + rot) % nslab) * BK); +#pragma unroll + for (int ks = 0; ks < BK; ks += 16) { + const hb16 a0 = hx_frag(&sA[ar][ks]), a1 = hx_frag(&sA[ar + 16][ks]); + const hb16 b0 = hx_frag(&sB[br][ks]), b1 = hx_frag(&sB[br + 16][ks]), b2 = hx_frag(&sB[br + 32][ks]), + b3 = hx_frag(&sB[br + 48][ks]), b4 = hx_frag(&sB[br + 64][ks]); +#define HX_W2(j, bj) acc[0][j] = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a0, bj, acc[0][j]); acc[1][j] = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a1, bj, acc[1][j]); + HX_W2(0, b0) HX_W2(1, b1) HX_W2(2, b2) HX_W2(3, b3) HX_W2(4, b4) +#undef HX_W2 + } + if (more) { + __syncthreads(); + HX_STORE(); + __syncthreads(); + } + } +#undef HX_LDA +#undef HX_LDB +#undef HX_STA +#undef HX_STB +#undef HX_LOAD +#undef HX_STORE +#pragma unroll + for (int i = 0; i < 2; ++i) +#pragma unroll + for (int j = 0; j < 5; ++j) { + const int n = nbase + 80 * wn + 16 * j + l16; +#pragma unroll + for (int e = 0; e < 8; ++e) { + const int m = m0 + 32 * wm + 16 * i + 2 * e + hi; + if (m < M) Y[(size_t) m * HX_N + n] = acc[i][j][e]; + } + } +#endif +} } // namespace pfg bool strata_pf_hcdown_bf16(const uint16_t* X, int64_t ldx, const uint16_t* Wd, const uint16_t* Wi, int64_t nd, @@ -574,6 +650,23 @@ bool strata_pf_hcdown_bf16(const uint16_t* X, int64_t ldx, const uint16_t* Wd, c return hipGetLastError() == hipSuccess; } +bool strata_pf_hcdown_exact_bf16(const uint16_t* X, int64_t ldx, const uint16_t* W, float* Y, int64_t T, int64_t N, + int64_t K, void* stream) { + if (!X || !W || !Y || T < 1 || N != pfg::HX_N || K != pfg::HX_K || ldx < K || ldx % 8 != 0 || ldx > (1LL << 30) || + T > (1LL << 30)) + return false; + static const bool gfx11 = [] { + int dev = 0; + hipDeviceProp_t prop{}; + if (hipGetDevice(&dev) != hipSuccess || hipGetDeviceProperties(&prop, dev) != hipSuccess) return false; + return std::strncmp(prop.gcnArchName, "gfx11", 5) == 0; + }(); + if (!gfx11) return false; + const unsigned grid = (unsigned) (2 * ((T + pfg::HX_BM - 1) / pfg::HX_BM)); + pfg::kernel_hcd_exact<<(stream)>>>(X, (int) ldx, W, Y, (int) T); + return hipGetLastError() == hipSuccess; +} + bool strata_pf_gemm_f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy, float beta, void* stream) { return strata_pf_gemm_f16_ld(X, K, W, K, Y, T, N, K, ldy, beta, stream); @@ -627,6 +720,9 @@ bool strata_pf_hcdown_bf16(const uint16_t*, int64_t, const uint16_t*, const uint int64_t, int64_t, void*) { return false; } +bool strata_pf_hcdown_exact_bf16(const uint16_t*, int64_t, const uint16_t*, float*, int64_t, int64_t, int64_t, void*) { + return false; +} bool strata_wmma_gemm_f16(const uint16_t*, const uint16_t*, float*, int64_t, int64_t, int64_t, int64_t, float, void*) { diff --git a/src/prefill/wmma_gemm.h b/src/prefill/wmma_gemm.h index cfe087a0..1e54e911 100644 --- a/src/prefill/wmma_gemm.h +++ b/src/prefill/wmma_gemm.h @@ -28,6 +28,11 @@ bool strata_pf_gemm_f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t /// K); lo T x nd and inj T x ni, FP32. K a multiple of 64, T >= 64. False (nothing launched) otherwise / off gfx11. bool strata_pf_hcdown_bf16(const uint16_t* X, int64_t ldx, const uint16_t* Wd, const uint16_t* Wi, int64_t nd, int64_t ni, float* lo, float* inj, int64_t T, int64_t K, void* stream = nullptr); +/// S (STRATA_HCD_EXACT=1): Y[t, n] = sum_k X[t, k] W[n, k] for N 320, K 10240 (BF16, FP32 out, X token stride ldx >= K, a +/// multiple of 8), bitwise equal to hipBLASLt solution 1176 / 1177 for that shape (its k order, StaggerU included). +/// False (nothing launched) for any other shape / off gfx11. +bool strata_pf_hcdown_exact_bf16(const uint16_t* X, int64_t ldx, const uint16_t* W, float* Y, int64_t T, int64_t N, + int64_t K, void* stream = nullptr); bool strata_pf_gemm_f16_ld(const uint16_t* X, int64_t ldx, const uint16_t* W, int64_t ldw, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy, float beta, void* stream = nullptr); From 528c1fb185b9c5470382d5a83317556248e64123 Mon Sep 17 00:00:00 2001 From: Strata W Date: Mon, 5 Oct 2026 06:02:44 +0000 Subject: [PATCH 55/55] prefill: fused-expert exact wins (table16 via direct selector, float4 moe_combine, LDS alias + occupancy) Bitwise-identical to e58d7fc (generated ids identical on UD-IQ4_XS, UD-Q4_K_XL, IQ3_S, IQ3_XXS at 8K/4K/64K; harness fused-output hash unchanged): - table16: IQ4_NL / IQ4_XS decode through the direct-selector v_perm form (X5; exhaustive 2^32 check). -DSTRATA_W_NO_T16 restores the old form. - moe_combine: four columns per thread with float4 loads, same fma order (X5); falls back to the scalar kernel if Dm / shared / bo are not 16-byte aligned. -DSTRATA_W_NO_COMB. - native_w11_kernel: the H tile aliased onto the weight buffers (gate/up LDS 46.5 -> 30.2 KB), amdgpu_waves_per_eu(8), 4 blocks per WGP (X1), only for the types that do not spill under the 192-VGPR cap (gate/up IQ2_*, IQ3_*, IQ4_XS; down Q2_0, Q8_0, IQ4_NL). -DSTRATA_W_NO_OCC. - X3 on1 (skip the second 16-row n tile of the down kernel) NOT included: no gain alone (-0.1%), and with the occupancy cap it makes IQ4_NL down spill 62 VGPRs and the whole bundle 2.3% slower. --- src/prefill/kernels.cu | 34 +++++++++++++++++++++++++++++ src/prefill/moe_fused_iq.cu | 43 +++++++++++++++++++++++++++++++------ 2 files changed, 70 insertions(+), 7 deletions(-) diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index ef5d4a19..f9a20cb5 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -1063,6 +1063,32 @@ __global__ void moe_combine_kernel(const float* __restrict__ Dm, const int32_t* bo[i] = s + shared[i] * sigm(sg[t]); } +// W (X5): four columns per thread, one float4 load per slot; the per-element expression and the k order are unchanged +// (bitwise equal to moe_combine_kernel). Needs 16-byte aligned Dm / shared / bo (N * 4 bytes per row is a multiple of 16). +__global__ void moe_combine4_kernel(const float* __restrict__ Dm, const int32_t* __restrict__ slot, + const float* __restrict__ w, const float4* __restrict__ shared, + const float* __restrict__ sg, float4* __restrict__ bo, int64_t T) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; // float4 index + if (i >= T * (N / 4)) return; + const int64_t t = i / (N / 4), d = (i % (N / 4)) * 4; + float4 s = make_float4(0.0f, 0.0f, 0.0f, 0.0f); + float4 v[10]; + float ww[10]; +#pragma unroll + for (int k = 0; k < 10; ++k) { + ww[k] = w[t * 10 + k]; + v[k] = *reinterpret_cast(Dm + (int64_t) slot[t * 10 + k] * N + d); + } +#pragma unroll + for (int k = 0; k < 10; ++k) { + s.x = fmaf(ww[k], v[k].x, s.x); s.y = fmaf(ww[k], v[k].y, s.y); + s.z = fmaf(ww[k], v[k].z, s.z); s.w = fmaf(ww[k], v[k].w, s.w); + } + const float g = sigm(sg[t]); + const float4 sh = shared[i]; + bo[i] = make_float4(s.x + sh.x * g, s.y + sh.y * g, s.z + sh.z * g, s.w + sh.w * g); +} + // ---------------------------------------------------------------- QSA helpers __global__ void rms_rows_kernel(float* __restrict__ x, const float* __restrict__ w, int64_t cols, int64_t ld, float eps) { __shared__ float sh[32]; @@ -1472,6 +1498,14 @@ void gather_rows16(const uint16_t* x16, const int32_t* src, uint16_t* dst16, int } void moe_combine(const float* Dm, const int32_t* slot, const float* w, const float* shared, const float* sg, float* bo, int64_t T, void* stream) { +#ifndef STRATA_W_NO_COMB + if (((reinterpret_cast(Dm) | reinterpret_cast(shared) | reinterpret_cast(bo)) & 15) == 0) { + moe_combine4_kernel<<>>( + Dm, slot, w, reinterpret_cast(shared), sg, reinterpret_cast(bo), T); + check("moe_combine"); + return; + } +#endif moe_combine_kernel<<>>(Dm, slot, w, shared, sg, bo, T); check("moe_combine"); } diff --git a/src/prefill/moe_fused_iq.cu b/src/prefill/moe_fused_iq.cu index d07b9d1a..d61cc29b 100644 --- a/src/prefill/moe_fused_iq.cu +++ b/src/prefill/moe_fused_iq.cu @@ -204,6 +204,19 @@ __device__ __forceinline__ uint4 sign_entry(int i, bool parity) { } #endif // 8 nibbles of q4 through a 16-entry int8 table (4 words): the low nibbles' values in .x, the high ones' in .y +// W (X5): direct-selector form on gfx: p = low 3 bits of each nibble picks within the table half, bit 3 picks the half; +// exhaustively bit-exact over all 2^32 inputs (X5). Disable with -DSTRATA_W_NO_T16. +#if defined(__HIPCC__) && !defined(STRATA_W_NO_T16) +__device__ __forceinline__ uint32_t table16_one(uint32_t x, const uint32_t (&t)[4]) { + const uint32_t p = x & 0x07070707u; + const uint32_t a = __builtin_amdgcn_perm(t[1], t[0], p), b = __builtin_amdgcn_perm(t[3], t[2], p); + return __builtin_amdgcn_perm(b, a, ((x >> 1) & 0x04040404u) | 0x03020100u); +} +__device__ __forceinline__ void table16(uint32_t q4, const uint32_t (&t)[4], uint32_t& lo, uint32_t& hi) { + lo = table16_one(q4, t); + hi = table16_one(q4 >> 4, t); +} +#else __device__ __forceinline__ void table16(uint32_t q4, const uint32_t (&t)[4], uint32_t& lo, uint32_t& hi) { uint32_t tmp[2]; const uint32_t sel = 0x32103210u | ((q4 & 0x88888888u) >> 1); @@ -216,6 +229,7 @@ __device__ __forceinline__ void table16(uint32_t q4, const uint32_t (&t)[4], uin lo = __byte_perm(tmp[0], tmp[1], 0x6420); hi = __byte_perm(tmp[0], tmp[1], 0x7531); } +#endif // Raw bytes of sub-block `ib` of the block at `bp` (IQ: the 256-value super-block, ib 0..7; Q2_0: the 64-value block, // ib 0..1; IQ4_NL: the 32-value block). @@ -661,8 +675,10 @@ __device__ __forceinline__ nw_i8 nw_wmma(nw_i4 a, nw_i4 b, nw_i8 c) { } __device__ __forceinline__ nw_i4 nw_u4(uint4 v) { return nw_i4{(int) v.x, (int) v.y, (int) v.z, (int) v.w}; } -template -__global__ void __launch_bounds__(NW_THREADS) +// W (X1): ALIAS = the H tile lives on the weight buffers (one extra barrier); LB > 0 = amdgpu_waves_per_eu(LB) (VGPR cap). +// Disable both with -DSTRATA_W_NO_OCC (the launch sites then use and grid factor wgp_blocks). +template +__global__ void __launch_bounds__(NW_THREADS) __attribute__((amdgpu_waves_per_eu(LB > 0 ? LB : 1))) native_w11_kernel(const Batch b, const NativeGeom geo, const Tables tb, const uint8_t* __restrict__ act, const int32_t* __restrict__ src, uint8_t* __restrict__ out, float* __restrict__ dm) { #if STRATA_NAT_W11 @@ -680,7 +696,9 @@ native_w11_kernel(const Batch b, const NativeGeom geo, const Tables tb, const ui ? sign_entries(WT) : 1; __shared__ __align__(16) uint4 ssign[SGN]; // the signs of a sign byte, as byte masks __shared__ int srow[kTileRows]; - __shared__ float hs[GU ? kTileRows : 1][GU ? 65 : 1]; + __shared__ float hs_sep[(GU && !ALIAS) ? kTileRows : 1][65]; + static_assert(!ALIAS || (size_t) kTileRows * 65 * 4 <= (size_t) 2 * NW_ROWS * WLD, "H tile must fit the weight buffers"); + float(*hs)[65] = ALIAS ? reinterpret_cast(wtbuf) : hs_sep; const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; const int wm = wave & 3, wn = wave >> 2, l16 = lane & 15, hi = lane >> 4; if constexpr (grid_bytes(WT) > 0) { @@ -811,6 +829,7 @@ native_w11_kernel(const Batch b, const NativeGeom geo, const Tables tb, const ui } } if constexpr (GU) { + if constexpr (ALIAS) __syncthreads(); // every wave is done reading the weight buffers if (on) { #pragma unroll for (int mt = 0; mt < 2; ++mt) @@ -1030,11 +1049,21 @@ void experts_native(const Batch& b, const NativeGeom& g, int n_expert, int64_t n #if defined(__HIPCC__) { const int64_t tiles = (n + kTileRows - 1) / kTileRows + (b.e1 - b.e0); - const unsigned g_gu = (unsigned) std::min(tiles * (1280 / NW_ROWS), (int64_t) d.sms * wgp_blocks(d.occ)); - const unsigned g_d = (unsigned) std::min(tiles * (2560 / NW_ROWS), (int64_t) d.sms * wgp_blocks(d.occ)); + // W (X1): LDS alias of the H tile + waves_per_eu(8) (192 VGPRs) + 4 blocks per WGP, only for the types whose + // kernels do not spill under the cap (measured: gate/up IQ2_*, IQ3_*, IQ4_XS 0-5 regs; down IQ4_NL 11, Q8_0 / Q2_0 0; + // Q4_K / Q5_K gate/up and Q5_1 down spill 100+ and keep the old launch). +#ifdef STRATA_W_NO_OCC + const bool occ_gu = false, occ_d = false; +#else + const bool occ_gu = g.gu_type == T_IQ2_XXS || g.gu_type == T_IQ2_XS || g.gu_type == T_IQ2_S || + g.gu_type == T_IQ3_XXS || g.gu_type == T_IQ3_S || g.gu_type == T_IQ4_XS; + const bool occ_d = g.d_type == T_Q2_0 || g.d_type == T_Q8_0 || g.d_type == T_IQ4_NL; +#endif + const unsigned g_gu = (unsigned) std::min(tiles * (1280 / NW_ROWS), (int64_t) d.sms * (occ_gu ? 4 : wgp_blocks(d.occ))); + const unsigned g_d = (unsigned) std::min(tiles * (2560 / NW_ROWS), (int64_t) d.sms * (occ_d ? 4 : wgp_blocks(d.occ))); const uint8_t* xa8 = (const uint8_t*) xa; uint8_t* ha8 = (uint8_t*) ha; -#define STRATA_NW_GU(T) native_w11_kernel<<>>(b, g, tb, xa8, src, ha8, nullptr) +#define STRATA_NW_GU(T) do { if (occ_gu) native_w11_kernel<<>>(b, g, tb, xa8, src, ha8, nullptr); else native_w11_kernel<<>>(b, g, tb, xa8, src, ha8, nullptr); } while (0) switch (g.gu_type) { case T_IQ2_XXS: STRATA_NW_GU(T_IQ2_XXS); break; case T_IQ2_XS: STRATA_NW_GU(T_IQ2_XS); break; @@ -1046,7 +1075,7 @@ void experts_native(const Batch& b, const NativeGeom& g, int n_expert, int64_t n default: STRATA_NW_GU(T_IQ4_XS); break; } #undef STRATA_NW_GU -#define STRATA_NW_D(T) native_w11_kernel<<>>(b, g, tb, ha8, src, nullptr, dm) +#define STRATA_NW_D(T) do { if (occ_d) native_w11_kernel<<>>(b, g, tb, ha8, src, nullptr, dm); else native_w11_kernel<<>>(b, g, tb, ha8, src, nullptr, dm); } while (0) if (g.d_type == T_Q2_0) STRATA_NW_D(T_Q2_0); else if (g.d_type == T_Q5_1) STRATA_NW_D(T_Q5_1); else if (g.d_type == T_Q8_0) STRATA_NW_D(T_Q8_0);