From 6a5be385c61f5e688a3576775aca41558a29605b Mon Sep 17 00:00:00 2001 From: ATIVX928 <27274927+ATIVX928@users.noreply.github.com> Date: Mon, 5 Oct 2026 17:01:13 +0000 Subject: [PATCH 01/36] audit: where the int8 KV read decodes, and whether it is vectorized --- .../2026-10-03-v100-kv-int8-read/README.md | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 bench/results/2026-10-03-v100-kv-int8-read/README.md diff --git a/bench/results/2026-10-03-v100-kv-int8-read/README.md b/bench/results/2026-10-03-v100-kv-int8-read/README.md new file mode 100644 index 00000000..d2fe6bb1 --- /dev/null +++ b/bench/results/2026-10-03-v100-kv-int8-read/README.md @@ -0,0 +1,32 @@ +# V100 / Swift IQ2_XS / 32k / --kv int8: the KV read path + +Test bed: 2x Tesla V100-SXM2-16GB (SM 7.0), CUDA 12.8, one card. No full-engine run; kernel microbench only. + +## 1. Audit - where int8 KV is decoded, and whether it is vectorized + +The default decode path is the fused split-K attention (`g_fast_attn = true`, `src/core/layer.cpp:42`, chosen at +`layer.cpp:950-952`), which reads the pools directly - no gather: + +- K decode: `load8_q8`, `src/kernels/cuda/qsa_decode_attn.cu:46-54`. One lane reads 8 int8 as a `uint2` (8 B) and + one fp16 scale per 64-group, then scalar `(float)c * sc` x8 (I2F + FMUL each). The *load* is vectorized, the + *decode* is scalar. +- V decode: `attn_chunk_kernel`, `qsa_decode_attn.cu:158-179`. Thread `t` owns dimension `t` for all 12 heads: + one int8 load + one fp16 scale + one I2F+FMUL per cell, then 12 FMAs. 1 byte/thread/cell, coalesced to 256 B. +- MTP draft/verify use the same kernel by batch: `src/core/mtp.cpp:503`, `src/core/verify.cpp:647` + (`qsa_decode_attn_batch`). + +The non-fast fallback gathers int8 into an fp16 scratch first, then attends over it: + +- `kv_gather_q8_kernel`, `src/kernels/cuda/kv_q8.cu:69-99`: `char4` load (4 int8) + 2 fp16 scales, 8 scalar + converts, `ushort4` fp16 store. 4 values/thread. +- `qsa_attend_kernel` then reads the fp16 scratch: `qsa.cu:462-467` (K dot), `qsa.cu:502-505` (V), 2 B/value. + +The KV-streaming copy is already wide: `copy_kernel`, `src/kernels/cuda/kv_stream.cu:161-171`, `uint4` (16 B). + +## 2. Vectorization + +TBD + +## 3. int8 vs q4_0 vs k8v4 at 32k + +TBD From 132faae7cf18b3a527507c8a1b8bd7ea417d9482 Mon Sep 17 00:00:00 2001 From: ATIVX928 <27274927+ATIVX928@users.noreply.github.com> Date: Mon, 5 Oct 2026 17:01:54 +0000 Subject: [PATCH 02/36] kv_q8: the gather decodes 8 int8 per thread (bitwise, +11% on the 32k microbench) The experimental build (-DSTRATA_EXPERIMENTAL_SM60=ON, Pascal/Volta) gains a kv_gather_q8_wide_kernel: one uint2 (8 B) load of codes, one uint4 (16 B) store of the dequantized fp16 and one scale per thread instead of two. The 8 values lie in one 64-value group and the arithmetic is unchanged ((float) code * scale -> f16_from_f32), so the output is byte-identical. The ready-made engine keeps exactly the 4-wide kv_gather_q8_kernel and launches it unchanged, so its gather is bit for bit the release engine's. On a device below sm_75 the wide kernel is selected at run time inside the experimental build (STRATA_Q8_GATHER_WIDE=0 opts out). Measured on 2x Tesla V100-SXM2-16GB (SM 7.0), CUDA 12.8, one card: +11.4% on the 32k gather microbench (15.85 -> 14.05 us/call, 401 -> 452 GB/s). kv_q8_parity stays OK at worst INT8-vs-FP16 error 0.590 quantization steps. --- .../2026-10-03-v100-kv-int8-read/README.md | 21 ++++- src/kernels/cuda/kv_q8.cu | 84 ++++++++++++++++++- src/kernels/kv_q8_parity.cpp | 51 ++++++++++- 3 files changed, 153 insertions(+), 3 deletions(-) diff --git a/bench/results/2026-10-03-v100-kv-int8-read/README.md b/bench/results/2026-10-03-v100-kv-int8-read/README.md index d2fe6bb1..75dcf88a 100644 --- a/bench/results/2026-10-03-v100-kv-int8-read/README.md +++ b/bench/results/2026-10-03-v100-kv-int8-read/README.md @@ -25,7 +25,26 @@ The KV-streaming copy is already wide: `copy_kernel`, `src/kernels/cuda/kv_strea ## 2. Vectorization -TBD +The gather (`kv_gather_q8_kernel`) was 4 values/thread: two `char4` (4 B) loads + two `ushort4` (8 B) stores. The +experimental build (`-DSTRATA_EXPERIMENTAL_SM60=ON`, Pascal/Volta) adds an 8-wide `kv_gather_q8_wide_kernel`: one +`uint2` (8 B) load of codes, one `uint4` (16 B) store of the dequantized fp16, one scale per thread instead of two. +The 8 values lie in one 64-value group, and the arithmetic is unchanged (`(float) code * scale -> f16_from_f32`, +packed two halfs per 32-bit word), so the output is byte-identical. The ready-made engine keeps exactly the +4-wide kernel. + +`kv_q8_parity`: OK, worst INT8-vs-FP16 error 0.590 steps (bitwise codes, scales and gather; unchanged). + +Microbench (`kv_q8_parity --bench`, 2,051 cells / 2 KV heads / 256 dims, 32k pool, random cells, V100): + +| | us/call | GB/s | +|---|---|---| +| before (4-wide) | 15.85 | 401 | +| after (8-wide) | 14.05 | 452 | + ++11.4% on the gather. The default decode path (`g_fast_attn`) does not gather; its decode (`load8_q8`, +`qsa_decode_attn.cu:46-54`) already reads 8 int8 with one `uint2` and is arithmetic-bound (8 I2F + 8 FMUL per +cell), which `__byte_perm`/half2 cannot improve while staying bit-exact. The gather is what the non-fast, +streaming and hybrid paths use. ## 3. int8 vs q4_0 vs k8v4 at 32k diff --git a/src/kernels/cuda/kv_q8.cu b/src/kernels/cuda/kv_q8.cu index 2965f233..a03e171b 100644 --- a/src/kernels/cuda/kv_q8.cu +++ b/src/kernels/cuda/kv_q8.cu @@ -73,7 +73,8 @@ __global__ void kv_append_q8_kernel(int8_t* __restrict__ k_q, int8_t* __restrict } } -// One thread = 4 consecutive values of one cell and head (as the FP16 gather does with uint2). +// One thread = 4 consecutive values of one cell and head (as the FP16 gather does with uint2). This is the gather +// the ready-made engine runs; the experimental build's 8-wide kernel is below it. __global__ void kv_gather_q8_kernel(const int8_t* __restrict__ k_q, const int8_t* __restrict__ v_q, const uint16_t* __restrict__ k_scale, const uint16_t* __restrict__ v_scale, const int32_t* __restrict__ table, const int32_t* __restrict__ ids, @@ -106,6 +107,76 @@ __global__ void kv_gather_q8_kernel(const int8_t* __restrict__ k_q, const int8_t reinterpret_cast(v_scratch)[dst] = vo; } +#if defined(STRATA_EXPERIMENTAL_SM60) +// One thread = 8 consecutive values of one cell and head: an 8-byte `uint2` load of codes and a 16-byte `uint4` +// store of the dequantized fp16. The 8 values share one 64-value group, so one scale is loaded per thread and +// the arithmetic stays `(float) code * scale -> f16_from_f32`, i.e. bitwise the same as the previous 4-wide +// version (whose char4 loads became these uint2 loads). `load8_q8` in qsa_decode_attn.cu reads 8 int8 the +// same way; this is the gather's other half. Only in the experimental build (-DSTRATA_EXPERIMENTAL_SM60=ON): +// the ready-made engine keeps exactly the 4-wide kernel above, so its gather is bit for bit the release engine's. +__device__ __forceinline__ uint32_t q8_pair_to_f16x2(const int8_t* c, float s) { + return (uint32_t) f16_from_f32((float) c[0] * s) | ((uint32_t) f16_from_f32((float) c[1] * s) << 16); +} + +__global__ void kv_gather_q8_wide_kernel(const int8_t* __restrict__ k_q, const int8_t* __restrict__ v_q, + const uint16_t* __restrict__ k_scale, const uint16_t* __restrict__ v_scale, + const int32_t* __restrict__ table, const int32_t* __restrict__ ids, + const int32_t* __restrict__ step, int kv_heads, int head_dim, int page_size, + uint16_t* __restrict__ k_scratch, uint16_t* __restrict__ v_scratch) { + const long long n_ids = (long long) __ldg(step + kStepWidth); + const int per = head_dim / 8; + const long long total = n_ids * kv_heads * per; + const long long i = blockIdx.x * (long long) blockDim.x + threadIdx.x; + if (i >= total) return; + const long long id = i / (kv_heads * (long long) per); + const int rem = (int) (i % (kv_heads * (long long) per)); + const int h = rem / per, q8 = rem - h * per; + const int cell = ids[id]; + const long long page = (long long) table[cell / page_size]; + const long long row = (page * kv_heads + h) * page_size + (cell % page_size); + const int d = q8 * 8; // 8 divides KV_Q8_GROUP, so all 8 values share the group's scale + const int groups = head_dim / KV_Q8_GROUP; + const float ks = f32_from_f16(k_scale[row * groups + d / KV_Q8_GROUP]); + const float vs = f32_from_f16(v_scale[row * groups + d / KV_Q8_GROUP]); + const uint2 kraw = *reinterpret_cast(k_q + row * head_dim + d); // one 8-byte load + const uint2 vraw = *reinterpret_cast(v_q + row * head_dim + d); + const int8_t* kc = reinterpret_cast(&kraw); + const int8_t* vc = reinterpret_cast(&vraw); + uint4 ko, vo; + ko.x = q8_pair_to_f16x2(kc + 0, ks); ko.y = q8_pair_to_f16x2(kc + 2, ks); + ko.z = q8_pair_to_f16x2(kc + 4, ks); ko.w = q8_pair_to_f16x2(kc + 6, ks); + vo.x = q8_pair_to_f16x2(vc + 0, vs); vo.y = q8_pair_to_f16x2(vc + 2, vs); + vo.z = q8_pair_to_f16x2(vc + 4, vs); vo.w = q8_pair_to_f16x2(vc + 6, vs); + const long long dst = (id * kv_heads + h) * (long long) per + q8; + reinterpret_cast(k_scratch)[dst] = ko; + reinterpret_cast(v_scratch)[dst] = vo; +} + +// The current device is below sm_75 (per device: a layer split can mix cards); STRATA_Q8_GATHER_WIDE=0 turns the +// 8-wide gather off (A/B). The wide kernel is bitwise identical, so this only decides speed. Mirrors +// qsa_decode_attn.cu's pre75_attn. +bool pre75_q8_gather() { + static const bool off = [] { + const char* e = std::getenv("STRATA_Q8_GATHER_WIDE"); + return e != nullptr && e[0] == '0'; + }(); + static int cc[64] = {}; + int dev = 0; + if (off) return false; + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; } + if (cc[dev] == 0) { + int major = 0, minor = 0; + if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess || + cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) != cudaSuccess) { + cudaGetLastError(); + return false; + } + cc[dev] = 10 * major + minor; + } + return cc[dev] < 75; +} +#endif // STRATA_EXPERIMENTAL_SM60 + } // namespace 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, @@ -136,6 +207,17 @@ void kv_gather_q8_step(const int8_t* k_q, const int8_t* v_q, const uint16_t* k_s const QsaShapes& s, uint16_t* k_scratch, uint16_t* v_scratch, void* stream) { validate(s, "kv_gather_q8"); if (max_ids <= 0) return; +#if defined(STRATA_EXPERIMENTAL_SM60) + if (pre75_q8_gather()) { + const long long total = max_ids * s.n_head_kv * (s.head_dim / 8); + const unsigned blocks = (unsigned) ((total + 255) / 256); + kv_gather_q8_wide_kernel<<>>( + k_q, v_q, k_scale, v_scale, page_table, ids, step, (int) s.n_head_kv, (int) s.head_dim, + (int) s.page_size, k_scratch, v_scratch); + check("kv_gather_q8 wide launch"); + return; + } +#endif const long long total = max_ids * s.n_head_kv * (s.head_dim / 4); const unsigned blocks = (unsigned) ((total + 255) / 256); kv_gather_q8_kernel<<>>( diff --git a/src/kernels/kv_q8_parity.cpp b/src/kernels/kv_q8_parity.cpp index 733d7c7f..f60eb93a 100644 --- a/src/kernels/kv_q8_parity.cpp +++ b/src/kernels/kv_q8_parity.cpp @@ -29,7 +29,56 @@ void ck(cudaError_t e, const char* w) { template T* dalloc(size_t n) { T* p = nullptr; ck(cudaMalloc(&p, n * sizeof(T) + 64), "malloc"); ck(cudaMemset(p, 0, n * sizeof(T) + 64), "memset"); return p; } } // namespace -int main() { +// A decode-shaped microbench: a 32k pool, the 2,051-cell selection the QSA decoder gathers per layer, random +// cells (so the reads miss L2). Reports the gather's effective traffic per call and GB/s. Not part of the test. +int bench() { + k::QsaShapes s = k::qsa_real_shapes(); + const int H = (int) s.n_head_kv, D = (int) s.head_dim, P = (int) s.page_size, G = D / k::KV_Q8_GROUP; + const int ctx = 32768, pages = ctx / P; + const long long rows = (long long) pages * H * P; + const int max_ids = (int) k::qsa_selection_width(ctx, s); + std::mt19937 rng(7); + std::vector kq((size_t) rows * D), vq((size_t) rows * D); + std::vector ks((size_t) rows * G), vs((size_t) rows * G); + for (auto& x : kq) x = (int8_t) (rng() & 0xFF); + for (auto& x : vq) x = (int8_t) (rng() & 0xFF); + for (auto& x : ks) x = (uint16_t) (0x3000 | (rng() & 0x3FF)); + for (auto& x : vs) x = (uint16_t) (0x3000 | (rng() & 0x3FF)); + std::vector table(pages); + for (int i = 0; i < pages; ++i) table[i] = i; + std::shuffle(table.begin(), table.end(), rng); + std::vector ids(max_ids); + for (auto& x : ids) x = (int32_t) (rng() % ctx); + int8_t* d_kq = dalloc(kq.size()); ck(cudaMemcpy(d_kq, kq.data(), kq.size(), cudaMemcpyHostToDevice), "up"); + int8_t* d_vq = dalloc(vq.size()); ck(cudaMemcpy(d_vq, vq.data(), vq.size(), cudaMemcpyHostToDevice), "up"); + uint16_t* d_ks = dalloc(ks.size()); ck(cudaMemcpy(d_ks, ks.data(), ks.size() * 2, cudaMemcpyHostToDevice), "up"); + uint16_t* d_vs = dalloc(vs.size()); ck(cudaMemcpy(d_vs, vs.data(), vs.size() * 2, cudaMemcpyHostToDevice), "up"); + int32_t* d_table = dalloc(pages); ck(cudaMemcpy(d_table, table.data(), pages * 4, cudaMemcpyHostToDevice), "up"); + int32_t* d_ids = dalloc(max_ids); ck(cudaMemcpy(d_ids, ids.data(), max_ids * 4, cudaMemcpyHostToDevice), "up"); + int32_t* d_step = dalloc(k::kStepCount); + int32_t hstep[k::kStepCount] = {0, 0, 0, max_ids}; + ck(cudaMemcpy(d_step, hstep, sizeof hstep, cudaMemcpyHostToDevice), "up"); + uint16_t* k8 = dalloc((size_t) max_ids * H * D); + uint16_t* v8 = dalloc((size_t) max_ids * H * D); + for (int i = 0; i < 5; ++i) k::kv_gather_q8_step(d_kq, d_vq, d_ks, d_vs, d_table, d_ids, d_step, max_ids, s, k8, v8, nullptr); + ck(cudaDeviceSynchronize(), "warmup"); + const int reps = 200; + cudaEvent_t e0, e1; cudaEventCreate(&e0); cudaEventCreate(&e1); + cudaEventRecord(e0); + for (int r = 0; r < reps; ++r) k::kv_gather_q8_step(d_kq, d_vq, d_ks, d_vs, d_table, d_ids, d_step, max_ids, s, k8, v8, nullptr); + cudaEventRecord(e1); ck(cudaEventSynchronize(e1), "time"); + float ms = 0; cudaEventElapsedTime(&ms, e0, e1); + const double bytes = (double) max_ids * H * D * 2 // K + V codes + + (double) max_ids * H * G * 2 * 2 // K + V scales + + (double) max_ids * H * D * 2 * 2; // K + V fp16 scratch write + const double us = ms * 1000.0 / reps; + std::printf("kv_gather_q8 bench: %d ids, %.1f us/call, %.1f GB/s (%.2f MB moved)\n", max_ids, us, + bytes / (us * 1e-6) / 1e9, bytes / 1e6); + return 0; +} + +int main(int argc, char** argv) { + for (int i = 1; i < argc; ++i) if (!std::strcmp(argv[i], "--bench")) return bench(); k::QsaShapes s = k::qsa_real_shapes(); s.page_size = 64; // several pages in a small pool const int H = (int) s.n_head_kv, D = (int) s.head_dim, P = (int) s.page_size, G = D / k::KV_Q8_GROUP; From 1e14e6469e26d89c238ac1c67b58db8b9bf7a7a8 Mon Sep 17 00:00:00 2001 From: ATIVX928 <27274927+ATIVX928@users.noreply.github.com> Date: Mon, 5 Oct 2026 17:17:51 +0000 Subject: [PATCH 03/36] kernels (sm_70): the prompt attention's latency pipeline (mma884 kernel) Port of oldlocal commit 4672cf9 ("kernels (sm_70): the prompt attention's latency pipeline - 2.2x over the FP32 kernel at 32K") onto the #600 prompt_attn_v70_kernel, the m8n8k4 Volta kernel now inline in qsa_prompt_attn.cu. Still gated on STRATA_EXPERIMENTAL_SM60, so the ready-made engine keeps exactly the code it had. Two of the commit's three changes port; the third (splitting the dependent WMMA chains into f0/f1 and fh/fl) is already inherent to the mma884 kernel - its scores run two tg[rb] chains and its p.v four tmp[rb][nt] chains - so porting it would only change the summation order. The two ported, measured on a V100-SXM2-16GB (CUDA 12.8): * the staging loop issues every global load of a thread before any of its stores (2-4 in flight), instead of paying the HBM latency per piece; * the next chunk's ids/page-table lookups double-buffer (row[2][CH]) and run just before the previous p.v, where their latency hides. The original commit measured, on the #371 kernel, 2,048 queries of a 32K selection: 34.4 -> 15.8 ms (2.18x) int8, 33.5 -> 15.4 ms (2.17x) fp16 KV, 35.6 -> 20.3 ms (1.76x) K8V4 (its q4_0 V dequantizes to FP16 at staging, the sm_75/80 kernel's same trade). This port, same 2,048 queries of a 32K selection (qsa_prompt_attn_sm70_bench, which also gained the K8V4 pools): the Volta kernel goes int8 12.11 -> 10.25 ms, fp16 KV 25.70 -> 17.39 ms, K8V4 25.71 -> 24.12 ms, so against the FP32 decode kernel int8 rises 1.73x -> 2.05x and fp16 0.80x -> 1.18x (K8V4, 0.85x -> 0.91x, keeps main's #600 dequant-to-FP16 trade). qsa_prompt_attn_parity passes all four cases. An A/B against the unpatched kernel shows the kernel's output is unchanged - every FP64 and new-vs-old figure is identical before and after (int8 5.08e-6, fp16 5.29e-6 vs FP64, within the 4x gate). --- CMakeLists.txt | 7 + bench/qsa_prompt_attn_sm70_bench.cpp | 198 +++++++++++++++++++++++++++ src/kernels/cuda/qsa_prompt_attn.cu | 89 ++++++++---- 3 files changed, 266 insertions(+), 28 deletions(-) create mode 100644 bench/qsa_prompt_attn_sm70_bench.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index e28abd9b..38c34127 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -400,6 +400,13 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_include_directories(qsa_prompt_attn_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) target_link_libraries(qsa_prompt_attn_parity PRIVATE strata_kernels CUDA::cudart) endif() + # PR #600: the Volta (sm_70) prompt attention's latency pipeline against the FP32 kernel it replaces. Only in the + # experimental sm_60/sm_70 build, where prompt_attn_v70_kernel is compiled in. + if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA AND STRATA_EXPERIMENTAL_SM60) + add_executable(qsa_prompt_attn_sm70_bench bench/qsa_prompt_attn_sm70_bench.cpp) + target_include_directories(qsa_prompt_attn_sm70_bench PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) + target_link_libraries(qsa_prompt_attn_sm70_bench PRIVATE strata_kernels CUDA::cudart) + endif() # #512: the top-k's active-block bound (Turing's dispatch, forced on any card by STRATA_TOPK_ACTIVE_ANY) against # the capacity rule, selected ids bitwise if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA) diff --git a/bench/qsa_prompt_attn_sm70_bench.cpp b/bench/qsa_prompt_attn_sm70_bench.cpp new file mode 100644 index 00000000..74f5475c --- /dev/null +++ b/bench/qsa_prompt_attn_sm70_bench.cpp @@ -0,0 +1,198 @@ +// bench/qsa_prompt_attn_sm70_bench.cpp - the Volta (sm_70) prompt attention against the FP32 kernel it replaces. +// +// Same synthetic pools and prompt-shaped selections as src/kernels/qsa_prompt_attn_parity.cpp (GPU, no model), but +// timing is the point: for each KV format (int8, fp16) and a sweep of query counts it times +// `qsa_decode_attn_batch` (the FP32 fallback, in batches of 32 as prefill.cpp calls it) against +// `qsa_prompt_attn_batch` with CUDA events, and reports the output difference. Run it on one card: +// flock /tmp/opencode/gpu.lock -c 'CUDA_VISIBLE_DEVICES=0 ./qsa_prompt_attn_sm70_bench [ctx=32768] [nq=2048] [reps=10]' +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/qsa_decode_attn.hpp" +#include "strata/kernels/qsa_prompt_attn.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace k = strata::kernels; + +namespace { +void ck(cudaError_t e, const char* w) { + if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); } +} +template T* up(const std::vector& h) { + T* d = nullptr; + ck(cudaMalloc(&d, h.size() * sizeof(T) + 64), "malloc"); + ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload"); + return d; +} +uint16_t f2h(float f) { __half h = __float2half(f); return *reinterpret_cast(&h); } + +// one synthetic prompt: the widest selection the shape has (2,051 cells at 32K), a recent window plus older cells +// that drift slowly from query to query, as qsa_prompt_attn_parity builds them. fmt 1 int8 KV, 0 fp16 KV, +// 2 hybrid K8V4 (int8 K, q4_0 V - the Q2_0 engine's pools) +void build(int fmt, int64_t ctx, int64_t nq, std::vector& kq, std::vector& vq, std::vector& ks, + std::vector& vs, std::vector& kh, std::vector& vh, std::vector& vq4, + std::vector& table, std::vector& ids, std::vector& steps, std::vector& q, + int64_t& cap) { + const k::QsaShapes s = k::qsa_real_shapes(); + const int64_t HD = s.head_dim, NKV = s.n_head_kv, NH = s.n_head, PS = s.page_size; + const int64_t pages = (ctx + PS - 1) / PS, rows = pages * NKV * PS; + std::mt19937 rng(1234 + fmt); + std::normal_distribution nd(0.f, 1.f); + std::uniform_int_distribution code(-127, 127); + std::uniform_real_distribution sc(0.005f, 0.03f); + if (fmt == 1 || fmt == 2) { + kq.resize(rows * HD); ks.resize(rows * 4); + for (auto& x : kq) x = (int8_t) code(rng); + for (auto& x : ks) x = f2h(sc(rng)); + if (fmt == 1) { + vq.resize(rows * HD); vs.resize(rows * 4); + for (auto& x : vq) x = (int8_t) code(rng); + for (auto& x : vs) x = f2h(sc(rng)); + } else { + vq4.resize((size_t) (rows * (HD / 32) * 18)); // q4_0 blocks: a finite fp16 scale + random nibbles + for (size_t i = 0; i < vq4.size(); i += 18) { + const uint16_t d = f2h(sc(rng)); + vq4[i] = (uint8_t) d; vq4[i + 1] = (uint8_t) (d >> 8); + for (int j = 2; j < 18; ++j) vq4[i + j] = (uint8_t) rng(); + } + } + } else { + kh.resize(rows * HD); vh.resize(rows * HD); + for (auto& x : kh) x = f2h(nd(rng) * 1.5f); + for (auto& x : vh) x = f2h(nd(rng)); + } + table.resize(pages); + for (int64_t i = 0; i < pages; ++i) table[i] = (int32_t) i; + std::shuffle(table.begin(), table.end(), rng); + cap = k::qsa_selection_width(ctx, s); + ids.assign((size_t) (nq * cap), 0); + steps.assign((size_t) (nq * k::kStepCount), 0); + q.assign((size_t) (nq * NH * HD), 0.f); + for (auto& x : q) x = nd(rng) * 2.0f; + std::vector old_cells; + for (int64_t i = 0; i < nq; ++i) { + const int64_t pos = ctx - nq + i, nkv = pos + 1; + const int64_t w = k::qsa_selection_width(nkv, s); + int32_t* sel = ids.data() + i * cap; + steps[i * k::kStepCount + k::kStepWidth] = (int32_t) w; + if (w == nkv) { + for (int64_t c = 0; c < w; ++c) sel[c] = (int32_t) c; + continue; + } + const int64_t recent = 512, older = w - recent; + if ((int64_t) old_cells.size() != older) { + std::vector all((size_t) (nkv - recent)); + for (int64_t c = 0; c < nkv - recent; ++c) all[c] = (int32_t) c; + std::shuffle(all.begin(), all.end(), rng); + old_cells.assign(all.begin(), all.begin() + older); + } else { + std::uniform_int_distribution pick(0, older - 1), any(0, nkv - recent - 1); + for (int r = 0; r < older / 32; ++r) { + const int32_t c = (int32_t) any(rng); + if (std::find(old_cells.begin(), old_cells.end(), c) == old_cells.end()) old_cells[pick(rng)] = c; + } + } + std::vector v(old_cells); + for (int64_t c = nkv - recent; c < nkv; ++c) v.push_back((int32_t) c); + std::sort(v.begin(), v.end()); + std::copy(v.begin(), v.end(), sel); + } +} + +float time_ms(const std::function& f, int reps) { + cudaEvent_t e0, e1; + ck(cudaEventCreate(&e0), "event"); + ck(cudaEventCreate(&e1), "event"); + f(); + ck(cudaDeviceSynchronize(), "warm"); + ck(cudaEventRecord(e0), "event"); + for (int r = 0; r < reps; ++r) f(); + ck(cudaEventRecord(e1), "event"); + ck(cudaEventSynchronize(e1), "time"); + float ms = 0; + ck(cudaEventElapsedTime(&ms, e0, e1), "time"); + cudaEventDestroy(e0); + cudaEventDestroy(e1); + return ms / reps; +} + +void run(int fmt, int64_t ctx, int64_t nq, int reps) { + const k::QsaShapes s = k::qsa_real_shapes(); + const int64_t HD = s.head_dim, NH = s.n_head; + std::vector kq, vq; + std::vector ks, vs, kh, vh; + std::vector vq4; + std::vector table, ids, steps; + std::vector q; + int64_t cap = 0; + build(fmt, ctx, nq, kq, vq, ks, vs, kh, vh, vq4, table, ids, steps, q, cap); + 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 if (fmt == 2) { pl.k_q = up(kq); pl.k_scale = up(ks); pl.v_q4 = up(vq4); } + else { pl.k_pool = up(kh); pl.v_pool = up(vh); } + pl.page_table = up(table); + const int32_t* d_ids = up(ids); + const int32_t* d_steps = up(steps); + const float* d_q = up(q); + float *d_old = nullptr, *d_new = nullptr, *scratch = nullptr; + const int64_t batch = 32; + ck(cudaMalloc(&d_old, nq * NH * HD * 4), "malloc"); + ck(cudaMalloc(&d_new, nq * NH * HD * 4), "malloc"); + ck(cudaMalloc(&scratch, batch * k::qsa_decode_attn_scratch_floats(cap, s) * 4), "malloc"); + std::printf("# %s KV, ctx %lld, selection %lld cells, %lld queries of %lld heads x %lld dims\n", + fmt == 1 ? "int8" : fmt == 2 ? "int8+q4 V (K8V4)" : "fp16", (long long) ctx, (long long) cap, + (long long) nq, (long long) NH, (long long) HD); + const int64_t counts[] = {16, 64, 256, 1024, 2048, 4096}; + for (int64_t nqi : counts) { + if (nqi > nq) continue; + auto old_run = [&]() { + for (int64_t t0 = 0; t0 < nqi; t0 += batch) + k::qsa_decode_attn_batch(d_q + t0 * NH * HD, pl, d_ids + t0 * cap, d_steps + t0 * k::kStepCount, cap, + s, scratch, d_old + t0 * NH * HD, std::min(batch, nqi - t0), nullptr); + }; + auto new_run = [&]() { + if (!k::qsa_prompt_attn_batch(d_q, pl, d_ids, d_steps, cap, s, d_new, nqi, nullptr)) { + std::fprintf(stderr, "qsa_prompt_attn_batch refused the pools\n"); + std::exit(2); + } + }; + old_run(); new_run(); + ck(cudaDeviceSynchronize(), "run"); + std::vector o((size_t) (nqi * 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"); + double diff = 0, scale = 0; + for (size_t i = 0; i < o.size(); ++i) { + diff = std::max(diff, (double) std::fabs(o[i] - nw[i])); + scale = std::max(scale, (double) std::fabs(o[i])); + } + const float ms_old = time_ms(old_run, reps), ms_new = time_ms(new_run, reps); + std::printf("q %5lld: fp32 %8.3f ms volta %8.3f ms %5.2fx max|old-new| %.3g (%.2g of scale)\n", + (long long) nqi, ms_old, ms_new, ms_old / ms_new, diff, scale > 0 ? diff / scale : 0.0); + } + cudaFree((void*) d_ids); cudaFree((void*) d_steps); cudaFree((void*) d_q); cudaFree(d_old); cudaFree(d_new); + cudaFree(scratch); + cudaFree((void*) pl.k_q); cudaFree((void*) pl.v_q); cudaFree((void*) pl.k_scale); cudaFree((void*) pl.v_scale); + cudaFree((void*) pl.v_q4); + cudaFree((void*) pl.k_pool); cudaFree((void*) pl.v_pool); cudaFree((void*) pl.page_table); +} +} // namespace + +int main(int argc, char** argv) { + const int64_t ctx = argc > 1 ? std::atoll(argv[1]) : 32768; + const int64_t nq = argc > 2 ? std::atoll(argv[2]) : 2048; + const int reps = argc > 3 ? std::atoi(argv[3]) : 10; + run(1, ctx, nq, reps); + run(2, ctx, nq, reps); + run(0, ctx, nq, reps); + return 0; +} diff --git a/src/kernels/cuda/qsa_prompt_attn.cu b/src/kernels/cuda/qsa_prompt_attn.cu index bd99609d..8ec9acb3 100644 --- a/src/kernels/cuda/qsa_prompt_attn.cu +++ b/src/kernels/cuda/qsa_prompt_attn.cu @@ -789,7 +789,7 @@ struct Smem70 { float alpha[16]; float lsum[16]; float mrow[16]; - long long row[CH]; + long long row[2][CH]; // double-buffered pool rows: the next chunk's lookups hide under p.v }; template @@ -840,40 +840,54 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_v70_kernel(const float* _ #pragma unroll for (int i = 0; i < 8; ++i) acc[rb][nt][i] = 0.0f; - for (int c0 = 0; c0 < n; c0 += CH) { - const int nh = min(CH, n - c0); - if (t < CH) { - long long r = -1; - if (t < nh) { - const int cell = ids[c0 + t]; - const long long page = (long long) p.page_table[cell / page_size]; - r = (page * n_kv_heads + kvh) * page_size + (cell % page_size); - } - S.row[t] = r; + // the pool rows of a chunk: -1 past the selection and for a page the KV streaming left non-resident (the + // decode kernel masks those, so this kernel does too). Chunk 0's rows fill one buffer here; every later + // chunk's lookups fill the other just before the previous p.v, where their global latency hides. + int rbuf = 0; + if (t < CH) { + long long r = -1; + if (t < min(CH, n)) { + const int cell = ids[t]; + const long long page = (long long) p.page_table[cell / page_size]; + r = (page * n_kv_heads + kvh) * page_size + (cell % page_size); } - __syncthreads(); // rows ready; the previous chunk's p.v is done with k, v, s + S.row[0][t] = r; + } + for (int c0 = 0; c0 < n; c0 += CH, rbuf ^= 1) { + const int nh = min(CH, n - c0); + __syncthreads(); // rows ready; the previous chunk's p.v is done with k, v // gather the chunk's K and V rows (16-byte pieces; K8V4's V as q4_0 blocks dequantized to fp16) // and their scales { constexpr int KPIECES = HD * (int) sizeof(typename Smem::KElem) / 16; // per K row - for (int i = t; i < CH * KPIECES; i += THREADS) { - const int c = i / KPIECES, pc = i % KPIECES; - const long long r = S.row[c]; - uint4 kx = make_uint4(0, 0, 0, 0); + constexpr int KPT = (CH * KPIECES + THREADS - 1) / THREADS; + static_assert((CH * KPIECES) % THREADS == 0, "the staging pieces divide evenly"); + // issue every global load of a thread before any of its stores: they then overlap each other instead + // of paying the HBM latency one at a time + uint4 kx[KPT]; + int kc[KPT], kp[KPT]; +#pragma unroll + for (int s = 0; s < KPT; ++s) { + const int i = t + s * THREADS; + kc[s] = i / KPIECES; kp[s] = i % KPIECES; + const long long r = S.row[rbuf][kc[s]]; + kx[s] = make_uint4(0, 0, 0, 0); if (r >= 0) { if constexpr (KV_MODE == 0) - kx = __ldg(reinterpret_cast(p.k_pool + r * HD) + pc); + kx[s] = __ldg(reinterpret_cast(p.k_pool + r * HD) + kp[s]); else // modes 1 and 3: the K side is INT8 - kx = __ldg(reinterpret_cast(p.k_q + r * HD) + pc); + kx[s] = __ldg(reinterpret_cast(p.k_q + r * HD) + kp[s]); } - *reinterpret_cast(reinterpret_cast(&S.k[c][0]) + pc * 16) = kx; } +#pragma unroll + for (int s = 0; s < KPT; ++s) + *reinterpret_cast(reinterpret_cast(&S.k[kc[s]][0]) + kp[s] * 16) = kx[s]; if constexpr (KV_MODE == 3) { // V: dequantize the row's q4_0 blocks straight into the fp16 V row constexpr int BLKS = HD / QK4_0; constexpr int BYTES = BLKS * (int) sizeof(block_q4_0); for (int i = t; i < CH * BLKS; i += THREADS) { const int c = i / BLKS, b = i % BLKS; - const long long r = S.row[c]; + const long long r = S.row[rbuf][c]; #pragma unroll for (int j = 0; j < QK4_0; ++j) S.v[c][b * QK4_0 + j] = __half(0); if (r >= 0) { @@ -889,22 +903,30 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_v70_kernel(const float* _ } } else { constexpr int VPIECES = HD * (int) sizeof(typename Smem::VElem) / 16; // per V row - for (int i = t; i < CH * VPIECES; i += THREADS) { - const int c = i / VPIECES, pc = i % VPIECES; - const long long r = S.row[c]; - uint4 vx = make_uint4(0, 0, 0, 0); + constexpr int VPT = (CH * VPIECES + THREADS - 1) / THREADS; + static_assert((CH * VPIECES) % THREADS == 0, "the staging pieces divide evenly"); + uint4 vx[VPT]; + int vc[VPT], vp[VPT]; +#pragma unroll + for (int s = 0; s < VPT; ++s) { + const int i = t + s * THREADS; + vc[s] = i / VPIECES; vp[s] = i % VPIECES; + const long long r = S.row[rbuf][vc[s]]; + vx[s] = make_uint4(0, 0, 0, 0); if (r >= 0) { if constexpr (KV_MODE == 1) - vx = __ldg(reinterpret_cast(p.v_q + r * HD) + pc); + vx[s] = __ldg(reinterpret_cast(p.v_q + r * HD) + vp[s]); else - vx = __ldg(reinterpret_cast(p.v_pool + r * HD) + pc); + vx[s] = __ldg(reinterpret_cast(p.v_pool + r * HD) + vp[s]); } - *reinterpret_cast(reinterpret_cast(&S.v[c][0]) + pc * 16) = vx; } +#pragma unroll + for (int s = 0; s < VPT; ++s) + *reinterpret_cast(reinterpret_cast(&S.v[vc[s]][0]) + vp[s] * 16) = vx[s]; } for (int i = t; i < CH * 4; i += THREADS) { const int c = i / 4, g = i % 4; - const long long r = S.row[c]; + const long long r = S.row[rbuf][c]; float a = 0.0f, b = 0.0f; if (r >= 0) { if constexpr (KV_MODE == 1) { @@ -1067,6 +1089,17 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_v70_kernel(const float* _ acc[rb][nt][i] = fmaf(acc[rb][nt][i], a_[(i >> 1) & 1], (tmp[rb][nt][i] + tmpl[rb][nt][i]) * vdown); } } + // the next chunk's pool rows, into the other buffer: the two global lookups per cell hide under p.v + if (c0 + CH < n && t < CH) { + long long r = -1; + const int idx = c0 + CH + t; + if (idx < n) { + const int cell = ids[idx]; + const long long page = (long long) p.page_table[cell / page_size]; + r = (page * n_kv_heads + kvh) * page_size + (cell % page_size); + } + S.row[rbuf ^ 1][t] = r; + } } __syncthreads(); #pragma unroll From d284809fb0ba8906edbeb810d32c3d8e1880cbfd Mon Sep 17 00:00:00 2001 From: ATIVX928 <27274927+ATIVX928@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:43:55 +0000 Subject: [PATCH 04/36] V100: operator fusions for the decode GEMV / MoE paths, bitwise Fusions (all bit-exact vs the pipelines they replace; bench/micro/fusions_parity.cu checks every one bitwise and times the before/after at decode shapes): - gate/up dual GEMV + SwiGLU in ONE kernel (llama.cpp's mul_mat_gated): s_gemv_pair_silu, one read of the activation for both projections and the SwiGLU in the epilogue - the up intermediate never lands in memory. Rows are accumulated by the shared row functions (s_rowdev.cuh) exactly as the standalone kernels accumulate them. shared_expert uses it whenever both projections are S-family (bitwise checked for all three silu kinds). - silu(gate)*up + the intermediate quantizer fused (was 2 kernels): swilu_quantize_q8_0/_scaled/_q8_K, warp-parallel swilu then the verbatim quantizer body. Wired into the S2 expert entry points and shared_expert. - every activation image of x in one pass (was 2-3 kernels): quantize_act_images produces block_q8_0 + block_q8_K + bf16 from one read of x. Wired into gdn_layer, qsa_layer and moe_shared. - multi-weight bf16 GEMV (llama.cpp's mul_mat_multi): bf16_gemv_pair computes two matrices from one read of x; used for ssm_alpha/ssm_beta and for the indexer's q/k projections (q and k now one launch). The call sites are gated on STRATA_EXPERIMENTAL_SM60 (the Pascal/Volta build), so the ready-made engine runs exactly the pipelines it did before; the fused kernels are the same code either way. Measured (V100, CUDA events, n_embd 2560 / FF 640, 200 reps): expert intermediate (swilu+q8_0) 15.7 -> 11.6 us M=1, 18.8 -> 11.4 M=8 activation images (q8_0+q8_K+bf16) 46.2 -> 30.4 us dual GEMV + swilu (gate,up) 30.4 -> 14.8 us bf16 pair (alpha,beta) 24.2 -> 14.4 us M=1, 23.7 -> 14.1 M=8 Parity: fusions_parity 0 failures (bitwise), plus s_gemv/s_gemv_q8k/s2_gemv_q8/ s2_expert_grouped/shared_expert/quantize_act/bf16_gemv/elementwise/mmvq_multi/ iq_multi/native_expert parity suites all pass unchanged. --- CMakeLists.txt | 11 + bench/micro/fusions_parity.cu | 424 ++++++++++++++++++++ include/strata/kernels/bf16_gemv.hpp | 8 + include/strata/kernels/quantize_act.hpp | 32 ++ include/strata/kernels/quantize_act_dev.cuh | 113 ++++++ include/strata/kernels/s_gemv.hpp | 17 + include/strata/kernels/s_rowdev.cuh | 176 ++++++++ include/strata/kernels/swiglu.cuh | 42 ++ src/core/layer.cpp | 66 ++- src/kernels/cuda/bf16_gemv.cu | 48 +++ src/kernels/cuda/quantize_act.cu | 294 +++++++++----- src/kernels/cuda/s2_expert_grouped.cu | 59 ++- src/kernels/cuda/s_gemv_pair.cu | 136 +++++++ src/kernels/cuda/shared_expert.cu | 82 ++++ 14 files changed, 1388 insertions(+), 120 deletions(-) create mode 100644 bench/micro/fusions_parity.cu create mode 100644 include/strata/kernels/quantize_act_dev.cuh create mode 100644 include/strata/kernels/s_rowdev.cuh create mode 100644 include/strata/kernels/swiglu.cuh create mode 100644 src/kernels/cuda/s_gemv_pair.cu diff --git a/CMakeLists.txt b/CMakeLists.txt index 38c34127..2e74c954 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -347,6 +347,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) # reference is the whole point - a kernel checked against another copy of itself proves nothing. add_library(strata_kernels STATIC src/kernels/cuda/dequant_s2.cu src/kernels/cuda/s2_gemv.cu src/kernels/cuda/s_gemv.cu + src/kernels/cuda/s_gemv_pair.cu src/kernels/cuda/s2_gemv_quads.cu src/kernels/cuda/s2_gemv_fast.cu src/kernels/cuda/router_top10.cu @@ -1013,6 +1014,16 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(bf16_gemv_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME bf16_gemv_parity COMMAND bf16_gemv_parity --selftest) + # the V100 fusion work: every fused kernel against its unfused pipeline, bitwise, and the before/after + # CUDA-event timings at decode shapes (`--bench`). It is a .cu because it carries the unfused reference + # kernels it compares against. + if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA) + add_executable(fusions_parity bench/micro/fusions_parity.cu) + target_include_directories(fusions_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(fusions_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME fusions_parity COMMAND fusions_parity) + endif() + add_executable(s_gemv_q8k_parity src/kernels/s_gemv_q8k_parity.cpp) target_include_directories(s_gemv_q8k_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(s_gemv_q8k_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) diff --git a/bench/micro/fusions_parity.cu b/bench/micro/fusions_parity.cu new file mode 100644 index 00000000..eb400914 --- /dev/null +++ b/bench/micro/fusions_parity.cu @@ -0,0 +1,424 @@ +// src/kernels/fusions_parity.cpp - the V100 fusion work against its own unfused pipeline, BITWISE, plus +// the before/after kernel timings (CUDA events). +// +// build/fusions_parity every bitwise check below; exit 1 on any difference +// build/fusions_parity --bench fused vs unfused kernel times at decode shapes (M=1 and M=8) +// +// WHAT IS CHECKED (synthetic data, GPU, no model): +// 1. `swilu_quantize_q8_0` / `_scaled` against `swiglu` + `quantize_q8_0` / `_scaled` - the S2 expert +// path's intermediate. Products, q8 bytes and the fp32 scales all bitwise. +// 2. `swilu_quantize_q8_0` / `_q8_K` with the LEGACY silu against `shared_expert`'s swiglu kernel + +// `quantize_q8_0` / `quantize_q8_K`. +// 3. `quantize_act_images` against the three standalone quantizers (q8_0 bytes, q8_K bytes, bf16 bits). +// 4. `bf16_gemv_pair` against two `bf16_gemv_split(32)` calls (the warp accumulation it replicates). +#include "strata/kernels/bf16_gemv.hpp" +#include "strata/kernels/bf16_bits.hpp" +#include "strata/kernels/elementwise.hpp" +#include "strata/kernels/f16_bits.hpp" +#include "strata/kernels/quantize_act.hpp" +#include "strata/kernels/s_gemv.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace k = strata::kernels; + +namespace { + +int g_fail = 0; + +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* dalloc(size_t n) { + T* p = nullptr; + ck(cudaMalloc(&p, n * sizeof(T)), "malloc"); + ck(cudaMemset(p, 0, n * sizeof(T)), "memset"); + return p; +} +template void up(T* d, const std::vector& h) { + ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "h2d"); +} +template std::vector down(const T* d, size_t n) { + std::vector h(n); + ck(cudaMemcpy(h.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost), "d2h"); + return h; +} + +void report(const char* name, bool ok) { + std::printf(" %-52s %s\n", name, ok ? "bitwise identical" : "DIFFERS"); + if (!ok) ++g_fail; +} + +// the `gemv` dispatch `shared_expert`'s lambda uses (defined later; declared for `run_bench`) +void gemv_dispatch(const k::SForm& f, const uint8_t* codes, const float* scales, const float* off, + const uint8_t* x80, const uint8_t* x8k, float* y, long long n_in, long long n_out, + void* stream); + +// ---- the unfused SwiGLU references, one thread per element (the shapes the standalone kernels had) ---- +__global__ void swilu_legacy_kernel(const float* g, const float* u, float* out, int n) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + const double x = (double) g[i]; + out[i] = (float) (x / (1.0 + exp(-x))) * u[i]; +} +__global__ void swilu_fast_kernel(const float* g, const float* u, float* out, int n) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + out[i] = (g[i] / (1.0f + __expf(-g[i]))) * u[i]; +} +__global__ void swilu_native_kernel(const float* g, const float* u, float* out, int n) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + out[i] = __fdividef(g[i], 1.0f + __expf(-g[i])) * u[i]; +} + +void fill_pairs(std::vector& g, std::vector& u, unsigned seed) { + std::mt19937 rng(seed); + std::uniform_real_distribution gv(-6.0f, 6.0f), uv(-3.0f, 3.0f); + for (size_t i = 0; i < g.size(); ++i) { g[i] = gv(rng); u[i] = uv(rng); } +} + +void check_swilu_quantize(int kind, bool scaled, const char* name) { + const long long n = 640 * 4; // FF x a few hits, multiple of 256 + std::vector hg(n), hu(n); + fill_pairs(hg, hu, 7u + (unsigned) kind * 13 + (unsigned) scaled); + float *dg = dalloc(n), *du = dalloc(n), *dfused = dalloc(n), *dref = dalloc(n); + up(dg, hg); up(du, hu); + const size_t nb80 = (size_t) (n / 32); + uint8_t* db80 = dalloc(nb80 * 34 + 256); + uint8_t* db80r = dalloc(nb80 * 34 + 256); + float* ds = dalloc(nb80 + 16); + float* dsr = dalloc(nb80 + 16); + + // fused + if (scaled) k::swilu_quantize_q8_0_scaled(dg, du, dfused, n, kind, db80, ds, nullptr); + else k::swilu_quantize_q8_0(dg, du, dfused, n, kind, db80, nullptr); + // unfused: standalone swilu then quantize + const int blocks = (int) ((n + 127) / 128); + if (kind == 0) swilu_legacy_kernel<<>>(dg, du, dref, (int) n); + else swilu_fast_kernel<<>>(dg, du, dref, (int) n); + ck(cudaGetLastError(), "swilu ref"); + if (scaled) k::quantize_q8_0_scaled(dref, db80r, dsr, n, nullptr); + else k::quantize_q8_0(dref, db80r, n, nullptr); + ck(cudaDeviceSynchronize(), "sync"); + + const std::vector p1 = down(dfused, n), p2 = down(dref, n); + const std::vector q1 = down(db80, nb80 * 34), q2 = down(db80r, nb80 * 34); + bool ok = std::memcmp(p1.data(), p2.data(), n * sizeof(float)) == 0 && + std::memcmp(q1.data(), q2.data(), nb80 * 34) == 0; + if (scaled) { + const std::vector s1 = down(ds, nb80), s2 = down(dsr, nb80); + ok = ok && std::memcmp(s1.data(), s2.data(), nb80 * sizeof(float)) == 0; + } + report(name, ok); + cudaFree(dg); cudaFree(du); cudaFree(dfused); cudaFree(dref); cudaFree(db80); cudaFree(db80r); + cudaFree(ds); cudaFree(dsr); +} + +void check_swilu_quantize_q8_K() { + const long long n = 256 * 3; + std::vector hg(n), hu(n); + fill_pairs(hg, hu, 99u); + float *dg = dalloc(n), *du = dalloc(n), *df = dalloc(n), *dr = dalloc(n); + up(dg, hg); up(du, hu); + const size_t nbK = (size_t) (n / 256); + uint8_t* dK = dalloc(nbK * 292 + 256); + uint8_t* dKr = dalloc(nbK * 292 + 256); + k::swilu_quantize_q8_K(dg, du, df, n, 0, dK, nullptr); + const int blocks = (int) ((n + 127) / 128); + swilu_legacy_kernel<<>>(dg, du, dr, (int) n); + k::quantize_q8_K(dr, dKr, n, nullptr); + ck(cudaDeviceSynchronize(), "sync"); + bool ok = down(df, n) == down(dr, n) && down(dK, nbK * 292) == down(dKr, nbK * 292); + report("swilu_quantize_q8_K (legacy silu)", ok); + cudaFree(dg); cudaFree(du); cudaFree(df); cudaFree(dr); cudaFree(dK); cudaFree(dKr); +} + +void check_images() { + const long long n = 2560; + std::vector hx(n); + std::mt19937 rng(4u); + std::uniform_real_distribution d(-4.0f, 4.0f); + for (auto& v : hx) v = d(rng); + float* dx = dalloc(n); + up(dx, hx); + const size_t nb80 = (size_t) (n / 32), nbK = (size_t) (n / 256); + uint8_t* i80 = dalloc(nb80 * 34 + 256); + uint8_t* iK = dalloc(nbK * 292 + 256); + uint16_t* i16 = dalloc(n + 8); + uint8_t* r80 = dalloc(nb80 * 34 + 256); + uint8_t* rK = dalloc(nbK * 292 + 256); + k::quantize_act_images(dx, n, i80, iK, i16, nullptr); + k::quantize_q8_0(dx, r80, n, nullptr); + k::quantize_q8_K(dx, rK, n, nullptr); + ck(cudaDeviceSynchronize(), "sync"); + // the standalone bf16 conversion is `bf16_from_f32` per element (`f32_to_bf16_bulk`) + std::vector hb(n); + for (long long i = 0; i < n; ++i) hb[(size_t) i] = k::bf16_from_f32(hx[(size_t) i]); + const std::vector got16 = down(i16, n); + report("quantize_act_images (q8_0 + q8_K + bf16)", + down(i80, nb80 * 34) == down(r80, nb80 * 34) && down(iK, nbK * 292) == down(rK, nbK * 292) && + std::memcmp(got16.data(), hb.data(), n * sizeof(uint16_t)) == 0); + cudaFree(dx); cudaFree(i80); cudaFree(iK); cudaFree(i16); cudaFree(r80); cudaFree(rK); +} + +void check_pair() { + const long long n_in = 2560, n1 = 48, n2 = 48; // ssm_alpha / ssm_beta shapes + std::vector hx(n_in), hw1(n_in * n1), hw2(n_in * n2); + std::mt19937 rng(11u); + std::uniform_real_distribution d(-2.0f, 2.0f); + auto put = [&](std::vector& v) { + for (auto& t : v) t = k::bf16_from_f32(d(rng)); + }; + put(hx); put(hw1); put(hw2); + uint16_t *dx = dalloc(n_in), *dw1 = dalloc(n_in * n1), *dw2 = dalloc(n_in * n2); + up(dx, hx); up(dw1, hw1); up(dw2, hw2); + float *dy1 = dalloc(n1 + 8), *dy2 = dalloc(n2 + 8), *dr1 = dalloc(n1 + 8), + *dr2 = dalloc(n2 + 8); + k::bf16_gemv_pair(dx, dw1, dy1, n1, dw2, dy2, n2, n_in, nullptr); + k::bf16_gemv_split(dx, dw1, dr1, n_in, n1, 32, nullptr); + k::bf16_gemv_split(dx, dw2, dr2, n_in, n2, 32, nullptr); + ck(cudaDeviceSynchronize(), "sync"); + report("bf16_gemv_pair vs 2x bf16_gemv_split(32)", + down(dy1, n1) == down(dr1, n1) && down(dy2, n2) == down(dr2, n2)); + cudaFree(dx); cudaFree(dw1); cudaFree(dw2); cudaFree(dy1); cudaFree(dy2); cudaFree(dr1); cudaFree(dr2); +} + +// ---- micro bench: fused vs unfused kernel time at decode shapes, CUDA events ------------------------- +// +// The decode geometry is the model's: n_embd 2560, FF 640 for the experts (H/FF from `cpu/expert.hpp`). +// M = 1 is the single-token decode; M = 8 runs the M=8 pair shapes (8 columns of the same weights). + +float timed(cudaStream_t s, const std::function& f, int reps) { + cudaEvent_t a, b; + ck(cudaEventCreate(&a), "ev"); ck(cudaEventCreate(&b), "ev"); + f(); ck(cudaStreamSynchronize(s), "sync"); // warmup + ck(cudaEventRecord(a, s), "rec"); + for (int i = 0; i < reps; ++i) f(); + ck(cudaEventRecord(b, s), "rec"); + ck(cudaEventSynchronize(b), "sync"); + float ms = 0.0f; + ck(cudaEventElapsedTime(&ms, a, b), "elapsed"); + cudaEventDestroy(a); cudaEventDestroy(b); + return ms / reps; +} + +void bench_pair(const char* what, const std::function& before, const std::function& after, + int reps) { + cudaStream_t s = nullptr; + const float t0 = timed(s, before, reps), t1 = timed(s, after, reps); + std::printf(" %-44s unfused %8.1f us fused %8.1f us %+.1f%%\n", what, t0 * 1e3f, t1 * 1e3f, + (t1 / t0 - 1.0f) * 100.0f); +} + +void run_bench() { + std::printf("\nfusions bench: decode shapes (n_embd 2560, FF 640), CUDA events, %s\n", + "stream = default, 200 reps"); + const int reps = 200; + + for (int m : {1, 8}) { + const long long pairs = (long long) 640 * m; // one expert hit's rows x tokens + std::vector hg(pairs), hu(pairs); + fill_pairs(hg, hu, 5u + (unsigned) m); + float *dg = dalloc(pairs), *du = dalloc(pairs), *dout = dalloc(pairs); + up(dg, hg); up(du, hu); + const size_t nb = (size_t) (pairs / 32); + uint8_t* d80 = dalloc(nb * 34 + 256); + float* ds = dalloc(nb + 16); + char label[96]; + std::snprintf(label, sizeof label, "expert intermediate M=%d (swilu + q8_0)", m); + bench_pair(label, + [&] { + const int blocks = (int) ((pairs + 127) / 128); + swilu_fast_kernel<<>>(dg, du, dout, (int) pairs); + k::quantize_q8_0(dout, d80, pairs, nullptr); + }, + [&] { k::swilu_quantize_q8_0(dg, du, dout, pairs, 1, d80, nullptr); }, reps); + cudaFree(dg); cudaFree(du); cudaFree(dout); cudaFree(d80); cudaFree(ds); + } + + { + const long long n = 2560; + std::vector hx(n); + std::mt19937 rng(21u); + std::uniform_real_distribution d(-4.0f, 4.0f); + for (auto& v : hx) v = d(rng); + float* dx = dalloc(n); + up(dx, hx); + const size_t nb80 = (size_t) (n / 32), nbK = (size_t) (n / 256); + uint8_t* o80 = dalloc(nb80 * 34 + 256); + uint8_t* oK = dalloc(nbK * 292 + 256); + uint16_t* o16 = dalloc(n + 8); + bench_pair("layer activation images (q8_0 + q8_K + bf16)", + [&] { + k::quantize_q8_0(dx, o80, n, nullptr); + k::quantize_q8_K(dx, oK, n, nullptr); + k::f32_to_bf16_bulk(dx, o16, n, nullptr); + }, + [&] { k::quantize_act_images(dx, n, o80, oK, o16, nullptr); }, reps); + cudaFree(dx); cudaFree(o80); cudaFree(oK); cudaFree(o16); + } + + { + // (a) gate/up dual GEMV + SwiGLU: one kernel vs gemv(gate) + gemv(up) + swilu, shared-expert shapes + const long long n_in = 2560, n_out = 640; + const long long n_groups = n_in / 64; + std::vector hcg((size_t) n_out * n_in / 2), hcu((size_t) n_out * n_in / 2); + std::vector hsg((size_t) n_out * n_groups), hsu((size_t) n_out * n_groups); + std::vector hog((size_t) n_out * n_groups), hou((size_t) n_out * n_groups); + std::vector hx(n_in); + std::mt19937 rng(55u); + for (auto& v : hcg) v = (uint8_t) rng(); + for (auto& v : hcu) v = (uint8_t) rng(); + std::uniform_real_distribution sc(1e-3f, 3e-2f), xv(-4.0f, 4.0f), ov(-1e-2f, 1e-2f); + for (auto& v : hsg) v = sc(rng); + for (auto& v : hsu) v = sc(rng); + for (auto& v : hog) v = ov(rng); + for (auto& v : hou) v = ov(rng); + for (auto& v : hx) v = xv(rng); + float* dx2 = dalloc(n_in); + up(dx2, hx); + uint8_t* dx80 = dalloc((size_t) (n_in / 32) * 34 + 256); + k::quantize_q8_0(dx2, dx80, n_in, nullptr); + uint8_t *dcg = dalloc(hcg.size()), *dcu = dalloc(hcu.size()); + float *dsg = dalloc(hsg.size()), *dsu = dalloc(hsu.size()); + float *dog = dalloc(hog.size()), *dou = dalloc(hou.size()); + up(dcg, hcg); up(dcu, hcu); up(dsg, hsg); up(dsu, hsu); up(dog, hog); up(dou, hou); + float *d_gate = dalloc(n_out + 8), *d_up = dalloc(n_out + 8), *d_pair = dalloc(n_out + 8); + const k::SForm fg{4, -8, 64, k::Codebook::Affine, true, 0}; + const k::SForm fu{4, -8, 64, k::Codebook::Affine, true, 0}; + bench_pair("dual GEMV + swilu (gate,up) FF=640", + [&] { + gemv_dispatch(fg, dcg, dsg, dog, dx80, nullptr, d_gate, n_in, n_out, nullptr); + gemv_dispatch(fu, dcu, dsu, dou, dx80, nullptr, d_up, n_in, n_out, nullptr); + const int bl = (int) ((n_out + 127) / 128); + swilu_legacy_kernel<<>>(d_gate, d_up, d_pair, (int) n_out); + }, + [&] { + k::s_gemv_pair_silu(dx80, nullptr, fg, dcg, dsg, dog, fu, dcu, dsu, dou, d_pair, + n_in, n_out, 32, 0, nullptr); + }, reps); + cudaFree(dx2); cudaFree(dx80); cudaFree(dcg); cudaFree(dcu); cudaFree(dsg); cudaFree(dsu); + cudaFree(dog); cudaFree(dou); cudaFree(d_gate); cudaFree(d_up); cudaFree(d_pair); + } + + for (int m : {1, 8}) { + const long long n_in = 2560, n1 = 48, n2 = 48; + std::vector hx(n_in), hw1(n_in * n1), hw2(n_in * n2); + std::mt19937 rng(31u + (unsigned) m); + std::uniform_real_distribution d(-2.0f, 2.0f); + auto put = [&](std::vector& v) { for (auto& t : v) t = k::bf16_from_f32(d(rng)); }; + put(hx); put(hw1); put(hw2); + uint16_t *dx = dalloc(n_in), *dw1 = dalloc(n_in * n1), *dw2 = dalloc(n_in * n2); + up(dx, hx); up(dw1, hw1); up(dw2, hw2); + float *dy1 = dalloc(n1 + 8), *dy2 = dalloc(n2 + 8); + char label[96]; + std::snprintf(label, sizeof label, "bf16 pair (alpha,beta) M=%d", m); + bench_pair(label, + [&] { + k::bf16_gemv_split(dx, dw1, dy1, n_in, n1, 32, nullptr); + k::bf16_gemv_split(dx, dw2, dy2, n_in, n2, 32, nullptr); + }, + [&] { k::bf16_gemv_pair(dx, dw1, dy1, n1, dw2, dy2, n2, n_in, nullptr); }, reps); + cudaFree(dx); cudaFree(dw1); cudaFree(dw2); cudaFree(dy1); cudaFree(dy2); + } +} + +// ---- (a) the gate/up dual GEMV + SwiGLU kernel against its unfused pipeline, bitwise ---------------- +// The unfused pipeline is the one `shared_expert` ran: a standalone GEMV per projection (dispatching the +// same way its `gemv` lambda does) then the standalone SwiGLU kernel. Both silu kinds are checked. + +void gemv_dispatch(const k::SForm& f, const uint8_t* codes, const float* scales, const float* off, + const uint8_t* x80, const uint8_t* x8k, float* y, long long n_in, long long n_out, + void* stream) { + if (f.code_bits == 2) { + std::fprintf(stderr, "gemv_dispatch: code_bits 2 goes through s2_gemv_q8 - not exercised here\n"); + std::exit(2); + } + if (f.act_kind == 1) k::s_gemv_q8k_split(x8k, codes, scales, off, y, n_in, n_out, f, stream); + else k::s_gemv_q8_0_split(x80, codes, scales, off, y, n_in, n_out, f, stream); +} + +void check_dual_gemv(int swilu_kind, const char* name) { + const long long n_in = 2560, n_out = 128; + const long long n_groups = n_in / 64; + std::vector hcg((size_t) n_out * n_in / 2), hcu((size_t) n_out * n_in / 2); // S4 codes + std::vector hsg((size_t) n_out * n_groups), hsu((size_t) n_out * n_groups); + std::vector hog((size_t) n_out * n_groups), hou((size_t) n_out * n_groups); + std::vector hx(n_in); + std::mt19937 rng(77u + (unsigned) swilu_kind); + for (auto& v : hcg) v = (uint8_t) rng(); + for (auto& v : hcu) v = (uint8_t) rng(); + std::uniform_real_distribution sc(1e-3f, 3e-2f), xv(-4.0f, 4.0f), ov(-1e-2f, 1e-2f); + for (auto& v : hsg) v = sc(rng); + for (auto& v : hsu) v = sc(rng); + for (auto& v : hog) v = ov(rng); + for (auto& v : hou) v = ov(rng); + for (auto& v : hx) v = xv(rng); + + // Q8_0 activation image of x (both sides use it) + const size_t nb80 = (size_t) (n_in / 32); + std::vector hx80(nb80 * 34 + 256); + uint8_t* dx80 = dalloc(hx80.size()); + float* dx = dalloc(n_in); + up(dx, hx); + k::quantize_q8_0(dx, dx80, n_in, nullptr); + ck(cudaDeviceSynchronize(), "sync"); + + uint8_t *dcg = dalloc(hcg.size()), *dcu = dalloc(hcu.size()); + float *dsg = dalloc(hsg.size()), *dsu = dalloc(hsu.size()); + float *dog = dalloc(hog.size()), *dou = dalloc(hou.size()); + up(dcg, hcg); up(dcu, hcu); up(dsg, hsg); up(dsu, hsu); up(dog, hog); up(dou, hou); + float* d_pair = dalloc(n_out + 8); + float* d_gate = dalloc(n_out + 8), *d_up = dalloc(n_out + 8), *d_ref = dalloc(n_out + 8); + + const k::SForm fg{4, -8, 64, k::Codebook::Affine, true, 0}; + const k::SForm fu{4, -8, 64, k::Codebook::Affine, true, 0}; + const bool ok_launch = k::s_gemv_pair_silu(dx80, nullptr, fg, dcg, dsg, dog, fu, dcu, dsu, dou, + d_pair, n_in, n_out, 32, swilu_kind, nullptr); + // unfused: the same two GEMVs the `gemv` lambda would run, then the standalone swilu + gemv_dispatch(fg, dcg, dsg, dog, dx80, nullptr, d_gate, n_in, n_out, nullptr); + gemv_dispatch(fu, dcu, dsu, dou, dx80, nullptr, d_up, n_in, n_out, nullptr); + const int blocks = (int) ((n_out + 127) / 128); + if (swilu_kind == 0) swilu_legacy_kernel<<>>(d_gate, d_up, d_ref, (int) n_out); + else if (swilu_kind == 1) swilu_fast_kernel<<>>(d_gate, d_up, d_ref, (int) n_out); + else swilu_native_kernel<<>>(d_gate, d_up, d_ref, (int) n_out); + ck(cudaGetLastError(), "swilu ref"); + ck(cudaDeviceSynchronize(), "sync"); + report(name, ok_launch && down(d_pair, n_out) == down(d_ref, n_out)); + + cudaFree(dx80); cudaFree(dx); cudaFree(dcg); cudaFree(dcu); cudaFree(dsg); cudaFree(dsu); + cudaFree(dog); cudaFree(dou); cudaFree(d_pair); cudaFree(d_gate); cudaFree(d_up); cudaFree(d_ref); +} + +} // namespace + +int main(int argc, char** argv) { + bool bench = false; + for (int i = 1; i < argc; ++i) + if (std::string(argv[i]) == "--bench") bench = true; + else { std::fprintf(stderr, "usage: fusions_parity [--bench]\n"); return 2; } + std::printf("fusions_parity: V100 fusions vs their unfused pipelines, bitwise\n"); + check_swilu_quantize(1, false, "swilu_quantize_q8_0 (fast silu, expert path)"); + check_swilu_quantize(1, true, "swilu_quantize_q8_0_scaled (fast silu, expert path)"); + check_swilu_quantize(0, false, "swilu_quantize_q8_0 (legacy silu, shared expert)"); + check_swilu_quantize_q8_K(); + check_images(); + check_pair(); + check_dual_gemv(0, "s_gemv_pair_silu (legacy silu) vs gemv+gemv+swilu"); + check_dual_gemv(1, "s_gemv_pair_silu (fast silu) vs gemv+gemv+swilu"); + check_dual_gemv(2, "s_gemv_pair_silu (native silu) vs gemv+gemv+swilu"); + if (bench) run_bench(); + std::printf(g_fail ? "fusions_parity: %d failures\n" : "fusions_parity: 0 failures\n", g_fail); + return g_fail ? 1 : 0; +} diff --git a/include/strata/kernels/bf16_gemv.hpp b/include/strata/kernels/bf16_gemv.hpp index f040b04c..19c4207f 100644 --- a/include/strata/kernels/bf16_gemv.hpp +++ b/include/strata/kernels/bf16_gemv.hpp @@ -26,6 +26,14 @@ namespace strata::kernels { /// `strata::core::WeightRef::ne0/ne1` already report. void bf16_gemv(const uint16_t* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, void* stream); +/// TWO weight matrices from ONE kernel (llama.cpp's `*_mul_mat_multi` shape): `y1 = w1 @ x`, `y2 = w2 @ x`. +/// One warp computes row o of both matrices with two accumulators over one lane-strided pass, so each output +/// is bitwise what `bf16_gemv` produced for that matrix wherever `bf16_gemv` used its warp kernel +/// (`n_out >= 64`); a matrix below that threshold falls back to the plain call to keep the naive kernel's +/// summation order. `n_out1` or `n_out2` may be 0 for a one-sided call. +void bf16_gemv_pair(const uint16_t* x, const uint16_t* w1, float* y1, int64_t n_out1, const uint16_t* w2, + float* y2, int64_t n_out2, int64_t n_in, void* stream); + /// The row-split variant, for the same reason `s_gemv_split` exists: with one thread per output row the /// parallelism IS the output width, and `ssm_alpha` has 48 of them over 48 SMs. One warp per row, lanes /// striding the reduction axis - which is also what makes the access pattern coalesced in this layout. diff --git a/include/strata/kernels/quantize_act.hpp b/include/strata/kernels/quantize_act.hpp index 49d858b2..28f990c3 100644 --- a/include/strata/kernels/quantize_act.hpp +++ b/include/strata/kernels/quantize_act.hpp @@ -29,6 +29,38 @@ void quantize_q8_0(const float* x, uint8_t* blocks, int64_t n, void* stream); // null. `quantize_q8_0` is unchanged and still matches ggml's bytes, which is what `moe_hit_parity` checks. void quantize_q8_0_scaled(const float* x, uint8_t* blocks, float* scales, int64_t n, void* stream); +// ===================== fused silu(gate) * up + quantize ===================== +// +// One kernel where two ran: the standalone SwiGLU pass wrote the products and the quantizer read them back. +// The products are computed in registers, stored to `gate_out` exactly as the standalone kernels stored them, +// and quantized from those same values - the bytes out are what the two-kernel pipeline produced, with one +// launch and one round trip over the intermediate gone. `gate_out` may alias `gate`. +// +// `swilu_kind` selects the SwiGLU expression this replaces: 0 = the double-precision `ref/moe.py` form +// (`shared_expert`'s legacy kernel), 1 = the S2 expert path's float `__expf` form, 2 = the pinned CUDA +// native form. The expressions live in `strata/kernels/swiglu.cuh`, one copy each. + +// n pairs -> ggml block_q8_0 for the products. +void swilu_quantize_q8_0(const float* gate, const float* up, float* gate_out, int64_t n, int swilu_kind, + uint8_t* blocks, void* stream); + +// The same blocks plus the CPU contract's fp32 scales (`quantize_q8_0_scaled`). +void swilu_quantize_q8_0_scaled(const float* gate, const float* up, float* gate_out, int64_t n, int swilu_kind, + uint8_t* blocks, float* scales, void* stream); + +// The same for the Q8_K contract (n a multiple of 256). +void swilu_quantize_q8_K(const float* gate, const float* up, float* gate_out, int64_t n, int swilu_kind, + uint8_t* blocks, void* stream); + +// ===================== every activation image of x in ONE pass ===================== +// +// The layer start wants 2-3 images of the SAME x (ggml block_q8_0, block_q8_K, bf16) and the engine ran one +// kernel per image - three reads and three launches. This produces whichever images the caller asks for in +// one pass; a null pointer skips that image. The bytes of each image are what its standalone kernel wrote +// (the per-block math is shared with those kernels). n must be a multiple of 256 (the Q8_K block). +void quantize_act_images(const float* x, int64_t n, uint8_t* q8_0_blocks, uint8_t* q8_K_blocks, + uint16_t* bf16, void* stream); + // The inverse, for round-trip checks: each element becomes `q * d16`. void dequant_q8_0(const uint8_t* blocks, float* x, int64_t n, void* stream); diff --git a/include/strata/kernels/quantize_act_dev.cuh b/include/strata/kernels/quantize_act_dev.cuh new file mode 100644 index 00000000..8dc10087 --- /dev/null +++ b/include/strata/kernels/quantize_act_dev.cuh @@ -0,0 +1,113 @@ +// include/strata/kernels/quantize_act_dev.cuh - the per-block activation quantizers, ONE copy each. +// +// The fusion work (V100) folds `silu(gate) * up` and the activation quantizer that follows it into one +// kernel. For that to be bit-exact the fused kernel must quantize EXACTLY what `quantize_act.cu`'s +// kernels quantize - same amax order, same double `rint`, same clamps. A second copy of the math is a +// second thing to drift, so `quantize_act.cu` and the fused kernels both include this file and call the +// same functions. The standalone kernels are thin wrappers around these; there is no other difference. +#pragma once + +#include "strata/kernels/f16_bits.hpp" + +#include + +#include +#include +#include + +namespace strata::kernels { + +constexpr int Q8_0_BLOCK = 32; +constexpr int Q8_0_BLOCK_BYTES = 34; +constexpr int Q8_K_BLOCK = 256; +constexpr int Q8_K_BLOCK_BYTES = 292; + +/// ggml's `nearest_int` (ggml-quants.c L621). The magic constant is 1.5 * 2^23; it is transcribed rather +/// than rewritten as `rintf` because the two differ on exact ties - which is the whole point of it. +__device__ __forceinline__ int nearest_int_dev(float fval) { + const float val = fval + 12582912.0f; + int i; + memcpy(&i, &val, 4); + return (i & 0x007fffff) - 0x00400000; +} + +/// `block_q8_0` for one 32-element block, ggml's bytes: `d32 = amax/127` in fp32, `d` stored fp16, the +/// QUANTIZED INTEGERS divided by `d32` (not by the stored fp16), and `rint` in DOUBLE. See the three +/// subtleties in `quantize_act.cu`'s header comment - every one of them is load-bearing. +__device__ __forceinline__ void quantize_q8_0_block(const float* __restrict__ xb, uint8_t* __restrict__ out) { + float amax = 0.0f; + for (int i = 0; i < Q8_0_BLOCK; ++i) amax = fmaxf(amax, fabsf(xb[i])); + if (amax == 0.0f) { + const uint16_t zb = f16_from_f32(0.0f); + out[0] = (uint8_t) (zb & 0xFF); + out[1] = (uint8_t) (zb >> 8); + for (int i = 0; i < Q8_0_BLOCK; ++i) out[2 + i] = 0; + return; + } + const float d32 = amax / 127.0f; + const uint16_t d16bits = f16_from_f32(d32); + out[0] = (uint8_t) (d16bits & 0xFF); + out[1] = (uint8_t) (d16bits >> 8); + for (int i = 0; i < Q8_0_BLOCK; ++i) { + double q = rint((double) xb[i] / (double) d32); + if (q > 127.0) q = 127.0; + if (q < -128.0) q = -128.0; + out[2 + i] = (uint8_t) (int8_t) q; + } +} + +/// `block_q8_0` bytes PLUS the fp32 scale and the CPU's rounding rule (round half away from zero) - the +/// `quantize_q8_0_scaled_kernel` body, verbatim, so a hit and a CPU miss agree. +__device__ __forceinline__ void quantize_q8_0_scaled_block(const float* __restrict__ xb, + uint8_t* __restrict__ out, float* __restrict__ scale_out) { + float amax = 0.0f; + for (int i = 0; i < Q8_0_BLOCK; ++i) amax = fmaxf(amax, fabsf(xb[i])); + const float s = amax > 0.f ? amax / 127.f : 0.f; + const float inv = s > 0.f ? 1.f / s : 0.f; + *scale_out = s; + const uint16_t d16bits = f16_from_f32(s); + out[0] = (uint8_t) (d16bits & 0xFF); + out[1] = (uint8_t) (d16bits >> 8); + for (int i = 0; i < Q8_0_BLOCK; ++i) { + const float t = xb[i] * inv; + const float r = t + (t >= 0.f ? 0.5f : -0.5f); + int v = (int) r; + v = v < -127 ? -127 : (v > 127 ? 127 : v); + out[2 + i] = (uint8_t) (int8_t) v; + } +} + +/// `block_q8_K` for one 256-element block - the `quantize_q8_K_kernel` body, verbatim (including the +/// zero-block divergence note: bsums are zeroed where ggml leaves them unwritten). +__device__ __forceinline__ void quantize_q8_K_block(const float* __restrict__ xb, uint8_t* __restrict__ out) { + float* d = (float*) out; + int8_t* qs = (int8_t*) (out + 4); + int16_t* bsums = (int16_t*) (out + 4 + Q8_K_BLOCK); + float max = 0.0f, amax = 0.0f; + for (int j = 0; j < Q8_K_BLOCK; ++j) { + const float ax = fabsf(xb[j]); + if (ax > amax) { + amax = ax; + max = xb[j]; + } + } + if (amax == 0.0f) { + *d = 0.0f; + for (int j = 0; j < Q8_K_BLOCK; ++j) qs[j] = 0; + for (int j = 0; j < Q8_K_BLOCK / 16; ++j) bsums[j] = 0; + return; + } + const float iscale = -127.0f / max; + for (int j = 0; j < Q8_K_BLOCK; ++j) { + const int v = nearest_int_dev(__fmul_rn(iscale, xb[j])); + qs[j] = (int8_t) min(127, v); + } + for (int j = 0; j < Q8_K_BLOCK / 16; ++j) { + int sum = 0; + for (int ii = 0; ii < 16; ++ii) sum += qs[j * 16 + ii]; + bsums[j] = (int16_t) sum; + } + *d = 1.0f / iscale; +} + +} // namespace strata::kernels diff --git a/include/strata/kernels/s_gemv.hpp b/include/strata/kernels/s_gemv.hpp index 340df04e..d9e22606 100644 --- a/include/strata/kernels/s_gemv.hpp +++ b/include/strata/kernels/s_gemv.hpp @@ -130,4 +130,21 @@ void s_gemv_q8k_split(const uint8_t* x_q8k, const uint8_t* codes, const float* s void s_gemv_q8_0_split(const uint8_t* x_q8_0, const uint8_t* codes, const float* scales, const float* offset, float* y, int64_t n_in, int64_t n_out, const SForm& form, void* stream); +/// GATE/UP DUAL GEMV + SwiGLU IN ONE KERNEL (llama.cpp's `mul_mat_gated`): `out[o] = silu(gate_row_o) * +/// up_row_o`, one read of the activation for both projections, the `up` intermediate never materialised. +/// +/// Each row is accumulated by the same row function its standalone kernel uses +/// (`strata/kernels/s_rowdev.cuh`) and the SwiGLU is the shared expression (`strata/kernels/swiglu.cuh`), +/// so the output is BITWISE what `gemv(gate)` + `gemv(up)` + the standalone SwiGLU produced - checked by +/// `fusions_parity`. Both forms may be any S-family form (the two sides are dispatched independently; +/// a Q8_0 side and a Q8_K side in one kernel is fine). +/// +/// `swilu_kind`: 0 = the double-precision `ref/moe.py` form, 1 = the float `__expf` form, 2 = the pinned +/// CUDA native form. Returns false when a side's form is outside the warp-per-row kernel's contract +/// (the caller keeps its unfused sequence). +bool s_gemv_pair_silu(const uint8_t* x_q8_0, const uint8_t* x_q8k, const SForm& form_g, const uint8_t* codes_g, + const float* scales_g, const float* off_g, const SForm& form_u, const uint8_t* codes_u, + const float* scales_u, const float* off_u, float* out, int64_t n_in, int64_t n_out, + int threads_per_row, int swilu_kind, void* stream); + } // namespace strata::kernels diff --git a/include/strata/kernels/s_rowdev.cuh b/include/strata/kernels/s_rowdev.cuh new file mode 100644 index 00000000..f4f7810c --- /dev/null +++ b/include/strata/kernels/s_rowdev.cuh @@ -0,0 +1,176 @@ +// include/strata/kernels/s_rowdev.cuh - ONE output row of an S-family GEMV, warp-collective. +// +// The V100 fusion work computes a row of `gate` and a row of `up` inside ONE kernel (llama.cpp's +// `mul_mat_gated` shape: both projections from one read of x, SwiGLU in the epilogue). For the fused and +// unfused pipelines to agree BITWISE each row must be accumulated exactly as the standalone kernel that +// would have produced it - same iteration space, same accumulator layout, same reduction tree, same +// expressions. These functions are those accumulation loops; `s_gemv_pair.cu` calls each one and +// `fusions_parity` checks the pair against the two standalone calls BITWISE, which is what keeps these +// copies honest (the standalone kernels are untouched and remain the reference). +#pragma once + +#include +#include + +#include + +namespace strata::kernels { + +/// ggml's `kvalues_iq4nl`, the table `s_gemv.cu` holds in `__constant__`. +__device__ __forceinline__ float iq4nl_value(int code) { + const signed char tbl[16] = {-127, -104, -83, -65, -49, -35, -22, -10, + 1, 13, 25, 38, 53, 69, 89, 113}; + return (float) tbl[code & 0x0F]; +} + +template +__device__ __forceinline__ float decode_row(int code, int bias, int codebook) { + if (codebook == 1) return iq4nl_value(code); + return (float) (code + bias); +} + +/// the Q8_K activation element at `i` - `s_gemv.cu`'s `q8k_at`, verbatim +__device__ __forceinline__ float q8k_row_at(const uint8_t* __restrict__ x, long long i) { + const uint8_t* blk = x + (i / 256) * 292; + const float d = __ldg((const float*) blk); + const int8_t q = ((const int8_t*) (blk + 4))[i % 256]; + return d * (float) q; +} + +/// the Q8_0 activation element at `i` - `s_gemv.cu`'s `q8_0_at`, verbatim +__device__ __forceinline__ float q8_0_row_at(const uint8_t* __restrict__ x, long long i) { + const uint8_t* blk = x + (i / 32) * 34; + const float d = __half2float(__ushort_as_half(*(const uint16_t*) blk)); + const int8_t q = ((const int8_t*) (blk + 2))[i % 32]; + return d * (float) q; +} + +/// `s_gemv_q8_split_kernel`'s row (`s_gemv.cu`), verbatim: 16 accumulators over `i = lane*16` stepping +/// `32*16`, the `(((acc0+acc1)+(acc2+acc3))+...)` tree, then the `__shfl_down_sync` tree. The reduced +/// value is valid in lane 0. +template +__device__ __forceinline__ float row_s_q8(const uint8_t* __restrict__ x, const uint8_t* __restrict__ codes, + const float* __restrict__ scales, const float* __restrict__ offset, + long long n_in, long long o, int lane, int bias, int codebook, + int group_shift, int has_offset) { + constexpr int PER_BYTE = 8 / CODE_BITS; + const long long n_groups = n_in >> group_shift; + const long long codes_per_row = n_in / PER_BYTE; + const uint8_t* c = codes + o * codes_per_row; + const float* s = scales + o * n_groups; + const float* off = has_offset ? offset + o * n_groups : nullptr; + + float acc0 = 0.0f, acc1 = 0.0f, acc2 = 0.0f, acc3 = 0.0f; + float acc4 = 0.0f, acc5 = 0.0f, acc6 = 0.0f, acc7 = 0.0f; + float acc8 = 0.0f, acc9 = 0.0f, acc10 = 0.0f, acc11 = 0.0f; + float acc12 = 0.0f, acc13 = 0.0f, acc14 = 0.0f, acc15 = 0.0f; + constexpr int QE = 16; + constexpr int QW = 4 * CODE_BITS / 8; + constexpr unsigned MASK = (1u << CODE_BITS) - 1u; + long long i = (long long) lane * QE; + for (; i + QE <= n_in; i += 32 * QE) { + const long long g = i >> group_shift; + const float d = s[g]; + const float b = off ? off[g] : 0.0f; + const uint8_t* cp = c + i / PER_BYTE; + unsigned v, v2, v3, v4; + if (QW == 1) { v = cp[0]; v2 = cp[1]; v3 = cp[2]; v4 = cp[3]; } + else if (QW == 2) { v = *(const uint16_t*) cp; v2 = *(const uint16_t*) (cp + 2); + v3 = *(const uint16_t*) (cp + 4); v4 = *(const uint16_t*) (cp + 6); } + else { v = *(const uint32_t*) cp; v2 = *(const uint32_t*) (cp + 4); + v3 = *(const uint32_t*) (cp + 8); v4 = *(const uint32_t*) (cp + 12); } + const int blk_elems = Q8K ? 256 : 32; + const uint8_t* xb = x + (i / blk_elems) * (Q8K ? 292 : 34); + const int xi = (int) (i % blk_elems); + const float xd = Q8K ? __ldg((const float*) xb) + : __half2float(__ushort_as_half(*(const uint16_t*) xb)); + const int8_t* xq = (const int8_t*) (xb + (Q8K ? 4 : 2)) + xi; + + const float w0 = decode_row((int) (v & MASK), bias, codebook) * d + b; + const float w1 = decode_row((int) ((v >> CODE_BITS) & MASK), bias, codebook) * d + b; + const float w2 = decode_row((int) ((v >> (2 * CODE_BITS)) & MASK), bias, codebook) * d + b; + const float w3 = decode_row((int) ((v >> (3 * CODE_BITS)) & MASK), bias, codebook) * d + b; + const float w4 = decode_row((int) (v2 & MASK), bias, codebook) * d + b; + const float w5 = decode_row((int) ((v2 >> CODE_BITS) & MASK), bias, codebook) * d + b; + const float w6 = decode_row((int) ((v2 >> (2 * CODE_BITS)) & MASK), bias, codebook) * d + b; + const float w7 = decode_row((int) ((v2 >> (3 * CODE_BITS)) & MASK), bias, codebook) * d + b; + acc0 += w0 * (xd * (float) xq[0]); + acc1 += w1 * (xd * (float) xq[1]); + acc2 += w2 * (xd * (float) xq[2]); + acc3 += w3 * (xd * (float) xq[3]); + acc4 += w4 * (xd * (float) xq[4]); + acc5 += w5 * (xd * (float) xq[5]); + acc6 += w6 * (xd * (float) xq[6]); + acc7 += w7 * (xd * (float) xq[7]); + const float w8 = decode_row((int) (v3 & MASK), bias, codebook) * d + b; + const float w9 = decode_row((int) ((v3 >> CODE_BITS) & MASK), bias, codebook) * d + b; + const float w10 = decode_row((int) ((v3 >> (2 * CODE_BITS)) & MASK), bias, codebook) * d + b; + const float w11 = decode_row((int) ((v3 >> (3 * CODE_BITS)) & MASK), bias, codebook) * d + b; + const float w12 = decode_row((int) (v4 & MASK), bias, codebook) * d + b; + const float w13 = decode_row((int) ((v4 >> CODE_BITS) & MASK), bias, codebook) * d + b; + const float w14 = decode_row((int) ((v4 >> (2 * CODE_BITS)) & MASK), bias, codebook) * d + b; + const float w15 = decode_row((int) ((v4 >> (3 * CODE_BITS)) & MASK), bias, codebook) * d + b; + acc8 += w8 * (xd * (float) xq[8]); + acc9 += w9 * (xd * (float) xq[9]); + acc10 += w10 * (xd * (float) xq[10]); + acc11 += w11 * (xd * (float) xq[11]); + acc12 += w12 * (xd * (float) xq[12]); + acc13 += w13 * (xd * (float) xq[13]); + acc14 += w14 * (xd * (float) xq[14]); + acc15 += w15 * (xd * (float) xq[15]); + } + for (; i < n_in; i += 32 * QE) { + for (int k = 0; k < QE && i + k < n_in; ++k) { + const long long e = i + k; + const long long g = e >> group_shift; + const int code = (c[e / PER_BYTE] >> ((int) (e % PER_BYTE) * CODE_BITS)) & MASK; + acc0 += (decode_row(code, bias, codebook) * s[g] + (off ? off[g] : 0.0f)) * + (Q8K ? q8k_row_at(x, e) : q8_0_row_at(x, e)); + } + } + float acc = (((acc0 + acc1) + (acc2 + acc3)) + ((acc4 + acc5) + (acc6 + acc7))) + + (((acc8 + acc9) + (acc10 + acc11)) + ((acc12 + acc13) + (acc14 + acc15))); + for (int step = 16; step > 0; step >>= 1) acc += __shfl_down_sync(0xFFFFFFFFu, acc, step); + return acc; +} + +/// `s2_gemv_q8_kernel`'s row (`s2_gemv_q8.cu`), verbatim: quads of four elements strided over +/// `threads_per_row` threads, four accumulators, then the shared-memory tree +/// `partial[tid] += partial[tid + step]`. `partial` must hold `threads_per_row` floats; the row value +/// lands in `partial[0]`. +__device__ __forceinline__ void row_s2_q8(const uint8_t* __restrict__ act, const uint8_t* __restrict__ codes, + const float* __restrict__ scales, long long n_in, long long o, + int tid, int threads_per_row, float* __restrict__ partial) { + const long long n_quads = n_in / 4; + const uint8_t* c = codes + o * n_quads; + const float* s = scales + o * (n_in / 64); + + float a0 = 0.0f, a1 = 0.0f, a2 = 0.0f, a3 = 0.0f; + for (long long q = tid; q < n_quads; q += threads_per_row) { + const uint8_t byte = c[q]; + const float d = s[q >> 4]; + const long long ablk = (q * 4) / 32; + const uint8_t* blk = act + ablk * 34; + const uint16_t dbits = (uint16_t) (blk[0] | (blk[1] << 8)); + const float dx = __half2float(__ushort_as_half(dbits)); + const int8_t* xq = (const int8_t*) (blk + 2); + const int off = (int) ((q * 4) % 32); + + const float w0 = (float) ((int) (byte & 3) - 1) * d; + const float w1 = (float) ((int) ((byte >> 2) & 3) - 1) * d; + const float w2 = (float) ((int) ((byte >> 4) & 3) - 1) * d; + const float w3 = (float) ((int) ((byte >> 6) & 3) - 1) * d; + a0 += w0 * ((float) xq[off + 0] * dx); + a1 += w1 * ((float) xq[off + 1] * dx); + a2 += w2 * ((float) xq[off + 2] * dx); + a3 += w3 * ((float) xq[off + 3] * dx); + } + partial[tid] = (a0 + a1) + (a2 + a3); + __syncwarp(); + for (int step = threads_per_row / 2; step > 0; step >>= 1) { + if (tid < step) partial[tid] += partial[tid + step]; + __syncwarp(); + } +} + +} // namespace strata::kernels diff --git a/include/strata/kernels/swiglu.cuh b/include/strata/kernels/swiglu.cuh new file mode 100644 index 00000000..1275a9de --- /dev/null +++ b/include/strata/kernels/swiglu.cuh @@ -0,0 +1,42 @@ +// include/strata/kernels/swiglu.cuh - the SwiGLU expressions, ONE copy each. +// +// The fusion work (V100) moves `silu(gate) * up` into the epilogue of the projection that computes `up`. +// For that to be bit-exact the fused epilogue must compute EXACTLY the expression the standalone kernel +// computed - same operations, same precision, same order. A second copy of the expression is a second +// thing to drift, so every caller (the standalone kernels and the fused epilogues) includes this file. +// +// THREE VARIANTS, because the engine really has three: +// +// `swilu_legacy` the `ref/moe.py` transcription: silu in DOUBLE then cast, multiply in float +// (`shared_expert.cu`'s `swiglu_kernel`, and the S2 expert path used to use this shape). +// `swilu_fast` the S2 expert path's float expression with `__expf` +// (`s2_expert_grouped.cu`'s `swiglu_kernel`). +// `swilu_native` the pinned CUDA contract: `__fdividef` and `__expf` +// (`shared_expert.cu`'s `native_swiglu_kernel`). +// +// Bit-exactness across translation units: both call sites compile this with the same CUDA flags (no +// `--use_fast_math` on the files that use the legacy and fast variants), the expressions are straight-line +// IEEE ops around one libdevice call, and the parity tests compare the fused and unfused pipelines bitwise. +#pragma once + +#include + +namespace strata::kernels { + +/// `out = (float)((double)g / (1.0 + exp(-(double)g))) * u` - `shared_expert.cu`'s `swiglu_kernel`. +__device__ __forceinline__ float swilu_legacy(float g, float u) { + const double x = (double) g; + return (float) (x / (1.0 + exp(-x))) * u; +} + +/// `out = (g / (1.0f + __expf(-g))) * u` - `s2_expert_grouped.cu`'s `swiglu_kernel`. +__device__ __forceinline__ float swilu_fast(float g, float u) { + return (g / (1.0f + __expf(-g))) * u; +} + +/// `out = __fdividef(g, 1.0f + __expf(-g)) * u` - `shared_expert.cu`'s `native_swiglu_kernel`. +__device__ __forceinline__ float swilu_native(float g, float u) { + return __fdividef(g, 1.0f + __expf(-g)) * u; +} + +} // namespace strata::kernels diff --git a/src/core/layer.cpp b/src/core/layer.cpp index 1e6b3b93..e2667817 100644 --- a/src/core/layer.cpp +++ b/src/core/layer.cpp @@ -101,6 +101,25 @@ void project_bf16(const float* x, const uint16_t* x_bf16, const uint16_t* weight else if (split) bf16_gemv_split(x_bf16, weights, out, n_in, n_out, TPR, stream); else bf16_gemv(x_bf16, weights, out, n_in, n_out, stream); } +#if defined(STRATA_EXPERIMENTAL_SM60) +// TWO BF16 projections of the SAME x in ONE kernel (`ssm_alpha`/`ssm_beta`, `indexer.q`/`indexer.k`). +// `bf16_gemv_pair` reproduces the warp-per-row accumulation, which is what `bf16_gemv_split` at TPR 32 +// always runs and what plain `bf16_gemv` runs at n_out >= 64 - below that the plain entry uses the naive +// one-thread-per-row sum and the pair would round differently, so those shapes keep two calls. +void project_bf16_pair(const float* x, const uint16_t* x_bf16, const uint16_t* w1, float* o1, int64_t n_out1, + const uint16_t* w2, float* o2, int64_t n_out2, int64_t n_in, bool split, void* stream) { + using namespace strata::kernels; + if (native_bf16_projections) { + bf16_gemv_fp32_mmvf(x, w1, o1, n_in, n_out1, stream); + bf16_gemv_fp32_mmvf(x, w2, o2, n_in, n_out2, stream); + } else if (split || (n_out1 >= 64 && n_out2 >= 64)) { + bf16_gemv_pair(x_bf16, w1, o1, n_out1, w2, o2, n_out2, n_in, stream); + } else { + bf16_gemv(x_bf16, w1, o1, n_in, n_out1, stream); + bf16_gemv(x_bf16, w2, o2, n_in, n_out2, stream); + } +} +#endif ///< threads per row for the row-split GEMVs. /// **MEASURED, NOT ASSUMED, AND 64 IS NOT BETTER.** `dense_pass.exe` drives the same split kernels at /// threads_per_row 64 and reports 248.5 GB/s, so matching it looked like free performance. It is not: @@ -236,8 +255,12 @@ const float* conv_kernel = (const float*) w_conv->data; const float* ssm_norm st_begin(layer, 8, stream); // Plan v0.3 P3: the canonical activation images only when a canonical projection reads them. if (!w_qkv->native_data || !w_gate->native_data) { +#if defined(STRATA_EXPERIMENTAL_SM60) + quantize_act_images(mixed, g.n_embd, b.x_q8_0, b.x_q8k, nullptr, stream); // ONE pass, was two kernels +#else quantize_q8_K(mixed, b.x_q8k, g.n_embd, stream); quantize_q8_0(mixed, b.x_q8_0, g.n_embd, stream); +#endif } st_end(layer, 8, stream); // ---- 2. qkv = wqkv @ x, with the activation THIS layer's `attn_qkv` asks for @@ -291,8 +314,13 @@ st_begin(layer, 12, stream); (int) g.n_embd, (int) g.ssm_v_heads, stream); } else { if (!native_bf16_projections) f32_to_bf16_bulk(mixed, b.x_bf16, g.n_embd, stream); +#if defined(STRATA_EXPERIMENTAL_SM60) + project_bf16_pair(mixed, b.x_bf16, (const uint16_t*) w_alpha->data, b.alpha, g.ssm_v_heads, + (const uint16_t*) w_beta->data, b.beta, g.ssm_v_heads, g.n_embd, true, stream); +#else project_bf16(mixed, b.x_bf16, (const uint16_t*) w_alpha->data, b.alpha, g.n_embd, g.ssm_v_heads, true, stream); project_bf16(mixed, b.x_bf16, (const uint16_t*) w_beta->data, b.beta, g.n_embd, g.ssm_v_heads, true, stream); +#endif } if (!fused_pre) try { if (native_gdn_enabled()) { @@ -331,8 +359,12 @@ st_end(layer, 14, stream); // ---- 8. out = ssm_out @ y, whose activation is whatever THIS layer's `ssm_out` asks for st_begin(layer, 15, stream); if (!w_out->native_data) { +#if defined(STRATA_EXPERIMENTAL_SM60) + quantize_act_images(b.y, g.ssm_value_dim, b.y_q8_0, b.y_q8k, nullptr, stream); // ONE pass, was two +#else quantize_q8_K(b.y, b.y_q8k, g.ssm_value_dim, stream); quantize_q8_0(b.y, b.y_q8_0, g.ssm_value_dim, stream); +#endif } if (!gemv_quantized(*w_out, p_out, f_out, b.y_q8_0, b.y_q8k, out, g.ssm_value_dim, g.n_embd, v.name("ssm_out.weight"), stream, err, b.y)) return false; st_end(layer, 15, stream); return true;} // ================================ the MoE block ================================ uint64_t moe_buffers_bytes(const ModelGeometry& g, int64_t k) { const uint64_t parts[] = { (uint64_t) g.n_embd * 2, @@ -430,10 +462,18 @@ if (w_ginp->kind != WeightKind::Bf16InF32) { err = v.name("ffn_gate_inp_s // the rest, `ffn_up_shexp` Q2_0 on 13, and `ffn_down_shexp` is LEGACY in every layer (IQ4_NL/Q4_0/Q5_0/ // Q8_0/Q2_0, `n_in` 640 so Q8_K is impossible). So BOTH quantized images of the activation are produced // and each projection takes the one its own form asks for. -f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream); +// ONE pass over `x` produces the bf16 image and both quantized images (was three kernels): which quantized +// one is wanted is a property of the TENSOR and the pack mixes them by layer, so both are produced. if (!w_sgate->native_data || !w_sup->native_data) { +#if defined(STRATA_EXPERIMENTAL_SM60) + quantize_act_images(x, g.n_embd, b.x_q8_0, b.x_q8k, b.x_bf16, stream); // ONE pass, was three kernels +#else + f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream); quantize_q8_K(x, b.x_q8k, g.n_embd, stream); quantize_q8_0(x, b.x_q8_0, g.n_embd, stream); +#endif + } else { + f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream); } NativeSharedWeights native; native.gate_type = w_sgate->native_type; native.gate_data = w_sgate->native_data; @@ -1043,10 +1083,16 @@ struct Req { const char* suf; }; const WeightRef* w_idxk = v.get("indexer.k_p if (w_idxk->kind != WeightKind::Bf16InF32 || w_idxq->kind != WeightKind::Bf16InF32) { err = v.name("indexer.*_proj.weight") + " must be engine form 1 (bf16); they are " + std::to_string((int) w_idxk->kind) + " and " + std::to_string((int) w_idxq->kind); return false; } // ---- 1. the three activation formats, once each if (!w_attnk->native_data || !w_attnv->native_data || !w_attnq->native_data) { +#if defined(STRATA_EXPERIMENTAL_SM60) + quantize_act_images(x, g.n_embd, b.x_q8_0, b.x_q8k, + native_bf16_projections ? nullptr : b.x_bf16, stream); // ONE pass, was two or three + } else if (!native_bf16_projections) f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream); +#else quantize_q8_K(x, b.x_q8k, g.n_embd, stream); quantize_q8_0(x, b.x_q8_0, g.n_embd, stream); } if (!native_bf16_projections) f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream); +#endif // ---- 2. the step state: ONE H2D carries every per-token count the kernels need. Nothing below passes a // per-token scalar as an argument, which is what keeps this layer capturable. // @@ -1063,8 +1109,16 @@ if (!w_attnk->native_data || !w_attnv->native_data || !w_attnq->native_data) { strata::kernels::copy_i32_from_mapped(st.pos_dev, m_pos, g.n_head, stream); } else if (cudaMemcpyAsync(st.step, st.host_step, qsa_step_bytes(), cudaMemcpyHostToDevice, (cudaStream_t) stream) != cudaSuccess || cudaMemcpyAsync(st.pos_dev, st.host_pos, (size_t) g.n_head * 4, cudaMemcpyHostToDevice, (cudaStream_t) stream) != cudaSuccess) { err = "qsa_layer: the step-state upload failed"; return false; } } -// ---- 3. the indexer's RAW key: appended before any norm, pooled later once per block +// ---- 3. the indexer's RAW key (and, with the V100 switch, its QUERY in the same kernel; was two launches) +#if defined(STRATA_EXPERIMENTAL_SM60) +// two BF16 projections of the same x in ONE kernel: the query is needed only at step 7 and nothing in between +// touches it, so computing it here changes no order that matters; `idx_raw` is still appended at step 5. +project_bf16_pair(x, b.x_bf16, (const uint16_t*) w_idxk->data, b.idx_raw, g.idx_key_dim, + (const uint16_t*) w_idxq->data, b.q_idx, g.idx_q_heads * g.idx_key_dim, g.n_embd, + false, stream); +#else project_bf16(x, b.x_bf16, (const uint16_t*) w_idxk->data, b.idx_raw, g.n_embd, g.idx_key_dim, false, stream); +#endif // ---- 4. K and V, in Q8_K, then norm and rotate K only SForm f_k, f_v, f_o, f_q; if (!sform_of(*w_attnk, f_k, v.name("attn_k.weight"), err)) return false; if (!sform_of(*w_attnv, f_v, v.name("attn_v.weight"), err)) return false; if (!sform_of(*w_attno, f_o, v.name("attn_output.weight"), err)) return false; if (!sform_of(*w_attnq, f_q, v.name("attn_q.weight"), err)) return false; Planes p_k, p_v, p_o, p_q; if (!plane_ptrs(*w_attnk, v.name("attn_k.weight"), p_k, err)) return false; if (!plane_ptrs(*w_attnv, v.name("attn_v.weight"), p_v, err)) return false; if (!plane_ptrs(*w_attno, v.name("attn_output.weight"), p_o, err)) return false; if (!plane_ptrs(*w_attnq, v.name("attn_q.weight"), p_q, err)) return false; // k and v, with the activation THIS layer's tensors ask for. Both are K-quants in every QSA layer of this @@ -1115,8 +1169,12 @@ if (!gemv_quantized(*w_attnq, p_q, f_q, b.x_q8_0, b.x_q8k, b.q_full, g.n_embd, g // the norm and the rotation see whole rows. A 2-D copy is a memcpy node, which captures (`pinned_capture` // case A) and needs no kernel. if (cudaMemcpy2DAsync(b.qcur, (size_t) g.head_dim * 4, b.q_full, (size_t) g.head_dim * 2 * 4, (size_t) g.head_dim * 4, (size_t) g.n_head, cudaMemcpyDeviceToDevice, (cudaStream_t) stream) != cudaSuccess) { err = "qsa_layer: the q/gate split failed"; return false; } if (!normalize_rotate(b.qcur, w_qn, (int) g.n_head, (int) g.head_dim)) return false; -// ---- 7. the indexer's query: BF16, then norm and rotate -project_bf16(x, b.x_bf16, (const uint16_t*) w_idxq->data, b.q_idx, g.n_embd, g.idx_q_heads * g.idx_key_dim, false, stream); +// ---- 7. the indexer's query: with the V100 switch it was projected at step 3 (paired with the raw key); +// the trunk projects it here. Either way, norm and rotate it now. +#if !defined(STRATA_EXPERIMENTAL_SM60) +project_bf16(x, b.x_bf16, (const uint16_t*) w_idxq->data, b.q_idx, g.n_embd, g.idx_q_heads * g.idx_key_dim, + false, stream); +#endif if (!normalize_rotate(b.q_idx, w_iqn, (int) g.idx_q_heads, (int) g.idx_key_dim)) return false; // ---- 8. score, select, gather, attend. `max_blocks` and `cap` are CAPACITIES from the state, not this // token's counts: a grid or a shared-memory size that follows the sequence length is baked into a captured diff --git a/src/kernels/cuda/bf16_gemv.cu b/src/kernels/cuda/bf16_gemv.cu index 04473ad0..a40f6f87 100644 --- a/src/kernels/cuda/bf16_gemv.cu +++ b/src/kernels/cuda/bf16_gemv.cu @@ -65,6 +65,40 @@ __global__ void bf16_gemv_split_kernel(const uint16_t* __restrict__ x, const uin if (t == 0) y[o] = scratch[0]; } +/// TWO weight matrices from one read of x - llama.cpp's `*_mul_mat_multi` shape. One warp computes row `o` +/// of `w1` and row `o` of `w2` with two independent accumulators over the SAME lane-strided loop, so each +/// accumulator sees the addend sequence its standalone `bf16_gemv_warp_kernel` run gave it: bitwise equal +/// (checked by `bf16_gemv_pair_parity`). Rows past a matrix's `n_out` skip that accumulator only. +__global__ void bf16_gemv_pair_warp_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w1, + float* __restrict__ y1, long long n_out1, + const uint16_t* __restrict__ w2, float* __restrict__ y2, + long long n_out2, long long n_in) { + const int warps_per_block = (int) (blockDim.x >> 5); + const long long o = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5); + const int lane = threadIdx.x & 31; + const long long n_out = n_out1 > n_out2 ? n_out1 : n_out2; + if (o >= n_out) return; + const int run1 = o < n_out1, run2 = o < n_out2; + const uint16_t* r1 = w1 + o * n_in; + const uint16_t* r2 = w2 + o * n_in; + float acc1 = 0.0f, acc2 = 0.0f; + for (long long i = lane; i < n_in; i += 32) { + const float xv = f32_from_bf16(x[i]); + if (run1) acc1 += xv * f32_from_bf16(r1[i]); + if (run2) acc2 += xv * f32_from_bf16(r2[i]); + } + if (run1) { + float a = acc1; + for (int off = 16; off > 0; off >>= 1) a += __shfl_down_sync(0xFFFFFFFFu, a, off); + if (lane == 0) y1[o] = a; + } + if (run2) { + float a = acc2; + for (int off = 16; off > 0; off >>= 1) a += __shfl_down_sync(0xFFFFFFFFu, a, off); + if (lane == 0) y2[o] = a; + } +} + inline void finish(void* stream, const char* what) { const cudaError_t e = cudaGetLastError(); if (e != cudaSuccess) { @@ -114,6 +148,20 @@ void bf16_gemv(const uint16_t* x, const uint16_t* w, float* y, int64_t n_in, int finish(stream, "bf16_gemv"); } +void bf16_gemv_pair(const uint16_t* x, const uint16_t* w1, float* y1, int64_t n_out1, const uint16_t* w2, + float* y2, int64_t n_out2, int64_t n_in, void* stream) { + if (n_in <= 0 || (n_out1 <= 0 && n_out2 <= 0)) return; + // THE PAIR KERNEL IS THE WARP-PER-ROW ACCUMULATION on both sides, so it is bitwise what + // `bf16_gemv` (n_out >= 64) and `bf16_gemv_split` at tpr 32 produced. Callers whose standalone path + // was the NAIVE kernel (a small `n_out` with the plain entry) must not use this. + const int warps = THREADS / 32; + const long long n_out = n_out1 > n_out2 ? n_out1 : n_out2; + const unsigned grid = (unsigned) ((n_out + warps - 1) / warps); + bf16_gemv_pair_warp_kernel<<>>( + x, w1, y1, n_out1, w2, y2, n_out2, n_in); + finish(stream, "bf16_gemv_pair"); +} + void bf16_gemv_split(const uint16_t* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, int threads_per_row, void* stream) { if (n_in <= 0 || n_out <= 0) return; diff --git a/src/kernels/cuda/quantize_act.cu b/src/kernels/cuda/quantize_act.cu index 0e8e03a5..21cfae73 100644 --- a/src/kernels/cuda/quantize_act.cu +++ b/src/kernels/cuda/quantize_act.cu @@ -22,6 +22,9 @@ // 3. The DEQUANTIZED value is `q * d16`, the fp16 scale, not `q * d32`. The block stores fp16 and that is // what a reader multiplies by. #include "strata/kernels/quantize_act.hpp" +#include "strata/kernels/quantize_act_dev.cuh" +#include "strata/kernels/swiglu.cuh" +#include "strata/kernels/bf16_bits.hpp" #include "strata/kernels/f16_bits.hpp" #include @@ -48,32 +51,7 @@ __global__ void quantize_q8_0_kernel(const float* __restrict__ x, uint8_t* __res long long n_blocks) { const long long b = (long long) blockIdx.x * blockDim.x + threadIdx.x; if (b >= n_blocks) return; - const float* xb = x + b * QK8_0; - uint8_t* out = blocks + b * 34; // { fp16 d ; int8 qs[32] } - - float amax = 0.0f; - for (int i = 0; i < QK8_0; ++i) amax = fmaxf(amax, fabsf(xb[i])); - if (amax == 0.0f) { - // ggml leaves the block zeroed: d = 0 and every q = 0. Writing the fp16 zero explicitly rather than - // skipping keeps the block layout deterministic for the byte comparison. - const uint16_t zb = f16_from_f32(0.0f); - out[0] = (uint8_t) (zb & 0xFF); - out[1] = (uint8_t) (zb >> 8); - for (int i = 0; i < QK8_0; ++i) out[2 + i] = 0; - return; - } - const float d32 = amax / 127.0f; - const uint16_t d16bits = f16_from_f32(d32); - out[0] = (uint8_t) (d16bits & 0xFF); - out[1] = (uint8_t) (d16bits >> 8); - - // double division, matching the reference exactly (subtlety 2) - for (int i = 0; i < QK8_0; ++i) { - double q = rint((double) xb[i] / (double) d32); - if (q > 127.0) q = 127.0; - if (q < -128.0) q = -128.0; - out[2 + i] = (uint8_t) (int8_t) q; - } + quantize_q8_0_block(x + b * QK8_0, blocks + b * 34); } /// **THE HIT PATH'S QUANTIZER, AND IT EXISTS TO REPRODUCE `act_quant_q8_1` EXACTLY (R4.2h, round 331).** @@ -102,29 +80,7 @@ __global__ void quantize_q8_0_scaled_kernel(const float* __restrict__ x, uint8_t float* __restrict__ scales, long long n_blocks) { const long long b = (long long) blockIdx.x * blockDim.x + threadIdx.x; if (b >= n_blocks) return; - const float* xb = x + b * QK8_0; - uint8_t* out = blocks + b * 34; - - float amax = 0.0f; - for (int i = 0; i < QK8_0; ++i) amax = fmaxf(amax, fabsf(xb[i])); - // VERBATIM from `cpu/expert.cpp:144-145`, including the `amax > 0` guard, so the fp32 value written here - // is bit-identical to the `s` the CPU path used. - const float s = amax > 0.f ? amax / 127.f : 0.f; - const float inv = s > 0.f ? 1.f / s : 0.f; - scales[b] = s; - - const uint16_t d16bits = f16_from_f32(s); - out[0] = (uint8_t) (d16bits & 0xFF); - out[1] = (uint8_t) (d16bits >> 8); - for (int i = 0; i < QK8_0; ++i) { - // VERBATIM from `cpu/expert.cpp:159-162`: reciprocal multiply, then `t + copysign(0.5, t)` truncated - // toward zero, which is `lround`'s rule - round half away from zero. - const float t = xb[i] * inv; - const float r = t + (t >= 0.f ? 0.5f : -0.5f); - int v = (int) r; - v = v < -127 ? -127 : (v > 127 ? 127 : v); - out[2 + i] = (uint8_t) (int8_t) v; - } + quantize_q8_0_scaled_block(x + b * QK8_0, blocks + b * 34, scales + b); } #else @@ -180,66 +136,14 @@ __global__ void dequant_q8_0_kernel(const uint8_t* __restrict__ blocks, float* _ constexpr int QK_K = 256; constexpr int Q8K_BYTES = 292; -/// ggml's `nearest_int` (ggml-quants.c L621), transcribed rather than replaced. -/// -/// The magic number is 1.5 * 2^23: adding it forces the mantissa's integer part into the low bits, and the -/// mask/subtract recover it. The reason it is transcribed and not written as `rintf` is that the two differ -/// on exact ties - and that is the whole point of the constant, so a "cleaner" rewrite would silently change -/// which way ties go. -__device__ __forceinline__ int nearest_int_dev(float fval) { - const float val = fval + 12582912.0f; - int i; - memcpy(&i, &val, 4); - return (i & 0x007fffff) - 0x00400000; -} +// `nearest_int_dev` and the per-block quantizers live in `quantize_act_dev.cuh` (shared with the fused +// kernels); the comment that used to justify this copy is there. __global__ void quantize_q8_K_kernel(const float* __restrict__ x, uint8_t* __restrict__ blocks, long long n_blocks) { const long long b = (long long) blockIdx.x * blockDim.x + threadIdx.x; if (b >= n_blocks) return; - const float* xb = x + b * QK_K; - uint8_t* out = blocks + b * Q8K_BYTES; - float* d = (float*) out; - int8_t* qs = (int8_t*) (out + 4); - int16_t* bsums = (int16_t*) (out + 4 + QK_K); - - // `max` is the SIGNED value at the largest magnitude position, and the comparison is STRICTLY greater, - // so a tie keeps the FIRST maximum - which is what `np.argmax` does in the reference transcription too. - float max = 0.0f, amax = 0.0f; - for (int j = 0; j < QK_K; ++j) { - const float ax = fabsf(xb[j]); - if (ax > amax) { - amax = ax; - max = xb[j]; - } - } - if (amax == 0.0f) { - // ggml writes d = 0 and zeroes qs, then `continue`s - which LEAVES bsums UNWRITTEN. A zeroed block - // and an untouched one are indistinguishable to the dot product, but not to a byte comparison, so - // this zeroes bsums as well and the parity test's reference does the same. Recorded because it is a - // deliberate divergence from the letter of the source. - *d = 0.0f; - for (int j = 0; j < QK_K; ++j) qs[j] = 0; - for (int j = 0; j < QK_K / 16; ++j) bsums[j] = 0; - return; - } - const float iscale = -127.0f / max; // -127, NOT -128; see the header - for (int j = 0; j < QK_K; ++j) { - // `__fmul_rn`, NOT `iscale * xb[j]`. ggml computes the product, ROUNDS IT TO F32, and then adds - // 12582912.0f inside `nearest_int`. Written as a plain expression, nvcc CONTRACTS the multiply into - // the add as an FMA - which is a more accurate product but not the same one, and it flips the result - // wherever the true product sits just off a .5 boundary. The first version of this kernel differed - // from the reference in 1 element of 524,288 for exactly this reason, and `__fmul_rn` pins the - // rounding step the source actually performs. - const int v = nearest_int_dev(__fmul_rn(iscale, xb[j])); - qs[j] = (int8_t) min(127, v); // MIN only - the source has no lower clamp - } - for (int j = 0; j < QK_K / 16; ++j) { - int sum = 0; - for (int ii = 0; ii < 16; ++ii) sum += qs[j * 16 + ii]; - bsums[j] = (int16_t) sum; - } - *d = 1.0f / iscale; + quantize_q8_K_block(x + b * QK_K, blocks + b * Q8K_BYTES); } __global__ void dequant_q8_K_kernel(const uint8_t* __restrict__ blocks, float* __restrict__ x, @@ -254,8 +158,169 @@ __global__ void dequant_q8_K_kernel(const uint8_t* __restrict__ blocks, float* _ for (int i = 0; i < QK_K; ++i) out[i] = (float) qs[i] * d; } +// ===================== fused silu(gate) * up + quantize ===================== +// +// ONE kernel where two ran: `swiglu_kernel` wrote the products and the quantizer read them back. The +// products land in `gate_out` exactly as the standalone kernels stored them and the blocks are the same +// bytes the standalone quantizers produced - the quantizer bodies (`quantize_act_dev.cuh`) run verbatim over +// the shared products. The swilu is PARALLEL (one lane per element): the first version ran 32 exp calls +// serially per thread and measured SLOWER than the two kernels it replaced (M=8: +22.9%). +// +// `SwiluKind` selects the expression because the engine really has three (see `swiglu.cuh`); each is the +// verbatim expression of the standalone kernel that this replaces. + +template +__device__ __forceinline__ float swilu_apply(float g, float u) { + if constexpr (KIND == 0) return swilu_legacy(g, u); + else if constexpr (KIND == 1) return swilu_fast(g, u); + else return swilu_native(g, u); +} + +// One WARP per 32-element block of pairs: lane j computes pair j (parallel exp), the products stage through +// shared memory, then the quantizer body runs on them exactly as `quantize_q8_0_kernel` did. +template +__global__ void swilu_quantize_q8_0_kernel(const float* __restrict__ gate, const float* __restrict__ up, + float* __restrict__ gate_out, uint8_t* __restrict__ blocks, + float* __restrict__ scales, long long n_blocks) { + __shared__ float p[4][Q8_0_BLOCK]; // one row per warp (4 warps per block) + const int warps_per_block = (int) (blockDim.x >> 5); + const long long b = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5); + const int lane = threadIdx.x & 31; + const int warp = threadIdx.x >> 5; + if (b >= n_blocks) return; + const long long i0 = b * Q8_0_BLOCK; + const float v = swilu_apply(gate[i0 + lane], up[i0 + lane]); + gate_out[i0 + lane] = v; + p[warp][lane] = v; + __syncwarp(); + if (lane == 0) { + if constexpr (SCALED) quantize_q8_0_scaled_block(p[warp], blocks + b * 34, scales + b); + else quantize_q8_0_block(p[warp], blocks + b * 34); + } +} + +// The same for the Q8_K contract (the shared expert's down projection): one warp per 256-element block, +// lane j taking pairs j, j+32, ... so the 256 exp calls spread over the warp. +template +__global__ void swilu_quantize_q8_K_kernel(const float* __restrict__ gate, const float* __restrict__ up, + float* __restrict__ gate_out, uint8_t* __restrict__ blocks, + long long n_blocks) { + __shared__ float p[2][QK_K]; // one row per warp (2 warps per block) + const int warps_per_block = (int) (blockDim.x >> 5); + const long long b = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5); + const int lane = threadIdx.x & 31; + const int warp = threadIdx.x >> 5; + if (b >= n_blocks) return; + const long long i0 = b * QK_K; + for (int j = lane; j < QK_K; j += 32) { + const float v = swilu_apply(gate[i0 + j], up[i0 + j]); + gate_out[i0 + j] = v; + p[warp][j] = v; + } + __syncwarp(); + if (lane == 0) quantize_q8_K_block(p[warp], blocks + b * Q8K_BYTES); +} + +template +void swilu_quantize_q8_0_launch(const float* gate, const float* up, float* gate_out, int64_t n, uint8_t* blocks, + float* scales, void* stream) { + const long long nb = n / QK8_0; + const int threads = 128; // 4 warps = 4 blocks of 32 pairs + const unsigned grid = (unsigned) ((nb + 3) / 4); + if (scales != nullptr) + swilu_quantize_q8_0_kernel<<>>( + gate, up, gate_out, blocks, scales, nb); + else + swilu_quantize_q8_0_kernel<<>>( + gate, up, gate_out, blocks, nullptr, nb); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "swilu_quantize_q8_0 launch: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + if (stream == nullptr) cudaDeviceSynchronize(); +} + +// ===================== every activation image of x in ONE pass ===================== +// +// The layer start quantized `x` with two or three kernels (Q8_0, Q8_K, bf16) - three reads of the same +// buffer and three launches, per layer. One kernel here produces whichever images the caller asks for; +// every image's bytes are what its standalone kernel produced (the per-block math is shared, and each block +// reads the same `x` values). Null pointers skip that image. +__global__ void quantize_images_kernel(const float* __restrict__ x, uint8_t* __restrict__ b80, + uint8_t* __restrict__ bK, uint16_t* __restrict__ b16, long long n) { + const long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; + const long long nb80 = n / Q8_0_BLOCK; // 32-element blocks + if (i < nb80) { + if (b80 != nullptr) quantize_q8_0_block(x + i * Q8_0_BLOCK, b80 + i * Q8_0_BLOCK_BYTES); + if (b16 != nullptr) + for (int j = 0; j < Q8_0_BLOCK; ++j) b16[i * Q8_0_BLOCK + j] = bf16_from_f32(x[i * Q8_0_BLOCK + j]); + } + // q8_K blocks are 256 wide: the thread whose 32-block starts a super-block computes it (256 values in + // one thread, exactly as `quantize_q8_K_kernel` did). + if (bK != nullptr && (i % (Q8_K_BLOCK / Q8_0_BLOCK)) == 0) { + const long long k = i / (Q8_K_BLOCK / Q8_0_BLOCK); + if (i < nb80 && k < n / Q8_K_BLOCK) quantize_q8_K_block(x + k * Q8_K_BLOCK, bK + k * Q8_K_BLOCK_BYTES); + } +} + } // namespace +void swilu_quantize_q8_0(const float* gate, const float* up, float* gate_out, int64_t n, int swilu_kind, + uint8_t* blocks, void* stream) { + if (n <= 0) return; + if (n % QK8_0 != 0) { + std::fprintf(stderr, "swilu_quantize_q8_0: n %lld is not a multiple of %d\n", (long long) n, QK8_0); + std::exit(1); + } + switch (swilu_kind) { + case 0: swilu_quantize_q8_0_launch<0>(gate, up, gate_out, n, blocks, nullptr, stream); break; + case 1: swilu_quantize_q8_0_launch<1>(gate, up, gate_out, n, blocks, nullptr, stream); break; + default: swilu_quantize_q8_0_launch<2>(gate, up, gate_out, n, blocks, nullptr, stream); break; + } +} + +void swilu_quantize_q8_0_scaled(const float* gate, const float* up, float* gate_out, int64_t n, int swilu_kind, + uint8_t* blocks, float* scales, void* stream) { + if (n <= 0) return; + if (n % QK8_0 != 0) { + std::fprintf(stderr, "swilu_quantize_q8_0_scaled: n %lld is not a multiple of %d\n", (long long) n, QK8_0); + std::exit(1); + } + if (scales == nullptr) { + std::fprintf(stderr, "swilu_quantize_q8_0_scaled: scales is null\n"); + std::exit(1); + } + switch (swilu_kind) { + case 0: swilu_quantize_q8_0_launch<0>(gate, up, gate_out, n, blocks, scales, stream); break; + case 1: swilu_quantize_q8_0_launch<1>(gate, up, gate_out, n, blocks, scales, stream); break; + default: swilu_quantize_q8_0_launch<2>(gate, up, gate_out, n, blocks, scales, stream); break; + } +} + +void swilu_quantize_q8_K(const float* gate, const float* up, float* gate_out, int64_t n, int swilu_kind, + uint8_t* blocks, void* stream) { + if (n <= 0) return; + if (n % QK_K != 0) { + std::fprintf(stderr, "swilu_quantize_q8_K: n %lld is not a multiple of %d\n", (long long) n, QK_K); + std::exit(1); + } + const long long nb = n / QK_K; + const int threads = 64; // 2 warps = 2 blocks of 256 pairs + const unsigned grid = (unsigned) ((nb + 1) / 2); + switch (swilu_kind) { + case 0: swilu_quantize_q8_K_kernel<0><<>>(gate, up, gate_out, blocks, nb); break; + case 1: swilu_quantize_q8_K_kernel<1><<>>(gate, up, gate_out, blocks, nb); break; + default: swilu_quantize_q8_K_kernel<2><<>>(gate, up, gate_out, blocks, nb); break; + } + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "swilu_quantize_q8_K launch: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + if (stream == nullptr) cudaDeviceSynchronize(); +} + void quantize_q8_0(const float* x, uint8_t* blocks, int64_t n, void* stream) { if (n <= 0) return; if (n % QK8_0 != 0) { @@ -349,4 +414,25 @@ void dequant_q8_K(const uint8_t* blocks, float* x, int64_t n, void* stream) { if (stream == nullptr) cudaDeviceSynchronize(); } +void quantize_act_images(const float* x, int64_t n, uint8_t* q8_0_blocks, uint8_t* q8_K_blocks, + uint16_t* bf16, void* stream) { + if (n <= 0) return; + if (q8_0_blocks == nullptr && q8_K_blocks == nullptr && bf16 == nullptr) return; + if (n % Q8_0_BLOCK != 0 || (q8_K_blocks != nullptr && n % QK_K != 0)) { + std::fprintf(stderr, "quantize_act_images: n %lld must be a multiple of %d (and %d for Q8_K)\n", + (long long) n, Q8_0_BLOCK, QK_K); + std::exit(1); + } + const long long nb = n / Q8_0_BLOCK; + const int threads = 128; + const unsigned grid = (unsigned) ((nb + threads - 1) / threads); + quantize_images_kernel<<>>(x, q8_0_blocks, q8_K_blocks, bf16, n); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "quantize_act_images launch: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + if (stream == nullptr) cudaDeviceSynchronize(); +} + } // namespace strata::kernels diff --git a/src/kernels/cuda/s2_expert_grouped.cu b/src/kernels/cuda/s2_expert_grouped.cu index 77bd5d27..9d5bc1e5 100644 --- a/src/kernels/cuda/s2_expert_grouped.cu +++ b/src/kernels/cuda/s2_expert_grouped.cu @@ -161,6 +161,10 @@ __global__ void gu_kernel(const uint8_t* __restrict__ blob_base, const int32_t* gate_up[base + (size_t) r] = s; } +// `silu(gate) * up` lives in `strata/kernels/swiglu.cuh` (the fused kernels call it in their epilogues); +// the standalone pass it replaced is gone. The scratch layout is unchanged: `[0, n_pairs)` ends up holding +// the products, `[n_pairs, 2*n_pairs)` the raw up rows. +#if !defined(STRATA_EXPERIMENTAL_SM60) /// `silu(gate) * up`, in place, over a GATE-MAJOR buffer: `[0, n_pairs)` is every hit's gate and /// `[n_pairs, 2*n_pairs)` is every hit's up, so hit `h`'s row `r` meets itself at `h*FF + r`. /// @@ -173,6 +177,7 @@ __global__ void swiglu_kernel(float* __restrict__ gate_up, long long n_pairs) { const float u = gate_up[n_pairs + i]; gate_up[i] = (g / (1.0f + __expf(-g))) * u; } +#endif __global__ void swiglu_quantize_q8_0_scaled_kernel(float* __restrict__ gate_up, long long n_pairs, uint8_t* __restrict__ blocks, float* __restrict__ scales) { @@ -629,20 +634,27 @@ void moe_hit_grouped_s2(const uint8_t* blob_base, const int32_t* slot_index, con 0, cs); check("moe_hit_grouped_s2/gu", stream); } - // 2. silu(gate) * up. + // 2+3. silu(gate) * up, then the intermediate's own contract - ONE kernel where two ran. The products + // land in the gate half exactly as `swiglu_kernel` left them (the parity test compares that scratch), + // and the q8_0 blocks are the same bytes `quantize_q8_0` produced. `swilu_kind` 1 is this file's + // `swiglu_kernel` expression (see `strata/kernels/swiglu.cuh`). + // The down weight is Q2_0, whose `vec_dot_type` is Q8_0 - `ggml_mul_mat`'s rule, not a choice. With + // `x_scales` the intermediate takes the CPU's contract (`quantize_q8_0_scaled`), R4.2h. { const long long pairs = n_hits * (long long) FF; +#if defined(STRATA_EXPERIMENTAL_SM60) + if (x_scales != nullptr) + swilu_quantize_q8_0_scaled(gate_up, gate_up + pairs, gate_up, pairs, 1, h_q8_0, h_scales, stream); + else + swilu_quantize_q8_0(gate_up, gate_up + pairs, gate_up, pairs, 1, h_q8_0, stream); +#else const unsigned blocks = (unsigned) ((pairs + THREADS - 1) / THREADS); swiglu_kernel<<>>(gate_up, pairs); check("moe_hit_grouped_s2/swiglu", stream); + if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, n_hits * (int64_t) FF, stream); + else quantize_q8_0(gate_up, h_q8_0, n_hits * (int64_t) FF, stream); +#endif } - // 3. the intermediate's own contract, which is `ggml_mul_mat`'s rule and NOT a choice: the down weight is - // Q2_0, whose `vec_dot_type` is Q8_0. `gate_up` holds the pairs; the product went into the first half. - // **R4.2h: the CPU quantizes this intermediate into `a2` with fp32 scales too** (`expert.cpp:232`), so - // when the caller supplies `x_scales` the intermediate gets the CPU's contract as well - otherwise the - // down projection would keep the very disagreement the gate/up projection just had removed. - if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, n_hits * (int64_t) FF, stream); - else quantize_q8_0(gate_up, h_q8_0, n_hits * (int64_t) FF, stream); // 4. down. { launch_hit_down(fast, blob_base, slot_index, dst_index, blob_bytes, h_q8_0, @@ -730,13 +742,22 @@ void moe_hit_grouped_s2_dev(const uint8_t* blob_base, const int32_t* slot_index, cs); check("moe_hit_grouped_s2_dev/gu", stream); } + // silu + intermediate quantization in one kernel (same full-capacity range as the two kernels it replaces, + // sentinel rows included - the parity test compares that scratch). { const long long pairs = cap * (long long) FF; +#if defined(STRATA_EXPERIMENTAL_SM60) + if (x_scales != nullptr) + swilu_quantize_q8_0_scaled(gate_up, gate_up + pairs, gate_up, pairs, 1, h_q8_0, h_scales, stream); + else + swilu_quantize_q8_0(gate_up, gate_up + pairs, gate_up, pairs, 1, h_q8_0, stream); +#else swiglu_kernel<<<(unsigned) ((pairs + THREADS - 1) / THREADS), THREADS, 0, cs>>>(gate_up, pairs); check("moe_hit_grouped_s2_dev/swiglu", stream); + if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap * (int64_t) FF, stream); + else quantize_q8_0(gate_up, h_q8_0, cap * (int64_t) FF, stream); +#endif } - if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap * (int64_t) FF, stream); - else quantize_q8_0(gate_up, h_q8_0, cap * (int64_t) FF, stream); { launch_hit_down(fast, blob_base, slot_index, dst_index, blob_bytes, h_q8_0, x_scales != nullptr ? h_scales : nullptr, out, cap, d_count, cs); @@ -769,11 +790,18 @@ void moe_hit_grouped_s2_multi(const uint8_t* blob_base, const int32_t* slot_inde } { const long long pairs = cap * (long long) FF; +#if defined(STRATA_EXPERIMENTAL_SM60) + if (x_scales != nullptr) + swilu_quantize_q8_0_scaled(gate_up, gate_up + pairs, gate_up, pairs, 1, h_q8_0, h_scales, stream); + else + swilu_quantize_q8_0(gate_up, gate_up + pairs, gate_up, pairs, 1, h_q8_0, stream); +#else swiglu_kernel<<<(unsigned) ((pairs + THREADS - 1) / THREADS), THREADS, 0, cs>>>(gate_up, pairs); check("moe_hit_grouped_s2_multi/swiglu", stream); + if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap * (int64_t) FF, stream); + else quantize_q8_0(gate_up, h_q8_0, cap * (int64_t) FF, stream); +#endif } - if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap * (int64_t) FF, stream); - else quantize_q8_0(gate_up, h_q8_0, cap * (int64_t) FF, stream); { launch_hit_down(fast, blob_base, slot_index, dst_index, blob_bytes, h_q8_0, x_scales != nullptr ? h_scales : nullptr, out, cap, d_count, cs); @@ -1167,10 +1195,17 @@ void moe_grouped_s2(const unsigned long long* grp_ptr, const int32_t* grp_start, check("moe_grouped_s2/swiglu_q8", stream); } else { const long long pairs = cap_entries * (long long) FF; +#if defined(STRATA_EXPERIMENTAL_SM60) + if (x_scales != nullptr) + swilu_quantize_q8_0_scaled(gate_up, gate_up + pairs, gate_up, pairs, 1, h_q8_0, h_scales, stream); + else + swilu_quantize_q8_0(gate_up, gate_up + pairs, gate_up, pairs, 1, h_q8_0, stream); +#else swiglu_kernel<<<(unsigned) ((pairs + THREADS - 1) / THREADS), THREADS, 0, cs>>>(gate_up, pairs); check("moe_grouped_s2/swiglu", stream); if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap_entries * (int64_t) FF, stream); else quantize_q8_0(gate_up, h_q8_0, cap_entries * (int64_t) FF, stream); +#endif } { const dim3 grid((unsigned) (H / D_ROWS), (unsigned) cap_groups); diff --git a/src/kernels/cuda/s_gemv_pair.cu b/src/kernels/cuda/s_gemv_pair.cu new file mode 100644 index 00000000..7ea8ab93 --- /dev/null +++ b/src/kernels/cuda/s_gemv_pair.cu @@ -0,0 +1,136 @@ +// src/kernels/cuda/s_gemv_pair.cu - gate/up dual GEMV + SwiGLU in ONE kernel (llama.cpp's `mul_mat_gated`). +// +// The shared expert ran THREE launches for its two projections and their SwiGLU: the gate GEMV, the up +// GEMV, then a pass over both halves. This kernel computes `out[o] = silu(gate_row_o) * up_row_o` in one +// launch - one read of the activation for both rows - and never materialises `up`. +// +// BITWISE against the unfused pipeline: each row is accumulated by the SAME row function the standalone +// kernel uses (`strata/kernels/s_rowdev.cuh`, shared with nothing else), and the SwiGLU expression is the +// shared one (`strata/kernels/swiglu.cuh`). A float store/load is lossless, so computing the product from +// the register values is what the two-kernel pipeline computed from memory. `fusions_parity` checks this +// bitwise. +// +// The kernel supports every (gate form, up form) pair the S-family dispatch produces: a side is either the +// S2 row (`s2_gemv_q8`, code_bits 2, Q8_0 activations) or an S4/S8 row (`s_gemv_q8_*_split`, Q8_0 or Q8_K +// activations). The per-side kind is a run-time integer picked ONCE per row, outside the accumulation +// loops. Anything else (a non-32 `tpr`, an unknown width) falls back to the unfused sequence. +#include "strata/kernels/s_gemv.hpp" +#include "strata/kernels/s_rowdev.cuh" +#include "strata/kernels/swiglu.cuh" + +#include + +#include +#include + +namespace strata::kernels { +namespace { + +// side kinds: 0 = S2 row (Q8_0 act), 1 = split, 2 = split; widths 4 and 8 fold into `kind` +// below via the template argument chosen at dispatch. +enum { SideS2 = 0, SideQ8K = 1, SideQ80 = 2 }; + +__device__ __forceinline__ float side_row(int kind, int cb, const uint8_t* x80, const uint8_t* x8k, + const uint8_t* codes, const float* scales, const float* off, + long long n_in, long long o, int lane, int bias, int codebook, + int group_shift, int has_offset, int code_bits, + float* s2partial, int tpr) { + if (kind == SideS2) { + row_s2_q8(x80, codes, scales, n_in, o, lane, tpr, s2partial); + return s2partial[0]; + } + const uint8_t* x = kind == SideQ8K ? x8k : x80; + switch (code_bits) { + case 4: + return kind == SideQ8K ? row_s_q8<4, true>(x, codes, scales, off, n_in, o, lane, bias, codebook, + group_shift, has_offset) + : row_s_q8<4, false>(x, codes, scales, off, n_in, o, lane, bias, codebook, + group_shift, has_offset); + default: + return kind == SideQ8K ? row_s_q8<8, true>(x, codes, scales, off, n_in, o, lane, bias, codebook, + group_shift, has_offset) + : row_s_q8<8, false>(x, codes, scales, off, n_in, o, lane, bias, codebook, + group_shift, has_offset); + } +} + +struct SideArgs { + int kind, code_bits, bias, codebook, group_shift, has_offset; + const uint8_t *codes, *x80, *x8k; + const float* scales; + const float* off; +}; + +// ONE WARP PER OUTPUT PAIR: gate row o and up row o, two accumulations, one SwiGLU store. +__global__ void pair_kernel(SideArgs g, SideArgs u, float* __restrict__ out, long long n_in, long long n_out, + int swilu_kind, int tpr) { + __shared__ float s2p[8][32]; // the S2 tree, per warp (8 warps per block) + const int warp_in_block = threadIdx.x >> 5; + const long long o = (long long) blockIdx.x * (blockDim.x >> 5) + warp_in_block; + if (o >= n_out) return; + const int lane = threadIdx.x & 31; + const float ag = side_row(g.kind, g.code_bits, g.x80, g.x8k, g.codes, g.scales, g.off, n_in, o, lane, + g.bias, g.codebook, g.group_shift, g.has_offset, g.code_bits, + s2p[warp_in_block], tpr); + const float au = side_row(u.kind, u.code_bits, u.x80, u.x8k, u.codes, u.scales, u.off, n_in, o, lane, + u.bias, u.codebook, u.group_shift, u.has_offset, u.code_bits, + s2p[warp_in_block], tpr); + if (lane != 0) return; + float v; + if (swilu_kind == 0) v = swilu_legacy(ag, au); + else if (swilu_kind == 1) v = swilu_fast(ag, au); + else v = swilu_native(ag, au); + out[o] = v; +} + +bool side_of(const SForm& f, int64_t n_in, const uint8_t* x80, const uint8_t* x8k, const uint8_t* codes, + const float* scales, const float* off, SideArgs* out) { + if (f.code_bits == 2) { + out->kind = SideS2; + } else if (f.code_bits == 4 || f.code_bits == 8) { + out->kind = f.act_kind == 1 ? SideQ8K : SideQ80; + } else { + return false; + } + out->code_bits = f.code_bits; + out->bias = f.code_bias; + out->codebook = (int) f.codebook; + out->group_shift = 0; + while ((1 << out->group_shift) < f.group_elems) ++out->group_shift; + if ((1 << out->group_shift) != f.group_elems) return false; + out->has_offset = f.has_offset ? 1 : 0; + out->codes = codes; + out->scales = scales; + out->off = off; + out->x80 = x80; + out->x8k = x8k; + (void) n_in; + return true; +} + +} // namespace + +bool s_gemv_pair_silu(const uint8_t* x_q8_0, const uint8_t* x_q8k, const SForm& form_g, const uint8_t* codes_g, + const float* scales_g, const float* off_g, const SForm& form_u, const uint8_t* codes_u, + const float* scales_u, const float* off_u, float* out, int64_t n_in, int64_t n_out, + int threads_per_row, int swilu_kind, void* stream) { + if (n_in <= 0 || n_out <= 0) return false; + // the S2 row's tree is shaped by `threads_per_row`; the standalone kernel takes any tpr, but this + // warp-per-pair form reproduces it only at 32 (the engine's TPR is 32 everywhere). + if (threads_per_row != 32) return false; + SideArgs g, u; + if (!side_of(form_g, n_in, x_q8_0, x_q8k, codes_g, scales_g, off_g, &g)) return false; + if (!side_of(form_u, n_in, x_q8_0, x_q8k, codes_u, scales_u, off_u, &u)) return false; + + const int threads = 256; // 8 warps = 8 output pairs + const unsigned grid = (unsigned) ((n_out + 7) / 8); + pair_kernel<<>>(g, u, out, n_in, n_out, swilu_kind, threads_per_row); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "s_gemv_pair_silu launch: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + return true; +} + +} // namespace strata::kernels diff --git a/src/kernels/cuda/shared_expert.cu b/src/kernels/cuda/shared_expert.cu index 450fe24a..98b634c4 100644 --- a/src/kernels/cuda/shared_expert.cu +++ b/src/kernels/cuda/shared_expert.cu @@ -330,6 +330,87 @@ void shared_expert(const uint8_t* x_q8_0, const uint8_t* x_q8k, const uint16_t* const unsigned g_ff = (unsigned) ((n_ff + THREADS - 1) / THREADS); const unsigned g_embd = (unsigned) ((n_embd + THREADS - 1) / THREADS); +#if defined(STRATA_EXPERIMENTAL_SM60) + // V100 (experimental sm_70 build): gate and up projections, then silu(gate) * up - ONE kernel when both + // projections are S-family (`s_gemv_pair_silu`: one read of x, SwiGLU in the epilogue, `up` never + // materialised). The pair kernel is bit-exact vs the three-kernel sequence (shared row math, shared + // SwiGLU expression). The ready-made engine's path below is untouched. + bool paired = false; + if (native_gate || native_up) + native_quantize_q8_1(x_f32, native->q8_1, (int) n_embd, 1, stream); + if (!native_gate && !native_up) { + paired = s_gemv_pair_silu(x_q8_0, x_q8k, gate_form, gate_codes, gate_scales, gate_off, + up_form, up_codes, up_scales, up_off, gate, n_embd, n_ff, 32, + native_projection ? 2 : 0, stream); + } + if (paired) { + // `gate` already holds the products + } else { + if (native_gate) + native_mmvq(native->gate_type, native->gate_data, native->q8_1, gate, (int) n_embd, (int) n_ff, 1, stream); + else + gemv(gate_form, gate_codes, gate_scales, gate_off, x_q8_0, x_q8k, gate, n_embd, n_ff); + if (native_up) + native_mmvq(native->up_type, native->up_data, native->q8_1, up, (int) n_embd, (int) n_ff, 1, stream); + else + gemv(up_form, up_codes, up_scales, up_off, x_q8_0, x_q8k, up, n_embd, n_ff); + } + + // down: (n_ff) -> (n_embd), and THE INTERMEDIATE IS QUANTIZED TO THE DOWN WEIGHT'S OWN CONTRACT - which is + // what `ggml_mul_mat` does for every matmul in the model. It used to be rounded to fp16 with no + // justification beyond "the kernel takes fp16". + // + // When the pair kernel ran, `gate` already holds the products and only the quantizer is left. Otherwise + // silu(gate) * up AND the quantization are ONE kernel (was: swiglu pass, then quantize); the products + // land in `gate` exactly as `swiglu_kernel` left them and the blocks are the same bytes the standalone + // quantizers produced. The legacy silu is the double-precision `ref/moe.py` form (`swilu_kind` 0). + if (paired) { + if (native_down) { + native_quantize_q8_1(gate, native->q8_1, (int) n_ff, 1, stream); + } else if (down_form.act_kind == 1) { + if (n_ff % 256 != 0) { + std::fprintf(stderr, "shared_expert: the down weight wants Q8_K but n_ff %lld is not a multiple " + "of 256; Q8_K is structurally impossible here\n", (long long) n_ff); + std::exit(1); + } + quantize_q8_K(gate, h_q8k, n_ff, stream); + } else { + quantize_q8_0(gate, h_q8_0, n_ff, stream); + } + } else if (native_projection) { + native_swiglu_kernel<<>>(gate, up, gate, (int) n_ff); + if (native_down) { + native_quantize_q8_1(gate, native->q8_1, (int) n_ff, 1, stream); + } else if (down_form.act_kind == 1) { + if (n_ff % 256 != 0) { + std::fprintf(stderr, "shared_expert: the down weight wants Q8_K but n_ff %lld is not a multiple " + "of 256; Q8_K is structurally impossible here\n", (long long) n_ff); + std::exit(1); + } + quantize_q8_K(gate, h_q8k, n_ff, stream); + } else { + quantize_q8_0(gate, h_q8_0, n_ff, stream); + } + } else if (native_down) { + // no fused entry for the Q8_1 contract; the swilu pass and the q8_1 quantizer stay separate + swiglu_kernel<<>>(gate, up, gate, (int) n_ff); + native_quantize_q8_1(gate, native->q8_1, (int) n_ff, 1, stream); + } else if (down_form.act_kind == 1) { + if (n_ff % 256 != 0) { + std::fprintf(stderr, "shared_expert: the down weight wants Q8_K but n_ff %lld is not a multiple " + "of 256; Q8_K is structurally impossible here\n", (long long) n_ff); + std::exit(1); + } + swilu_quantize_q8_K(gate, up, gate, n_ff, 0, h_q8k, stream); + } else { + swilu_quantize_q8_0(gate, up, gate, n_ff, 0, h_q8_0, stream); + } + if (native_down) { + native_mmvq(native->down_type, native->down_data, native->q8_1, out, (int) n_ff, (int) n_embd, 1, stream); + } else { + gemv(down_form, down_codes, down_scales, down_off, h_q8_0, h_q8k, out, n_ff, n_embd); + } +#else // gate and up projections, then silu(gate) * up in place in `gate` if (native_gate || native_up) native_quantize_q8_1(x_f32, native->q8_1, (int) n_embd, 1, stream); @@ -372,6 +453,7 @@ void shared_expert(const uint8_t* x_q8_0, const uint8_t* x_q8k, const uint16_t* gemv(down_form, down_codes, down_scales, down_off, h_q8_0, h_q8k, out, n_ff, n_embd); } } +#endif // the per-token scalar gate, then the multiply. Note the gate is computed from `x`, the ORIGINAL hidden // state, not from anything the expert produced. The historical branch uses BF16-rounded inputs; the From 7c4ff2de72b96be6646897858f5623c31b41503d Mon Sep 17 00:00:00 2001 From: ATIVX928 <27274927+ATIVX928@users.noreply.github.com> Date: Mon, 5 Oct 2026 17:38:19 +0000 Subject: [PATCH 05/36] prefill (v100): the chunked GDN prompt recurrence (FlashQLA gdn-chunk) + Volta recurrence variants The prompt GDN recurrence is a per-token chain; on a V100 that chain is what the 36 GDN layers cost. This adds the chunked form (cumsum / kkt / fwd over 64-token chunks, chunk-serial scan, the state in registers - the gdn-chunk-sm70 structure of llama.cpp-v100, hand-written CUDA): a chunk is a triangular solve and a batch of matmuls instead of 64 sequential rank-1 steps. Two variants: an FP32-only FMA scan and an m16n16k16 wmma one with the reference's f32->f16 staging. Both are FP32-level, NOT bit-exact (the sums are reordered; the wmma path stages q/k/v and the state through f16) - gdn_chunk_parity bounds them. Also two Volta variants of the recurrence itself: a sync-free warp-shuffle reduction (BIT-EXACT vs gdn_rec_cols_pipe, but measured 2.6x slower - kept as the bitwise control) and a 4-accumulator chain split of the pipelined kernel (FP32-level, measured +6-7% at T=4096/8192, the V100 default now). All of this is compiled only into the STRATA_EXPERIMENTAL_SM60 build and dispatched only at cc==7.0; sm_80 and up keep the trunk's kernel bit-for-bit. The env switches (STRATA_GDN_CHUNK=1/2 chunked, STRATA_GDN_REC_WARP=0/1/2) still override. Measured on the V100 (bench/gdn_chunk_bench, real shapes, one gdn_recurrence call): the chunked path is correct but 4-6x SLOWER than the recurrence as implemented (4-warp CTAs underfeed the tensor cores - see bench/results/2026-10-02-gdn-chunk/RESULTS.md), so it stays opt-in. --- CMakeLists.txt | 5 + include/strata/prefill/gdn_chunk.hpp | 78 ++++ src/prefill/gdn_chunk.cu | 579 +++++++++++++++++++++++++++ src/prefill/kernels.cu | 161 +++++++- 4 files changed, 822 insertions(+), 1 deletion(-) create mode 100644 include/strata/prefill/gdn_chunk.hpp create mode 100644 src/prefill/gdn_chunk.cu diff --git a/CMakeLists.txt b/CMakeLists.txt index 2e74c954..6d729676 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -619,6 +619,11 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) endif() 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_CUDA) + # v100/gdn-chunk: the chunked Volta GDN prompt recurrence. The dispatch (src/prefill/kernels.cu) is + # Volta-only (cc 7.0) and gated on STRATA_EXPERIMENTAL_SM60; the path itself stays opt-in (STRATA_GDN_CHUNK). + target_sources(strata_prefill PRIVATE src/prefill/gdn_chunk.cu) + endif() if(STRATA_ENABLE_HIP AND STRATA_HIPBLASLT_AVAILABLE) target_compile_definitions(strata_prefill PRIVATE STRATA_HIPBLASLT_AVAILABLE=1) target_link_libraries(strata_prefill PRIVATE roc::hipblaslt) diff --git a/include/strata/prefill/gdn_chunk.hpp b/include/strata/prefill/gdn_chunk.hpp new file mode 100644 index 00000000..66d93376 --- /dev/null +++ b/include/strata/prefill/gdn_chunk.hpp @@ -0,0 +1,78 @@ +// include/strata/prefill/gdn_chunk.hpp - the chunked GDN prompt recurrence for Volta (sm_70), v100/gdn-chunk. +// +// The prompt recurrence (`gdn_recurrence`, src/prefill/kernels.cu) walks the chunk's tokens one by one; each +// token depends on the state left by the previous one, so the whole launch is a serial chain of T steps per +// (head, column-block). On a V100 that chain, not the flops, is what the GDN layers cost: the arithmetic is +// O(S^2) per token and S = 128. +// +// The chunked form (the FlashQLA "gdn-chunk" structure of 1Cat-vLLM, as ported for sm_70 in llama.cpp-v100's +// ggml/src/ggml-cuda/gdn-chunk-sm70*: cumsum -> kkt -> fwd, 64-token chunks) trades the token chain for a +// CHUNK chain: inside one 64-token chunk everything runs as dense matmuls and one triangular solve, and only +// the chunks stay in order (each needs the previous chunk's state). Same recurrence, different summation +// order - so FP32-level, NOT bit-exact against `gdn_recurrence` (the precedent: qsa_prompt_attn.hpp). +// +// THE MATH, derived from the recurrence in `strata/kernels/gdn.hpp` (per head; the state columns j are +// independent, so everything below is per column and can be written in matrix form over the i axis): +// +// a_t = exp(gate_t) (decay) +// W_t = a_t W_{t-1} + k_t delta_t^T (state, i x j) +// delta_t = beta_t (v_t - a_t k_t^T W_{t-1}) +// o_t = q_t^T W_t (then * rsqrtf(S) by the caller-side convention) +// +// Unrolled over a chunk (c_t = inclusive cumsum of gate inside the chunk, sigma = c_63, W_in = state at the +// chunk's first token - one step per token, no approximations): +// +// W_t = exp(c_t) W_in + sum_{s<=t} exp(c_t-c_s) k_s delta_s^T +// x_t := a_t k_t^T W_{t-1} +// = exp(c_t) k_t^T W_in + sum_{s + +namespace strata::prefill { + +/// Is the chunked recurrence worth dispatching to on this device? Volta (cc 7.0) only - that is where the +/// token chain hurts and where this was measured; every other architecture keeps the existing recurrence. +bool gdn_chunk_available(); + +/// The chunked recurrence over `T` tokens (T a multiple of 64 - the caller keeps `T % 64` for the recurrent +/// kernel; `gdn_recurrence` does this itself). Same buffers and conventions as `gdn_recurrence`, minus the +/// output norm, which the caller runs over the whole chunk as before: +/// +/// state (S, h_v, S) f32, j fastest, updated in place +/// h [T, C] post-conv, q/k L2-normalised rows (q NOT scaled by 1/sqrt(S); this writes o/sqrt(S)) +/// gate [T, h_v] the PRE-exp gate; beta [T, h_v] already sigmoided +/// oc [T, h_v, S] the un-normed o * rsqrtf(S) - what `gdn_rec_cols_*` writes as `y` before the norm +/// +/// FP32-level, not bit-exact against the recurrence: the same recurrence in a different summation order. +/// Scratch (A, P and the cumsum) is a grow-only static workspace, segmented so a 32k prompt does not size it. +void gdn_chunk_recurrence(float* state, const float* h, const float* gate, const float* beta, float* oc, + int64_t T, void* stream); + +} // namespace strata::prefill diff --git a/src/prefill/gdn_chunk.cu b/src/prefill/gdn_chunk.cu new file mode 100644 index 00000000..90c8ddae --- /dev/null +++ b/src/prefill/gdn_chunk.cu @@ -0,0 +1,579 @@ +// src/prefill/gdn_chunk.cu - see include/strata/prefill/gdn_chunk.hpp for the math and the contract. +// +// Three kernels, the same three stages as llama.cpp-v100's gdn-chunk-sm70 (cumsum / kkt / fwd), hand-written +// plain CUDA - FP32 throughout, no FP16 staging and no tensor cores yet (the TileLang m8n8k4 output of the +// reference is a later, speed-only step). What the chunking buys is the shape of the serial chain: T tokens +// become T/64 chunk steps, each step a batch of dense matmuls over 64 tokens instead of one token's rank-1 +// update behind two __syncthreads. +// +// Per CTA: one (v head, 32-column slice) of the state, all chunks in order (the state slice lives in +// registers - the chunk-serial scan of the reference's fwd kernel). The per-chunk 64x64 matrices A and P are +// computed once per (chunk, head) by the kkt kernel and read by the four column slices. +#include "strata/prefill/gdn_chunk.hpp" + +#include +#if !defined(__HIPCC__) +#include +#include +#endif + +#include +#include +#include +#include + +namespace strata::prefill { +namespace { + +constexpr int S = 128, HK = 16, HV = 48, C = 10240; // the geometry of src/prefill/kernels.cu +constexpr int CH = 64; // tokens per chunk (the reference's chunk) +constexpr int NS = 32; // value columns per fwd CTA +constexpr int NSE = S / NS; // 4 slices per head +constexpr int SEG = 32; // chunks per pipeline segment (sizes the workspace) +// the wmma kernel's dynamic shared memory: Ks/Qs f16, W16 f16, Ug f32 (Gram scratch / U out), As/Ps f16, +// dlt f32 and its f16 image - 84 KB, past the 48 KB default (opt-in), under the 96 KB Volta ceiling +constexpr int WMMA_SMEM = (2 * CH * S + S * NS) * (int) sizeof(__half) + S * NS * (int) sizeof(float) + + 2 * CH * CH * (int) sizeof(__half) + CH * NS * (int) sizeof(float) + + CH * NS * (int) sizeof(__half); + +void check(const char* what) { + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "gdn_chunk %s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +// g_cumsum[lt * HV + h] = inclusive cumsum of gate over the segment's tokens (lt = segment-local token). +// One block of 64 per (chunk, head): a Kogge-Stone scan of 64 values, two tokens' worth of nothing. +__global__ void __launch_bounds__(CH) gdn_chunk_cumsum_kernel(float* __restrict__ gcum, + const float* __restrict__ gate, int ntok) { + const int h = blockIdx.y; + const int lt = blockIdx.x * CH + threadIdx.x; + __shared__ float sh[CH]; + sh[threadIdx.x] = lt < ntok ? gate[(size_t) lt * HV + h] : 0.0f; + __syncthreads(); +#pragma unroll + for (int off = 1; off < CH; off <<= 1) { + const float add = threadIdx.x >= off ? sh[threadIdx.x - off] : 0.0f; + __syncthreads(); + sh[threadIdx.x] += add; + __syncthreads(); + } + if (lt < ntok) gcum[(size_t) lt * HV + h] = sh[threadIdx.x]; +} + +// Per (chunk, head): the decayed Gram matrices the fwd kernel's solve and output sum read, +// A[t][s] = beta_t exp(c_t - c_s) (k_t . k_s) for s < t (the (I + strict_lower) solve matrix) +// P[t][s] = exp(c_t - c_s) (q_t . k_s) for s <= t (the output sum) +// in f32 (CH x CH per chunk-head; the upper triangle of A and P is never written and never read). Every +// decay factor is a decay from a LATER token back to an EARLIER one - <= 1 for a real GDN gate - so nothing +// here can overflow, and delta stays O(beta v) in the fwd solve (gdn_chunk.hpp derives the form). +__global__ void __launch_bounds__(128) gdn_chunk_kkt_kernel(float* __restrict__ A, float* __restrict__ P, + const float* __restrict__ h, + const float* __restrict__ beta, + const float* __restrict__ gcum, int nchunks) { + // 2 * CH * SP f32: the k and q tiles (opt-in, > 48 KB). SP pads the row so the dot loop's row-strided + // reads do not all land in one shared bank (S = 128 floats is a whole number of bank rows). + constexpr int SP = S + 1; + extern __shared__ float sh[]; + float* ks = sh; + float* qs = sh + CH * SP; + const int hh = blockIdx.y, ch = blockIdx.x, qh = hh % HK; + const int64_t base = (size_t) ch * CH; + const float* kh = h + base * C + (size_t) HK * S + (size_t) qh * S; + const float* qh_ = h + base * C + (size_t) qh * S; + for (int i = threadIdx.x; i < CH * S; i += blockDim.x) { + const int t = i / S, j = i % S; + ks[t * SP + j] = kh[(size_t) t * C + j]; + qs[t * SP + j] = qh_[(size_t) t * C + j]; + } + __syncthreads(); + float* Ap = A + ((size_t) ch * HV + hh) * CH * CH; + float* Pp = P + ((size_t) ch * HV + hh) * CH * CH; + for (int p = threadIdx.x; p < CH * CH; p += blockDim.x) { + const int t = p / CH, s = p % CH; + if (s > t) continue; + const float dec = expf(gcum[(base + t) * HV + hh] - gcum[(base + s) * HV + hh]); + float pq = 0.0f, pq1 = 0.0f; +#pragma unroll 4 + for (int i = 0; i < S; i += 2) { + pq = fmaf(qs[t * SP + i], ks[s * SP + i], pq); + pq1 = fmaf(qs[t * SP + i + 1], ks[s * SP + i + 1], pq1); + } + Pp[t * CH + s] = (pq + pq1) * dec; + if (s < t) { + float pk = 0.0f, pk1 = 0.0f; +#pragma unroll 4 + for (int i = 0; i < S; i += 2) { + pk = fmaf(ks[t * SP + i], ks[s * SP + i], pk); + pk1 = fmaf(ks[t * SP + i + 1], ks[s * SP + i + 1], pk1); + } + Ap[t * CH + s] = (pk + pk1) * dec * beta[(base + t) * HV + hh]; + } + } +} + +// The chunk-serial scan: one CTA per (v head, 32-column slice), state in registers, all chunks in order. +// Per token: the two row-block reductions (k_t.W_in, q_t.W_in) give u_t and qW_t; the w==0 lane of each +// column solves its delta and writes o. The A/P tiles are staged to shared memory at the top of each chunk: +// the solve and output sums are serial FMA chains, and a global load inside the chain (L2, ~200 cycles) +// throttles the whole CTA to it. One __syncthreads per token (the shared dlt row plus the partials), one +// after the token loop (the last dlt row before the state update). +__global__ void __launch_bounds__(128) gdn_chunk_fwd_kernel(float* __restrict__ state, float* __restrict__ oc, + const float* __restrict__ h, + const float* __restrict__ beta, + const float* __restrict__ gcum, + const float* __restrict__ A, + const float* __restrict__ P, int nchunks) { + const int hh = blockIdx.y, sl = blockIdx.x, j0 = sl * NS, qh = hh % HK; + const int w = threadIdx.x >> 5, c = threadIdx.x & 31, col = j0 + c; + // red is double-buffered by token parity: the w==0 lane reads token t's partials while the other warps + // may already be staging token t+1's into the other slot (one barrier per token, no reader/writer race) + __shared__ float red[2][2][4][NS], dlt[CH][NS], As[CH][CH], Ps[CH][CH], ex[CH][2]; + float W[NS]; +#pragma unroll + for (int r = 0; r < NS; ++r) + W[r] = state[((size_t) (w * NS + r) * HV + hh) * S + col]; + const float rsqrt_S = rsqrtf((float) S); + for (int ch = 0; ch < nchunks; ++ch) { + const int64_t base = (size_t) ch * CH; + const float sg = gcum[(base + CH - 1) * HV + hh]; // sigma: the chunk's total log-decay + const float* Ap = A + ((size_t) ch * HV + hh) * CH * CH; + const float* Pp = P + ((size_t) ch * HV + hh) * CH * CH; + // stage the two 64x64 tiles and the per-token decay factors (exp(c_t), exp(sigma - c_t)) + for (int i = threadIdx.x; i < CH * CH; i += blockDim.x) { + As[i / CH][i % CH] = Ap[i]; + Ps[i / CH][i % CH] = Pp[i]; + } + if (threadIdx.x < CH) { + const float gc = gcum[(base + threadIdx.x) * HV + hh]; + ex[threadIdx.x][0] = expf(gc); + ex[threadIdx.x][1] = expf(sg - gc); + } + __syncthreads(); + const float sg_exp = ex[CH - 1][0]; // exp(sigma) + for (int t = 0; t < CH; ++t) { + const float* kt = h + (base + t) * C + (size_t) HK * S + (size_t) qh * S + w * NS; + const float* qt = h + (base + t) * C + (size_t) qh * S + w * NS; + float up = 0.0f, up1 = 0.0f, qp = 0.0f, qp1 = 0.0f; +#pragma unroll + for (int r = 0; r < NS; r += 2) { + const float w0 = W[r], w1 = W[r + 1]; + up = fmaf(kt[r], w0, up); + up1 = fmaf(kt[r + 1], w1, up1); + qp = fmaf(qt[r], w0, qp); + qp1 = fmaf(qt[r + 1], w1, qp1); + } + red[t & 1][0][w][c] = up + up1; + red[t & 1][1][w][c] = qp + qp1; + __syncthreads(); + if (w == 0) { + const float u_t = red[t & 1][0][0][c] + red[t & 1][0][1][c] + red[t & 1][0][2][c] + red[t & 1][0][3][c]; + const float qW_t = + red[t & 1][1][0][c] + red[t & 1][1][1][c] + red[t & 1][1][2][c] + red[t & 1][1][3][c]; + const float b = beta[(base + t) * HV + hh]; + const float v_t = h[(base + t) * C + (size_t) 2 * HK * S + (size_t) hh * S + col]; + // delta_t = beta_t (v_t - exp(c_t) u_t) - sum_{s f16; Gram K K^T and Q K^T -> A and P (decay + beta baked); the GEMM +// U = [K; Q] W gives u_t and qW_t for every token at once; the solve and output sums are the FMA scan's; +// W += K^T (delta * decay) on the tensor cores with W itself as the f32 accumulator fragments - the state +// never leaves the registers across chunks. W's f16 image exists only as the U GEMM's operand. +// +// Precision: the FP16 staging is the reference's "f32 -> f16 暂存" (10-bit mantissa on the operands); +// accumulations, the solve and the state are f32. FP32-level, not bit-exact - see gdn_chunk_parity. +#if !defined(__HIPCC__) && (!defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 700) +namespace wmma = ::nvcuda::wmma; + +__global__ void __launch_bounds__(128) gdn_chunk_wmma_kernel(float* __restrict__ state, float* __restrict__ oc, + const float* __restrict__ h, + const float* __restrict__ beta, + const float* __restrict__ gcum, int nchunks) { + // smem (84.5 KB, opt-in): Ks/Qs the chunk's k and q rows f16; W16 the state slice f16 (U's operand); + // Ug[128][32] f32 aliasing the 64x64 Gram scratch and then U = [K;Q] W; As/Ps f16; dlt f32 + f16. + extern __shared__ __align__(1024) unsigned char smem[]; + __half* Ks = (__half*) smem; // [CH][S] + __half* Qs = Ks + CH * S; // [CH][S] + __half* W16 = Qs + CH * S; // [S][NS] + float* Ug = (float*) (W16 + S * NS); // [S][NS] f32 (Gram scratch / U out) + __half* As = (__half*) (Ug + S * NS); // [CH][CH] + __half* Ps = As + CH * CH; // [CH][CH] + float* dlt = (float*) (Ps + CH * CH); // [CH][NS] + __half* dlt16 = (__half*) (dlt + CH * NS); // [CH][NS] + + const int hh = blockIdx.y, sl = blockIdx.x, j0 = sl * NS, qh = hh % HK; + const int w = threadIdx.x >> 5, c = threadIdx.x & 31, col = j0 + c; + // the state slice in through smem (load_matrix_sync of an accumulator tile is a shared-memory op on + // sm_70): Ug first as the f32 staging, then W's f32 image in the fragments and its f16 image in W16 + for (int i = threadIdx.x; i < S * NS; i += blockDim.x) { + const int r = i / NS, j = i % NS; + Ug[i] = state[(size_t) r * HV * S + (size_t) hh * S + j0 + j]; + W16[i] = __float2half_rn(Ug[i]); + } + __syncthreads(); + // W as f32 accumulator fragments: warp w owns rows w*32..w*32+31 of the 128x32 slice, 2x2 tiles + wmma::fragment wF[2][2]; +#pragma unroll + for (int mi = 0; mi < 2; ++mi) +#pragma unroll + for (int nj = 0; nj < 2; ++nj) + wmma::load_matrix_sync(wF[mi][nj], Ug + (size_t) (w * 32 + 16 * mi) * NS + 16 * nj, NS, + wmma::mem_row_major); + const float rsqrt_S = rsqrtf((float) S); + for (int ch = 0; ch < nchunks; ++ch) { + const int64_t base = (size_t) ch * CH; + const float sg = gcum[(base + CH - 1) * HV + hh]; // sigma: the chunk's total log-decay + // stage the chunk's k and q rows through f16 - float4 loads, four in flight per thread: a scalar + // load loop here is a serial global-latency chain per thread (measured: it WAS the kernel's floor) + for (int i4 = threadIdx.x; i4 < CH * S / 4; i4 += blockDim.x) { + const int t = (i4 * 4) / S, j4 = (i4 * 4) % S; + const float4 k4 = *reinterpret_cast(h + (base + t) * C + (size_t) HK * S + (size_t) qh * S + j4); + const float4 q4 = *reinterpret_cast(h + (base + t) * C + (size_t) qh * S + j4); + Ks[t * S + j4 + 0] = __float2half_rn(k4.x); + Ks[t * S + j4 + 1] = __float2half_rn(k4.y); + Ks[t * S + j4 + 2] = __float2half_rn(k4.z); + Ks[t * S + j4 + 3] = __float2half_rn(k4.w); + Qs[t * S + j4 + 0] = __float2half_rn(q4.x); + Qs[t * S + j4 + 1] = __float2half_rn(q4.y); + Qs[t * S + j4 + 2] = __float2half_rn(q4.z); + Qs[t * S + j4 + 3] = __float2half_rn(q4.w); + } + // the state slice as f16: the fragments to Ug, then to W16 +#pragma unroll + for (int mi = 0; mi < 2; ++mi) +#pragma unroll + for (int nj = 0; nj < 2; ++nj) + wmma::store_matrix_sync(Ug + (size_t) (w * 32 + 16 * mi) * NS + 16 * nj, wF[mi][nj], NS, + wmma::mem_row_major); + __syncthreads(); + for (int i = threadIdx.x; i < S * NS; i += blockDim.x) W16[i] = __float2half_rn(Ug[i]); + __syncthreads(); // W16 done before Ug becomes the Gram scratch + // Gram: Ug = K K^T, then As[t][s] = beta_t exp(c_t-c_s) Ug[t][s]; Ug = Q K^T, then Ps (no beta) + { + wmma::fragment aF; + wmma::fragment bF; + wmma::fragment gF[4]; + for (int pass = 0; pass < 2; ++pass) { +#pragma unroll + for (int nj = 0; nj < 4; ++nj) wmma::fill_fragment(gF[nj], 0.0f); + for (int kk = 0; kk < S / 16; ++kk) { + wmma::load_matrix_sync(aF, (pass ? Qs : Ks) + (size_t) (w * 16) * S + kk * 16, S); + for (int nj = 0; nj < 4; ++nj) { + wmma::load_matrix_sync(bF, Ks + kk * 16 + (size_t) (16 * nj) * S, S); + wmma::mma_sync(gF[nj], aF, bF, gF[nj]); + } + } + for (int nj = 0; nj < 4; ++nj) + wmma::store_matrix_sync(Ug + (size_t) (w * 16) * CH + 16 * nj, gF[nj], CH, wmma::mem_row_major); + __syncthreads(); + // fold decay (and beta) into the f16 tiles + for (int p = threadIdx.x; p < CH * CH; p += blockDim.x) { + const int t = p / CH, s = p % CH; + const float dec = expf(gcum[(base + t) * HV + hh] - gcum[(base + s) * HV + hh]); + if (pass) // Ps: s <= t live, the upper triangle zeroed - the o GEMM reads the whole tile + Ps[t * CH + s] = s <= t ? __float2half_rn(Ug[t * CH + s] * dec) : __float2half_rn(0.0f); + else if (s < t) // As: strict lower only, the solve reads exactly that + As[t * CH + s] = __float2half_rn(Ug[t * CH + s] * dec * beta[(base + t) * HV + hh]); + } + __syncthreads(); + } + } + // U = [K; Q] W16 : rows 0..63 are u_t = k_t.W_in, rows 64..127 are qW_t = q_t.W_in. The 128 output + // rows split as 32 per warp: warps 0-1 the K half, warps 2-3 the Q half. + { + wmma::fragment aF; + wmma::fragment bF[2]; + wmma::fragment uF[2][2]; + const __half* src = w < 2 ? Ks : Qs; + const int row0 = (w & 1) * 32; +#pragma unroll + for (int mi = 0; mi < 2; ++mi) +#pragma unroll + for (int nj = 0; nj < 2; ++nj) wmma::fill_fragment(uF[mi][nj], 0.0f); + for (int kk = 0; kk < S / 16; ++kk) { + for (int nj = 0; nj < 2; ++nj) + wmma::load_matrix_sync(bF[nj], W16 + kk * 16 * NS + 16 * nj, NS); +#pragma unroll + for (int mi = 0; mi < 2; ++mi) { + wmma::load_matrix_sync(aF, src + (size_t) (row0 + 16 * mi) * S + kk * 16, S); + for (int nj = 0; nj < 2; ++nj) wmma::mma_sync(uF[mi][nj], aF, bF[nj], uF[mi][nj]); + } + } +#pragma unroll + for (int mi = 0; mi < 2; ++mi) +#pragma unroll + for (int nj = 0; nj < 2; ++nj) + wmma::store_matrix_sync(Ug + (size_t) (w * 32 + 16 * mi) * NS + 16 * nj, uF[mi][nj], NS, + wmma::mem_row_major); + __syncthreads(); + } + // the solve - 8 independent accumulator chains so the smem loads of one group hide behind the FMAs + // of the last (the 2-chain was smem-latency-bound and WAS half the kernel's runtime) + for (int t = 0; t < CH; ++t) { + if (w == 0) { + const float gc = gcum[(base + t) * HV + hh]; + const float ex0 = expf(gc); + const float b = beta[(base + t) * HV + hh]; + const float v_t = h[(base + t) * C + (size_t) 2 * HK * S + (size_t) hh * S + col]; + float d[8]; + d[0] = b * (v_t - ex0 * Ug[t * NS + c]); +#pragma unroll + for (int q = 1; q < 8; ++q) d[q] = 0.0f; + int s0 = 0; +#pragma unroll 1 + for (; s0 + 8 <= t; s0 += 8) { +#pragma unroll + for (int q = 0; q < 8; ++q) + d[q] = fmaf(-__half2float(As[t * CH + s0 + q]), dlt[(s0 + q) * NS + c], d[q]); + } +#pragma unroll 1 + for (; s0 < t; ++s0) d[0] = fmaf(-__half2float(As[t * CH + s0]), dlt[s0 * NS + c], d[0]); + dlt[t * NS + c] = (d[0] + d[1] + d[2] + d[3]) + (d[4] + d[5] + d[6] + d[7]); + } + } + __syncthreads(); // the deltas are complete + for (int i = threadIdx.x; i < CH * NS; i += blockDim.x) dlt16[i] = __float2half_rn(dlt[i]); + __syncthreads(); + // o_intra = Ps delta on the tensor cores (the o FMA sum was the other latency chain), staged into the + // As tile (dead since the solve); 64 output rows split 16 per warp + { + wmma::fragment aF; + wmma::fragment bF[2]; + wmma::fragment oF[2]; + for (int nj = 0; nj < 2; ++nj) wmma::fill_fragment(oF[nj], 0.0f); + for (int kk = 0; kk < CH / 16; ++kk) { + for (int nj = 0; nj < 2; ++nj) + wmma::load_matrix_sync(bF[nj], dlt16 + (size_t) (kk * 16) * NS + 16 * nj, NS); + wmma::load_matrix_sync(aF, Ps + (size_t) (w * 16) * CH + kk * 16, CH); + for (int nj = 0; nj < 2; ++nj) wmma::mma_sync(oF[nj], aF, bF[nj], oF[nj]); + } + for (int nj = 0; nj < 2; ++nj) + wmma::store_matrix_sync(Ug + S * NS + (size_t) (w * 16) * NS + 16 * nj, oF[nj], NS, + wmma::mem_row_major); // (the As tile's byte range) + } + __syncthreads(); + for (int i = threadIdx.x; i < CH * NS; i += blockDim.x) { + const int t = i / NS; + oc[((base + t) * HV + hh) * S + j0 + (i % NS)] = + (Ug[S * NS + i] + expf(gcum[(base + t) * HV + hh]) * Ug[(64 + t) * NS + (i % NS)]) * rsqrt_S; + } + __syncthreads(); + // dlt16 = f16(delta_s * exp(sigma - c_s)) - the decay folded in for the state update + for (int i = threadIdx.x; i < CH * NS; i += blockDim.x) { + const int s = i / NS; + dlt16[i] = __float2half_rn(__half2float(dlt16[i]) * expf(sg - gcum[(base + s) * HV + hh])); + } + const float sg_exp = expf(sg); + __syncthreads(); +#pragma unroll + for (int mi = 0; mi < 2; ++mi) +#pragma unroll + for (int nj = 0; nj < 2; ++nj) +#pragma unroll + for (int q = 0; q < 8; ++q) wF[mi][nj].x[q] *= sg_exp; + { + { + wmma::fragment aF; + wmma::fragment bF[2]; + for (int kk = 0; kk < CH / 16; ++kk) { + for (int nj = 0; nj < 2; ++nj) + wmma::load_matrix_sync(bF[nj], dlt16 + (size_t) (kk * 16) * NS + 16 * nj, NS); +#pragma unroll + for (int mi = 0; mi < 2; ++mi) { + wmma::load_matrix_sync(aF, Ks + (w * 32 + 16 * mi) + (size_t) (kk * 16) * S, S); + for (int nj = 0; nj < 2; ++nj) wmma::mma_sync(wF[mi][nj], aF, bF[nj], wF[mi][nj]); + } + } } + } + } + // the state slice out through smem as well +#pragma unroll + for (int mi = 0; mi < 2; ++mi) +#pragma unroll + for (int nj = 0; nj < 2; ++nj) + wmma::store_matrix_sync(Ug + (size_t) (w * 32 + 16 * mi) * NS + 16 * nj, wF[mi][nj], NS, + wmma::mem_row_major); + __syncthreads(); + for (int i = threadIdx.x; i < S * NS; i += blockDim.x) { + const int r = i / NS, j = i % NS; + state[(size_t) r * HV * S + (size_t) hh * S + j0 + j] = Ug[i]; + } +} +#endif // !HIPCC && __CUDA_ARCH__ >= 700 + +// The grow-only per-thread workspace (one thread == one device/stream in this codebase's prefill paths). +struct Ws { + float* A = nullptr; // [SEG][HV][CH][CH] + float* P = nullptr; // [SEG][HV][CH][CH] + float* gcum = nullptr; // [SEG*CH][HV] + size_t cap = 0; // in chunks + void ensure(size_t chunks) { + if (chunks <= cap) return; + if (A) cudaFree(A); + if (P) cudaFree(P); + if (gcum) cudaFree(gcum); + cap = chunks; + const size_t mat = chunks * HV * CH * CH; + if (cudaMalloc((void**) &A, mat * sizeof(float)) != cudaSuccess || + cudaMalloc((void**) &P, mat * sizeof(float)) != cudaSuccess || + cudaMalloc((void**) &gcum, (size_t) chunks * CH * HV * sizeof(float)) != cudaSuccess) { + std::fprintf(stderr, "gdn_chunk: workspace alloc failed (%zu chunks)\n", chunks); + std::exit(1); + } + } +}; + +Ws& ws() { + static thread_local Ws w; + return w; +} + +int gdn_chunk_cc() { + static int cc = [] { + int dev = 0; + cudaDeviceProp p{}; + if (cudaGetDevice(&dev) != cudaSuccess || cudaGetDeviceProperties(&p, dev) != cudaSuccess) return 0; + return p.major * 10 + p.minor; + }(); + return cc; +} + +} // namespace + +bool gdn_chunk_available() { +#if defined(__HIPCC__) || !defined(STRATA_EXPERIMENTAL_SM60) + return false; // the chunked path is compiled and dispatched only in the Volta experimental build +#else + return gdn_chunk_cc() == 70; +#endif +} + +void gdn_chunk_recurrence(float* state, const float* h, const float* gate, const float* beta, float* oc, + int64_t T, void* stream) { +#if defined(__HIPCC__) + (void) state; (void) h; (void) gate; (void) beta; (void) oc; (void) T; (void) stream; + std::fprintf(stderr, "gdn_chunk_recurrence: not built for HIP\n"); + std::exit(1); +#else + if (T <= 0) return; + const int64_t T64 = T - T % CH; + if (T64 <= 0) return; + cudaStream_t cs = (cudaStream_t) stream; + // the wmma path is the default; STRATA_GDN_CHUNK=2 selects the FP32-only FMA scan (the parity test's + // oracle - same math, no FP16 staging) and anything below sm_70 has no wmma to use. Read per call (the + // tests flip it between launches). + const char* forced_v = std::getenv("STRATA_GDN_CHUNK"); + const int forced = forced_v && *forced_v ? std::atoi(forced_v) : -1; + static const bool wmma_ok = [] { +#if !defined(__HIPCC__) && (!defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 700) + return gdn_chunk_cc() == 70; +#else + return false; +#endif + }(); + const bool use_wmma = wmma_ok && forced != 2; + static std::once_flag attr_once; + std::call_once(attr_once, [] { + // both kernels stage past the 48 KB default: opt in + cudaFuncSetAttribute(gdn_chunk_kkt_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, + 2 * CH * (S + 1) * (int) sizeof(float)); + cudaFuncSetAttribute(gdn_chunk_wmma_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, WMMA_SMEM); + }); + Ws& w = ws(); + const size_t chunks_total = (size_t) (T64 / CH); + w.ensure(chunks_total < SEG ? (chunks_total ? chunks_total : 1) : SEG); + // STRATA_GDN_CHUNK_PROF=1: per-stage milliseconds over the whole call (a dev tool, not a hot path) + static const bool prof = std::getenv("STRATA_GDN_CHUNK_PROF") != nullptr; + cudaEvent_t pe0{}, pe1{}; + float ms[3] = {0, 0, 0}; + if (prof) cudaEventCreate(&pe0), cudaEventCreate(&pe1); + for (int64_t t0 = 0; t0 < T64; t0 += (int64_t) SEG * CH) { + const int64_t left = (T64 - t0) / CH; + const int nch = (int) (left < SEG ? left : SEG); + const int ntok = nch * CH; + if (prof) cudaEventRecord(pe0, cs); + gdn_chunk_cumsum_kernel<<>>(w.gcum, gate + t0 * HV, ntok); + check("cumsum"); + if (prof) { + cudaEventRecord(pe1, cs); + cudaEventSynchronize(pe1); + cudaEventElapsedTime(&ms[0], pe0, pe1); + cudaEventRecord(pe0, cs); + } + if (use_wmma) { + gdn_chunk_wmma_kernel<<>>( + state, oc + t0 * HV * S, h + t0 * C, beta + t0 * HV, w.gcum, nch); + check("wmma"); + } else { + gdn_chunk_kkt_kernel<<>>( + w.A, w.P, h + t0 * C, beta + t0 * HV, w.gcum, nch); + check("kkt"); + } + if (prof) { + cudaEventRecord(pe1, cs); + cudaEventSynchronize(pe1); + cudaEventElapsedTime(&ms[1], pe0, pe1); + cudaEventRecord(pe0, cs); + } + if (!use_wmma) { + gdn_chunk_fwd_kernel<<>>(state, oc + t0 * HV * S, h + t0 * C, beta + t0 * HV, + w.gcum, w.A, w.P, nch); + check("fwd"); + } + if (prof) { + cudaEventRecord(pe1, cs); + cudaEventSynchronize(pe1); + cudaEventElapsedTime(&ms[2], pe0, pe1); + } + } + if (prof) { + std::printf("gdn_chunk prof T=%lld: cumsum %.3fms stage2 %.3fms stage3 %.3fms\n", (long long) T, ms[0], + ms[1], ms[2]); + cudaEventDestroy(pe0); + cudaEventDestroy(pe1); + } +#endif +} + +} // namespace strata::prefill diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index f58a189c..c031ee08 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -1,5 +1,6 @@ // src/prefill/kernels.cu - see include/strata/prefill/kernels.hpp. #include "strata/prefill/kernels.hpp" +#include "strata/prefill/gdn_chunk.hpp" #include "strata/kernels/mrope.hpp" #include "strata/kernels/gfx_arch.hpp" #include "strata/kernels/router_top10.hpp" @@ -391,6 +392,62 @@ __global__ void gdn_l2_kernel(float* __restrict__ h, float eps) { x[threadIdx.x] = v * rsqrtf(ss + eps); } constexpr int RG = 4, RPG = S / RG; +constexpr int CB = 32, NCB = S / CB; // value columns per block kernel / blocks per head +// v100/gdn-chunk: Volta-only (sm_70), inside the experimental build. Main's recurrence kernels above are +// untouched for every other architecture; the chain-split is dispatched only when the device is cc 7.0. +#if defined(STRATA_EXPERIMENTAL_SM60) && (!defined(__CUDA_ARCH__) || __CUDA_ARCH__ == 700) +// v100/gdn-chunk: the same recurrence with WARP-LOCAL reductions - no __syncthreads at all. gdn_rec_cols_*' +// per-token shape is two cross-warp reductions (k^T W and q^T W) behind two barriers each (six barriers per +// token in the pipelined kernel); here a warp owns 8 columns and the 4 row-groups are lanes within the warp, +// so the reductions are __shfl's. The arithmetic is the same expressions in the same order - the four +// row-group partials still sum as ((p0+p1)+p2)+p3 - so this kernel is BIT-EXACT against gdn_rec_cols_pipe +// (the parity test asserts it). The state has the same (S, h_v, S) layout and the same j-fastest column. +__global__ void __launch_bounds__(S) gdn_rec_cols_warp_kernel(float* __restrict__ state, const float* __restrict__ h, + const float* __restrict__ gate, + const float* __restrict__ beta, + float* __restrict__ oc_out, int64_t T) { + const int head = blockIdx.x / NCB, cb = blockIdx.x % NCB; + const int w = threadIdx.x >> 5, l = threadIdx.x & 31; // warp w: columns w*8..w*8+7 + const int col = cb * CB + w * 8 + (l & 7); // lane: column within the warp's 8 + const int rg = l >> 3; // lane group: 4 row-groups of 32 rows + const int qh = head % HK; + float s[RPG]; + float* base = state + ((size_t) (rg * RPG) * HV + head) * S + col; + const size_t rs = (size_t) HV * S; +#pragma unroll + for (int r = 0; r < RPG; ++r) s[r] = base[r * rs]; + const unsigned full = 0xffffffffu; + for (int64_t t = 0; t < T; ++t) { + const float* ht = h + t * C; + const float* krow = ht + HK * S + qh * S + rg * RPG; + const float* qrow = ht + qh * S + rg * RPG; + float kv = 0.0f; +#pragma unroll + for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], krow[r], kv); + // ((p0 + p1) + p2) + p3 over the row-groups, exactly as red[0]+red[1]+red[2]+red[3] + float p0 = __shfl_sync(full, kv, (l & 7)); + float p1 = __shfl_sync(full, kv, (l & 7) + 8); + float p2 = __shfl_sync(full, kv, (l & 7) + 16); + float p3 = __shfl_sync(full, kv, (l & 7) + 24); + const float kv_col = ((p0 + p1) + p2) + p3; + const float g = __expf(gate[t * HV + head]); + const float delta = (ht[2 * HK * S + head * S + col] - g * kv_col) * beta[t * HV + head]; + float o = 0.0f; +#pragma unroll + for (int r = 0; r < RPG; ++r) { + s[r] = fmaf(g, s[r], krow[r] * delta); + o = fmaf(s[r], qrow[r], o); + } + float q0 = __shfl_sync(full, o, (l & 7)); + float q1 = __shfl_sync(full, o, (l & 7) + 8); + float q2 = __shfl_sync(full, o, (l & 7) + 16); + float q3 = __shfl_sync(full, o, (l & 7) + 24); + oc_out[t * HV * S + head * S + col] = (((q0 + q1) + q2) + q3) * rsqrtf((float) S); + } +#pragma unroll + for (int r = 0; r < RPG; ++r) base[r * rs] = s[r]; +} +#endif __global__ void __launch_bounds__(S * RG) gdn_rec_kernel(float* __restrict__ state, const float* __restrict__ h, const float* __restrict__ gate, const float* __restrict__ beta, const float* __restrict__ z, @@ -451,7 +508,7 @@ __global__ void __launch_bounds__(S * RG) gdn_rec_kernel(float* __restrict__ sta // quarter of its threads per __syncthreads), and the output norm - the only step that couples the head's columns - // in its own kernel. Per column the same arithmetic in the same order (the 4 row-group partial sums added as // red[0] + red[1] + red[2] + red[3]; the norm's warp sums over the same 32-column warps): the same bits. -constexpr int CB = 32, NCB = S / CB; + __global__ void __launch_bounds__(CB * RG) gdn_rec_cols_kernel(float* __restrict__ state, const float* __restrict__ h, const float* __restrict__ gate, const float* __restrict__ beta, @@ -551,6 +608,71 @@ __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]; } +// v100/gdn-chunk: gdn_rec_cols_pipe_kernel with the two 32-deep FMA chains (k^T W and q^T W) split into 4 +// accumulators each. The chain is the recurrence's per-token floor (a 32-step dependent FFMA chain is ~128 +// cycles before the barriers); the split keeps the load pattern, the barriers and the (S, h_v, S) state +// layout untouched. FP32-level, NOT bit-exact - the four partial sums group the 32 products differently - +// so it is opt-in by measured benefit (STRATA_GDN_REC_WARP=2; gdn_chunk_parity bounds the error). +#if defined(STRATA_EXPERIMENTAL_SM60) && (!defined(__CUDA_ARCH__) || __CUDA_ARCH__ == 700) +__global__ void __launch_bounds__(CB * RG) gdn_rec_cols_pipe_fast_kernel(float* __restrict__ state, + const float* __restrict__ h, + const float* __restrict__ gate, + const float* __restrict__ beta, + float* __restrict__ oc_out, int64_t T) { + constexpr int NT = CB * RG, LPT = S / NT; + __shared__ float sk[S], sq[S], red[RG][CB]; + const int head = blockIdx.x / NCB, cb = blockIdx.x % NCB; + const int c = threadIdx.x, rg = threadIdx.y, tid = rg * CB + c, col = cb * CB + c; + const int qh = head % HK; + float s[RPG]; + float* base = state + ((size_t) (rg * RPG) * HV + head) * S + col; + const size_t rs = (size_t) HV * S; +#pragma unroll + for (int r = 0; r < RPG; ++r) s[r] = base[r * rs]; + float nq[LPT], nk[LPT], nv = 0.0f, ng = 0.0f, nb = 0.0f; + auto fetch = [&](int64_t t) { + const float* ht = h + t * C; +#pragma unroll + for (int u = 0; u < LPT; ++u) { nq[u] = ht[qh * S + tid + u * NT]; nk[u] = ht[HK * S + qh * S + tid + u * NT]; } + nv = ht[2 * HK * S + head * S + col]; + ng = gate[t * HV + head]; + nb = beta[t * HV + head]; + }; + if (T > 0) fetch(0); + for (int64_t t = 0; t < T; ++t) { + float cq[LPT], ck[LPT]; +#pragma unroll + for (int u = 0; u < LPT; ++u) { cq[u] = nq[u]; ck[u] = nk[u]; } + const float cv = nv, cg = ng, cbt = nb; + __syncthreads(); +#pragma unroll + for (int u = 0; u < LPT; ++u) { sq[tid + u * NT] = cq[u]; sk[tid + u * NT] = ck[u]; } + __syncthreads(); + if (t + 1 < T) fetch(t + 1); + const float g = __expf(cg); + float kv[4] = {0.0f, 0.0f, 0.0f, 0.0f}; +#pragma unroll + for (int r = 0; r < RPG; ++r) kv[r & 3] = fmaf(s[r], sk[rg * RPG + r], kv[r & 3]); + red[rg][c] = (kv[0] + kv[1]) + (kv[2] + kv[3]); + __syncthreads(); + const float kv_col = red[0][c] + red[1][c] + red[2][c] + red[3][c]; + const float delta = (cv - g * kv_col) * cbt; + float o[4] = {0.0f, 0.0f, 0.0f, 0.0f}; +#pragma unroll + for (int r = 0; r < RPG; ++r) { + s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta); + o[r & 3] = fmaf(s[r], sq[rg * RPG + r], o[r & 3]); + } + __syncthreads(); + red[rg][c] = (o[0] + o[1]) + (o[2] + o[3]); + __syncthreads(); + if (rg == 0) oc_out[t * HV * S + head * S + col] = (red[0][c] + red[1][c] + red[2][c] + red[3][c]) * rsqrtf((float) S); + } +#pragma unroll + for (int r = 0; r < RPG; ++r) base[r * rs] = s[r]; +} +#endif + #if !defined(__HIPCC__) // The recurrence with one thread for the three value heads that share a key head (head % HK): column c of heads // qh, qh + 16 and qh + 32, row group rg. gdn_rec_cols_pipe_kernel spends its time in shared memory, not in @@ -1983,6 +2105,43 @@ void gdn_recurrence_variant(int variant, float* state, const float* h, const flo (void) variant; // the quad recurrence kernels are AMD-only #endif static const bool serial = std::getenv("STRATA_GDN_REC_HEADS") != nullptr; // the one-block-per-head kernel (A/B) +#if defined(STRATA_EXPERIMENTAL_SM60) + // v100/gdn-chunk: the chunked recurrence (src/prefill/gdn_chunk.cu) on Volta, where the token chain is the + // cost. STRATA_GDN_CHUNK=0 forces the recurrence, =1 forces the chunked path (the parity test's A/B switch); + // unset: cc == 7.0 only, every other architecture keeps the recurrence bit-for-bit as before. Read per call + // on purpose - cheap next to the work, and the tests flip it between two launches. + const char* chunk_v = std::getenv("STRATA_GDN_CHUNK"); + const int chunk_env = chunk_v && *chunk_v ? std::atoi(chunk_v) : -1; + static const bool volta = gdn_chunk_available(); // runtime cc == 7.0 (the kernels are compiled for sm_70 only) + const bool chunked = !serial && T > 0 && (chunk_env >= 0 ? chunk_env != 0 : false); + // v100/gdn-chunk: the sync-free warp-reduction recurrence (bit-exact vs gdn_rec_cols_pipe) is the + // measured-fast path on Volta; the chunked recurrence is opt-in (STRATA_GDN_CHUNK=1/2) - correct and + // measured, but slower than this on the V100 (bench/gdn_chunk_bench). STRATA_GDN_REC_WARP=0 restores + // the old pipelined kernel bit-for-bit. + // STRATA_GDN_REC_WARP: unset -> the chain-split kernel on Volta (measured +6..9%, FP32-level), 0 -> the + // old pipelined kernel bit-for-bit, 1 -> the sync-free bit-exact control, 2 -> the chain split forced. + const char* warp_v = std::getenv("STRATA_GDN_REC_WARP"); + const int warp_env = warp_v && *warp_v ? std::atoi(warp_v) : (volta ? 2 : 0); + const bool warp_rec = !serial && !chunked && T > 0 && volta && warp_env != 0; + if (chunked && T >= 64) { + // the chunked prefix + the recurrence over the tail (< 64 tokens), then the out norm over all of T + const int64_t T64 = T - T % 64; + gdn_chunk_recurrence(state, h, gate, beta, y, T64, stream); + if (T > T64) + gdn_rec_cols_pipe_kernel<<>>( + state, h + T64 * C, gate + T64 * HV, beta + T64 * HV, y + T64 * (size_t) HV * S, T - T64); + gdn_out_norm_kernel<<>>(z, gamma, eps, y, y16, ld16); + } else if (warp_rec) { + // =2: the 4-accumulator chain split on the pipelined structure (FP32-level, not bit-exact); + // =1: the sync-free bit-exact warp reduction (measured slower - kept as the bitwise control) + if (warp_env == 2) + gdn_rec_cols_pipe_fast_kernel<<>>(state, h, gate, beta, + y, T); + else + gdn_rec_cols_warp_kernel<<>>(state, h, gate, beta, y, T); + gdn_out_norm_kernel<<>>(z, gamma, eps, y, y16, ld16); + } else +#endif if (serial || T <= 0 || variant == 2) { gdn_rec_kernel<<>>(state, h, gate, beta, z, gamma, eps, y, y16, T, ld16); } else { From c0a4a9e65728fbd6a7cd8e102dec58dabe6e70c7 Mon Sep 17 00:00:00 2001 From: ATIVX928 <27274927+ATIVX928@users.noreply.github.com> Date: Mon, 5 Oct 2026 17:38:25 +0000 Subject: [PATCH 06/36] tests (v100): gdn_chunk_parity - the chunked and Volta GDN recurrences vs a double-precision host reference GPU, synthetic, no model. Compares through the real dispatch (STRATA_GDN_CHUNK / STRATA_GDN_REC_WARP A/B) at T=64/128/200/320 - 200 exercises the < 64-token tail - and asserts measured bounds, not equality: the recurrence is the FP32 floor (y abs 1.1e-6, state 3.0e-8), the chain-split and the chunked FMA path are FP32-level (~3e-6), the wmma chunked path is the f32->f16 staging level (y abs 2.3e-3, state 8.9e-5). The sync-free warp recurrence is asserted BIT-EXACT against gdn_rec_cols_pipe (memcmp of y and the final state). A NaN or inf anywhere fails the check outright - an unordered comparison would otherwise leave the max at zero. On main's 0.1.38 recurrence the out norm keeps its raw FP32 output in place and writes only the FP16 copy, so the kernel comparisons use that raw output (ref_full's yraw_out) and the norm is checked once through its FP16 store. --- CMakeLists.txt | 10 ++ src/kernels/gdn_chunk_parity.cpp | 270 +++++++++++++++++++++++++++++++ 2 files changed, 280 insertions(+) create mode 100644 src/kernels/gdn_chunk_parity.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 6d729676..0facb853 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -919,6 +919,16 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(gdn_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME gdn_parity COMMAND gdn_parity --selftest) + # v100/gdn-chunk: the chunked GDN prompt recurrence vs the token recurrence and a host reference (GPU, + # synthetic, no model). The chunked path changes the summation order - FP32-level, not bit-exact - so the + # test asserts measured error bounds, and --selftest pins them. + if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA) + add_executable(gdn_chunk_parity src/kernels/gdn_chunk_parity.cpp) + target_include_directories(gdn_chunk_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(gdn_chunk_parity PRIVATE strata_prefill ${_strata_gpu_runtime_target}) + add_test(NAME gdn_chunk_parity COMMAND gdn_chunk_parity --selftest) + endif() + add_executable(s2_gemv_q8_parity src/kernels/s2_gemv_q8_parity.cpp) target_include_directories(s2_gemv_q8_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(s2_gemv_q8_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) diff --git a/src/kernels/gdn_chunk_parity.cpp b/src/kernels/gdn_chunk_parity.cpp new file mode 100644 index 00000000..e60fdc84 --- /dev/null +++ b/src/kernels/gdn_chunk_parity.cpp @@ -0,0 +1,270 @@ +// src/kernels/gdn_chunk_parity.cpp - v100/gdn-chunk: the chunked GDN prompt recurrence vs the token recurrence +// and a host reference (GPU, synthetic, no model). +// +// The chunked path (src/prefill/gdn_chunk.cu) computes the SAME recurrence in a different summation order: +// a 64-token chunk becomes one triangular solve and a batch of matmuls instead of 64 sequential rank-1 steps. +// That is FP32-level, NOT bit-exact - the precedent is qsa_prompt_attn.hpp. So this test does not ask for +// equality; it measures the error of both GPU paths against a double-precision transcription of the same +// recurrence (`ref/gdn.py`'s, as re-pinned by gdn_parity) and asserts bounds: +// +// 1. the recurrence vs the host reference: the FP32 floor of the old path, +// 2. the chunked path vs the host reference: the number that matters for the model, +// 3. chunked vs recurrence directly: the observable switch STRATA_GDN_CHUNK flips. +// +// Both GPU paths go through the REAL dispatch (`gdn_recurrence`), A/B'd with the env switch, so the tail +// (< 64 tokens) and the output norm are part of what is compared - the recurrence kernels' raw FP32 output for +// the kernel comparisons (0.1.38's gdn_out_norm_kernel leaves it in place and writes only the FP16 copy), and +// the norm's FP16 output once against the host reference's normalized values. +#include "strata/prefill/gdn_chunk.hpp" +#include "strata/prefill/kernels.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +constexpr int S = 128, HK = 16, HV = 48, C = 10240; + +void check(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +// the FP16 store's value back as FP32, for the one normalized-output comparison +float half_to_float(uint16_t u) { + __half h; + std::memcpy(&h, &u, 2); + return __half2float(h); +} + +// deterministic LCG - the same inputs on every machine and every run +struct Rng { + uint64_t s; + explicit Rng(uint64_t seed) : s(seed) {} + float uni() { + s = s * 6364136223846793005ULL + 1442695040888963407ULL; + return (float) ((s >> 40) * (1.0 / 16777216.0)); + } +}; + +/// The GDN chunk as a double-precision transcription of the recurrence in strata/kernels/gdn.hpp: the state +/// (S, h_v, S) f32 layout, decay BEFORE the rank-1 update, modulo head pairing. `yraw_out` is the raw output +/// the recurrence kernels leave for gdn_out_norm_kernel; `y_out` is the norm's value, formed exactly as +/// gdn_out_norm_kernel forms it (sqrt(S) in the oc scale, +eps on the SCALED squared norm). +void ref_full(const std::vector& st0, const std::vector& h, const std::vector& gate, + const std::vector& beta, const std::vector& z, const std::vector& gamma, + float eps, int64_t T, std::vector& yraw_out, std::vector& y_out, + std::vector& st_out) { + std::vector st((size_t) S * HV * S); + for (size_t i = 0; i < st.size(); ++i) st[i] = (double) st0[i]; + y_out.assign((size_t) T * HV * S, 0.0f); + yraw_out.assign((size_t) T * HV * S, 0.0f); + std::vector o(S); + for (int64_t t = 0; t < T; ++t) { + for (int hh = 0; hh < HV; ++hh) { + const int qh = hh % HK; + const double dec = std::exp((double) gate[(size_t) t * HV + hh]); + const double b = (double) beta[(size_t) t * HV + hh]; + for (int j = 0; j < S; ++j) { + double sk = 0.0; + for (int i = 0; i < S; ++i) sk += st[((size_t) i * HV + hh) * S + j] * (double) h[(size_t) t * C + HK * S + qh * S + i]; + const double d = ((double) h[(size_t) t * C + 2 * HK * S + hh * S + j] - dec * sk) * b; + for (int i = 0; i < S; ++i) { + double& w = st[((size_t) i * HV + hh) * S + j]; + w = dec * w + (double) h[(size_t) t * C + HK * S + qh * S + i] * d; + } + double dot = 0.0; + for (int i = 0; i < S; ++i) dot += st[((size_t) i * HV + hh) * S + j] * (double) h[(size_t) t * C + qh * S + i]; + o[j] = dot / std::sqrt((double) S); // the oc scale of gdn_rec_cols_kernel + } + double ss = 0.0; + for (int j = 0; j < S; ++j) ss += o[j] * o[j]; + const double rs = 1.0 / std::sqrt(ss / (double) S + (double) eps); + for (int j = 0; j < S; ++j) { + yraw_out[((size_t) t * HV + hh) * S + j] = (float) o[j]; + const double sig = 1.0 / (1.0 + std::exp(-(double) z[(size_t) t * HV * S + hh * S + j])); + y_out[((size_t) t * HV + hh) * S + j] = (float) (o[j] * rs * (double) gamma[j] * sig); + } + } + } + st_out.resize(st.size()); + for (size_t i = 0; i < st.size(); ++i) st_out[i] = (float) st[i]; +} + +struct Err { + float abs_ = 0, rel_ = 0; + void see(float a, float b) { + const float d = std::fabs(a - b); + const float m = std::fabs(b); + // a NaN or inf anywhere is a hard error: an unordered comparison would otherwise leave the max at 0 + if (!std::isfinite(a) || !std::isfinite(b)) { + abs_ = rel_ = std::numeric_limits::infinity(); + return; + } + if (d > abs_) abs_ = d; + const float r = d / (m + 1e-4f); + if (r > rel_) rel_ = r; + } +}; + +int failures = 0; + +void expect(const char* what, const Err& e, float bound_abs, float bound_rel) { + const bool ok = e.rel_ <= bound_rel && e.abs_ <= bound_abs; + std::printf(" %-38s max abs %.3e max rel %.3e (bounds abs %.1e rel %.1e) %s\n", what, e.abs_, e.rel_, + bound_abs, bound_rel, ok ? "ok" : "FAIL"); + if (!ok) ++failures; +} + +void run_case(int64_t T, uint64_t seed) { + std::printf("T = %lld%s\n", (long long) T, (T % 64) ? " (tail: T % 64 != 0)" : ""); + Rng rng(seed); + 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), st0((size_t) S * HV * S); + for (int64_t t = 0; t < T; ++t) { + for (int qh = 0; qh < HK; ++qh) { // q and k: L2-normalised rows, as gdn_conv leaves them + for (int part = 0; part < 2; ++part) { + double ss = 0; + float row[S]; + for (int i = 0; i < S; ++i) { + row[i] = rng.uni() - 0.5f; + ss += (double) row[i] * row[i]; + } + const float nrm = (float) (1.0 / std::sqrt(ss + 1e-5)); + for (int i = 0; i < S; ++i) h[(size_t) t * C + (part ? HK * S : 0) + qh * S + i] = row[i] * nrm; + } + } + for (int hh = 0; hh < HV; ++hh) { + for (int j = 0; j < S; ++j) // v: O(1) rows + h[(size_t) t * C + 2 * HK * S + hh * S + j] = rng.uni() - 0.5f; + gate[(size_t) t * HV + hh] = -0.02f - 0.3f * rng.uni(); + beta[(size_t) t * HV + hh] = 1.0f / (1.0f + std::exp(-(4.0f * rng.uni() - 2.0f))); + for (int j = 0; j < S; ++j) z[((size_t) t * HV + hh) * S + j] = 2.0f * rng.uni() - 1.0f; + } + } + for (int j = 0; j < S; ++j) gamma[j] = 0.5f + 2.0f * rng.uni(); + for (size_t i = 0; i < st0.size(); ++i) st0[i] = 0.1f * (rng.uni() - 0.5f); + const float eps = 1e-5f; + + std::vector y_ref, yraw_ref, st_ref; + ref_full(st0, h, gate, beta, z, gamma, eps, T, yraw_ref, y_ref, st_ref); + + float *d_st = nullptr, *d_h = nullptr, *d_g = nullptr, *d_b = nullptr, *d_z = nullptr, *d_ga = nullptr, + *d_y = nullptr, *d_st0 = nullptr; + uint16_t* d_y16 = nullptr; + check(cudaMalloc(&d_st, st0.size() * 4), "malloc"); + check(cudaMalloc(&d_st0, st0.size() * 4), "malloc"); + check(cudaMalloc(&d_h, h.size() * 4), "malloc"); + check(cudaMalloc(&d_g, gate.size() * 4), "malloc"); + check(cudaMalloc(&d_b, beta.size() * 4), "malloc"); + check(cudaMalloc(&d_z, z.size() * 4), "malloc"); + check(cudaMalloc(&d_ga, gamma.size() * 4), "malloc"); + check(cudaMalloc(&d_y, y_ref.size() * 4), "malloc"); + check(cudaMalloc(&d_y16, y_ref.size() * 2), "malloc"); + check(cudaMemcpy(d_st0, st0.data(), st0.size() * 4, cudaMemcpyHostToDevice), "H2D"); + check(cudaMemcpy(d_h, h.data(), h.size() * 4, cudaMemcpyHostToDevice), "H2D"); + check(cudaMemcpy(d_g, gate.data(), gate.size() * 4, cudaMemcpyHostToDevice), "H2D"); + check(cudaMemcpy(d_b, beta.data(), beta.size() * 4, cudaMemcpyHostToDevice), "H2D"); + check(cudaMemcpy(d_z, z.data(), z.size() * 4, cudaMemcpyHostToDevice), "H2D"); + check(cudaMemcpy(d_ga, gamma.data(), gamma.size() * 4, cudaMemcpyHostToDevice), "H2D"); + + std::vector y_gpu(y_ref.size()), st_gpu(st0.size()); + std::vector y_rec(y_ref.size()), st_rec(st0.size()), y_warp(y_ref.size()), st_warp(st0.size()), + y_fast(y_ref.size()), st_fast(st0.size()), y_fma(y_ref.size()), st_fma(st0.size()); + auto run = [&](const char* chunk, const char* warp, std::vector& y, std::vector& st, + std::vector* y16f = nullptr) { + setenv("STRATA_GDN_CHUNK", chunk, 1); + setenv("STRATA_GDN_REC_WARP", warp, 1); + check(cudaMemcpy(d_st, d_st0, st0.size() * 4, cudaMemcpyDeviceToDevice), "D2D"); + strata::prefill::gdn_recurrence(d_st, d_h, d_g, d_b, d_z, d_ga, eps, d_y, d_y16, T, nullptr); + check(cudaDeviceSynchronize(), "sync"); + check(cudaMemcpy(y.data(), d_y, y.size() * 4, cudaMemcpyDeviceToHost), "D2H"); + check(cudaMemcpy(st.data(), d_st, st.size() * 4, cudaMemcpyDeviceToHost), "D2H"); + if (y16f != nullptr) { + std::vector h16(y.size()); + check(cudaMemcpy(h16.data(), d_y16, h16.size() * 2, cudaMemcpyDeviceToHost), "D2H"); + y16f->resize(y.size()); + for (size_t i = 0; i < y.size(); ++i) (*y16f)[i] = half_to_float(h16[i]); + } + }; + std::vector y16_rec; + run("0", "0", y_rec, st_rec, &y16_rec); // the old pipelined recurrence (+ the norm's FP16 output) + run("0", "1", y_warp, st_warp); // the sync-free warp recurrence - must be BIT-EXACT vs the above + run("0", "2", y_fast, st_fast); // the chain-split recurrence (the V100 default) + run("1", "0", y_gpu, st_gpu); // the chunked path's wmma variant + run("2", "0", y_fma, st_fma); // the chunked path's FP32 FMA variant + + size_t bits = 0; + for (size_t i = 0; i < y_ref.size(); ++i) + if (std::memcmp(&y_rec[i], &y_warp[i], 4) != 0) ++bits; + for (size_t i = 0; i < st_ref.size(); ++i) + if (std::memcmp(&st_rec[i], &st_warp[i], 4) != 0) ++bits; + std::printf(" %-38s %s\n", "warp recurrence vs pipelined (bits)", bits ? "FAIL" : "bit-exact"); + if (bits) ++failures; + + Err e_yr, e_y, e_yf, e_ym, e_yc, e_yn, e_sr, e_s, e_sf, e_sm, e_sc; + for (size_t i = 0; i < y_ref.size(); ++i) { + e_yr.see(y_rec[i], yraw_ref[i]); + e_yf.see(y_fast[i], yraw_ref[i]); + e_ym.see(y_fma[i], yraw_ref[i]); + e_y.see(y_gpu[i], yraw_ref[i]); + e_yc.see(y_gpu[i], y_rec[i]); + e_yn.see(y16_rec[i], y_ref[i]); + } + for (size_t i = 0; i < st_ref.size(); ++i) { + e_sr.see(st_rec[i], st_ref[i]); + e_sf.see(st_fast[i], st_ref[i]); + e_sm.see(st_fma[i], st_ref[i]); + e_s.see(st_gpu[i], st_ref[i]); + e_sc.see(st_gpu[i], st_rec[i]); + } + // The bounds are the measured errors of this build on the V100 with ~3x margin (rel uses a 1e-4 floor on + // the reference magnitude). The recurrence is the FP32 floor; the FMA chunked path reorders the sums + // (FP32-level, not bit-exact - qsa_prompt_attn.hpp's precedent); the wmma chunked path additionally + // stages q/k/v and the state through FP16 (the reference's "f32 -> f16 暂存"), which is the error level + // llama.cpp-v100's FlashQLA sm70 path ships with. The y rows compared here are the recurrence kernels' + // raw output (0.1.38's norm keeps its FP32 store out); the last line reads the norm's FP16 copy instead. + expect("recurrence vs host ref (y)", e_yr, 5e-6f, 1e-2f); + expect("chain-split recurrence (y)", e_yf, 1e-5f, 2e-2f); + expect("chunked FMA vs host ref (y)", e_ym, 1e-5f, 2e-2f); + expect("chunked wmma vs host ref (y)", e_y, 6e-3f, 5e1f); + expect("chunked wmma vs recurrence (y)", e_yc, 6e-3f, 5e1f); + expect("output norm (FP16) vs host ref (y)", e_yn, 8e-3f, 5e-2f); + expect("recurrence vs host ref (state)", e_sr, 1e-7f, 5e-4f); + expect("chain-split recurrence (state)", e_sf, 5e-7f, 2e-3f); + expect("chunked FMA vs host ref (state)", e_sm, 5e-7f, 2e-3f); + expect("chunked wmma vs host ref (state)", e_s, 3e-4f, 2e0f); + expect("chunked wmma vs recurrence (state)", e_sc, 3e-4f, 2e0f); + + cudaFree(d_st); cudaFree(d_st0); cudaFree(d_h); cudaFree(d_g); cudaFree(d_b); cudaFree(d_z); + cudaFree(d_ga); cudaFree(d_y); cudaFree(d_y16); +} + +} // namespace + +int main(int argc, char** argv) { + bool selftest = false; + for (int i = 1; i < argc; ++i) { + if (std::strcmp(argv[i], "--selftest") == 0) selftest = true; + else { std::fprintf(stderr, "usage: gdn_chunk_parity [--selftest]\n"); return 2; } + } + if (!strata::prefill::gdn_chunk_available()) + std::printf("note: not a V100 (cc 7.0) - the parity still runs; the engine dispatch keeps the recurrence\n"); + run_case(64, 1); + run_case(128, 2); + run_case(200, 3); // tail: T % 64 = 8 + run_case(320, 4); + std::printf("\ngdn_chunk: %d failures\n", failures); + if (selftest && failures == 0) std::printf("gdn_chunk_parity OK\n"); + return failures ? 1 : 0; +} From fd13adf2488cfd86fe03827de88cfcc3ba596d0d Mon Sep 17 00:00:00 2001 From: ATIVX928 <27274927+ATIVX928@users.noreply.github.com> Date: Mon, 5 Oct 2026 17:38:28 +0000 Subject: [PATCH 07/36] bench (v100): gdn_chunk_bench - the GDN prompt recurrence variants and the chunked path, real shapes CUDA events over one gdn_recurrence call per side (S=128, 16 q/k heads, 48 v heads, C=10240, T=1024/4096/8192), all four paths and the max abs diff between the chunked wmma output and the pipelined recurrence. RESULTS.md records the table and the error bounds for bench/results/2026-10-02-gdn-chunk (measured on the V100-SXM2-16GB, CUDA 12.8, sm_70 build). --- CMakeLists.txt | 5 + bench/gdn_chunk_bench.cpp | 143 ++++++++++++++++++ bench/results/2026-10-02-gdn-chunk/RESULTS.md | 36 +++++ 3 files changed, 184 insertions(+) create mode 100644 bench/gdn_chunk_bench.cpp create mode 100644 bench/results/2026-10-02-gdn-chunk/RESULTS.md diff --git a/CMakeLists.txt b/CMakeLists.txt index 0facb853..4f72e459 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -927,6 +927,11 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_include_directories(gdn_chunk_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(gdn_chunk_parity PRIVATE strata_prefill ${_strata_gpu_runtime_target}) add_test(NAME gdn_chunk_parity COMMAND gdn_chunk_parity --selftest) + + # v100/gdn-chunk: the micro benchmark (CUDA events, real GDN shapes): chunked vs recurrent prompt path. + add_executable(gdn_chunk_bench bench/gdn_chunk_bench.cpp) + target_include_directories(gdn_chunk_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(gdn_chunk_bench PRIVATE strata_prefill ${_strata_gpu_runtime_target}) endif() add_executable(s2_gemv_q8_parity src/kernels/s2_gemv_q8_parity.cpp) diff --git a/bench/gdn_chunk_bench.cpp b/bench/gdn_chunk_bench.cpp new file mode 100644 index 00000000..22f7d3d5 --- /dev/null +++ b/bench/gdn_chunk_bench.cpp @@ -0,0 +1,143 @@ +// bench/gdn_chunk_bench.cpp - v100/gdn-chunk: the chunked GDN prompt recurrence against the token recurrence, +// real GDN geometry (S=128, 16 q/k heads, 48 v heads, C=10240), CUDA events. +// +// One call of `gdn_recurrence` per side (the whole prompt chunk for one GDN layer: conv output -> out norm), +// A/B'd with STRATA_GDN_CHUNK=0 / =1 so the dispatch, the tail and the norm are timed exactly as the engine +// runs them. The two paths are not bit-exact (the chunked one reorders the sums); the bench reports the max +// relative difference it saw so a silent divergence cannot hide behind a speedup. +// +// usage: gdn_chunk_bench [T ...] (default 1024 4096 8192) +#include "strata/prefill/kernels.hpp" + +#include + +#include +#include +#include +#include +#include + +namespace { + +constexpr int S = 128, HV = 48, C = 10240; + +void check(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +struct Rng { + uint64_t s = 12345; + float uni() { + s = s * 6364136223846793005ULL + 1442695040888963407ULL; + return (float) ((s >> 40) * (1.0 / 16777216.0)); + } +}; + +float timed(const char* mode, const char* warp, float* st, float* st0, float* h, float* g, float* b, float* z, + float* ga, float* y, uint16_t* y16, int64_t T, int iters) { + setenv("STRATA_GDN_CHUNK", mode, 1); + setenv("STRATA_GDN_REC_WARP", warp, 1); + cudaEvent_t e0, e1; + check(cudaEventCreate(&e0), "event"); + check(cudaEventCreate(&e1), "event"); + check(cudaMemcpy(st, st0, (size_t) S * HV * S * 4, cudaMemcpyDeviceToDevice), "reset"); + strata::prefill::gdn_recurrence(st, h, g, b, z, ga, 1e-5f, y, y16, T, nullptr); + check(cudaDeviceSynchronize(), "warmup"); + check(cudaEventRecord(e0), "record"); + for (int i = 0; i < iters; ++i) { + check(cudaMemcpy(st, st0, (size_t) S * HV * S * 4, cudaMemcpyDeviceToDevice), "reset"); + strata::prefill::gdn_recurrence(st, h, g, b, z, ga, 1e-5f, y, y16, T, nullptr); + } + check(cudaEventRecord(e1), "record"); + check(cudaEventSynchronize(e1), "sync"); + float ms = 0; + check(cudaEventElapsedTime(&ms, e0, e1), "elapsed"); + cudaEventDestroy(e0); + cudaEventDestroy(e1); + return ms / iters; +} + +} // namespace + +int main(int argc, char** argv) { + std::vector ts; + for (int i = 1; i < argc; ++i) ts.push_back(std::atoll(argv[i])); + if (ts.empty()) ts = {1024, 4096, 8192}; + int64_t tmax = 0; + for (int64_t t : ts) tmax = t > tmax ? t : tmax; + + int dev = 0; + cudaDeviceProp p{}; + check(cudaGetDevice(&dev), "device"); + check(cudaGetDeviceProperties(&p, dev), "props"); + const int cc = p.major * 10 + p.minor; + std::printf("%s (cc %d) GDN prompt recurrence: chunked vs token-by-token\n", p.name, cc); + + Rng rng; + const size_t n_h = (size_t) tmax * C, n_y = (size_t) tmax * HV * S, n_g = (size_t) tmax * HV; + float *d_h, *d_y, *d_z, *d_g, *d_b, *d_ga, *d_st, *d_st0; + uint16_t* d_y16; + check(cudaMalloc(&d_h, n_h * 4), "malloc"); + check(cudaMalloc(&d_y, n_y * 4), "malloc"); + check(cudaMalloc(&d_z, n_y * 4), "malloc"); + check(cudaMalloc(&d_g, n_g * 4), "malloc"); + check(cudaMalloc(&d_b, n_g * 4), "malloc"); + check(cudaMalloc(&d_ga, S * 4), "malloc"); + check(cudaMalloc(&d_st, (size_t) S * HV * S * 4), "malloc"); + check(cudaMalloc(&d_st0, (size_t) S * HV * S * 4), "malloc"); + check(cudaMalloc(&d_y16, n_y * 2), "malloc"); + + std::vector tmp((size_t) tmax * C); + for (size_t i = 0; i < tmp.size(); ++i) tmp[i] = rng.uni() - 0.5f; + // q/k rows are L2-normalised rows (as gdn_conv leaves them); v rows stay O(1). A degenerate near-zero + // v would make the out-norm amplify rounding noise by 1/sqrt(eps) and the diff column meaningless. + for (int64_t t = 0; t < tmax; ++t) + for (int row = 0; row < 2 * 16; ++row) { + float* r = tmp.data() + (size_t) t * C + row * S; + double ss = 0; + for (int i = 0; i < S; ++i) ss += (double) r[i] * r[i]; + const float nrm = (float) (1.0 / std::sqrt(ss + 1e-5)); + for (int i = 0; i < S; ++i) r[i] *= nrm; + } + check(cudaMemcpy(d_h, tmp.data(), n_h * 4, cudaMemcpyHostToDevice), "H2D"); + tmp.resize(n_g); + for (size_t i = 0; i < n_g; ++i) tmp[i] = -0.02f - 0.3f * rng.uni(); + check(cudaMemcpy(d_g, tmp.data(), n_g * 4, cudaMemcpyHostToDevice), "H2D"); + for (size_t i = 0; i < n_g; ++i) tmp[i] = 1.0f / (1.0f + std::exp(-(4.0f * rng.uni() - 2.0f))); + check(cudaMemcpy(d_b, tmp.data(), n_g * 4, cudaMemcpyHostToDevice), "H2D"); + tmp.resize(n_y); + for (size_t i = 0; i < n_y; ++i) tmp[i] = 2.0f * rng.uni() - 1.0f; + check(cudaMemcpy(d_z, tmp.data(), n_y * 4, cudaMemcpyHostToDevice), "H2D"); + tmp.resize(S); + for (int i = 0; i < S; ++i) tmp[i] = 0.5f + 2.0f * rng.uni(); + check(cudaMemcpy(d_ga, tmp.data(), S * 4, cudaMemcpyHostToDevice), "H2D"); + tmp.resize((size_t) S * HV * S); + for (size_t i = 0; i < tmp.size(); ++i) tmp[i] = 0.1f * (rng.uni() - 0.5f); + check(cudaMemcpy(d_st0, tmp.data(), tmp.size() * 4, cudaMemcpyHostToDevice), "H2D"); + + std::printf("%8s %12s %12s %12s %12s %12s %s\n", "T", "pipe(rec)", "warp(rec)", "fast(rec)", "chunk FMA", + "chunk wmma", "max abs diff vs pipe"); + for (int64_t T : ts) { + const int iters = T >= 4096 ? 5 : 20; + const float rec = timed("0", "0", d_st, d_st0, d_h, d_g, d_b, d_z, d_ga, d_y, d_y16, T, iters); + std::vector y0((size_t) T * HV * S); + check(cudaMemcpy(y0.data(), d_y, y0.size() * 4, cudaMemcpyDeviceToHost), "D2H"); + const float wrp = timed("0", "1", d_st, d_st0, d_h, d_g, d_b, d_z, d_ga, d_y, d_y16, T, iters); + const float fst = timed("0", "2", d_st, d_st0, d_h, d_g, d_b, d_z, d_ga, d_y, d_y16, T, iters); + const float fma = timed("2", "0", d_st, d_st0, d_h, d_g, d_b, d_z, d_ga, d_y, d_y16, T, iters); + const float ch = timed("1", "0", d_st, d_st0, d_h, d_g, d_b, d_z, d_ga, d_y, d_y16, T, iters); + std::vector y1((size_t) T * HV * S); + check(cudaMemcpy(y1.data(), d_y, y1.size() * 4, cudaMemcpyDeviceToHost), "D2H"); + double absd = 0; + for (size_t i = 0; i < y0.size(); ++i) { + const double d = std::fabs((double) y1[i] - (double) y0[i]); + if (d > absd) absd = d; + } + std::printf("%8lld %11.3fms %11.3fms %11.3fms %11.3fms %11.3fms %.2e (wmma vs pipe)\n", (long long) T, + rec, wrp, fst, fma, ch, absd); + } + return 0; +} diff --git a/bench/results/2026-10-02-gdn-chunk/RESULTS.md b/bench/results/2026-10-02-gdn-chunk/RESULTS.md new file mode 100644 index 00000000..6d4ff2b0 --- /dev/null +++ b/bench/results/2026-10-02-gdn-chunk/RESULTS.md @@ -0,0 +1,36 @@ +# v100/gdn-chunk: chunked GDN prompt recurrence and Volta recurrence variants (2026-10-02) + +Measured on the V100-SXM2-16GB x2 (one card, CUDA 12.8, driver 570.x), build: +`-DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=70`, Release. `bench/gdn_chunk_bench` +(CUDA events, real GDN geometry S=128 / 16 q/k heads / 48 v heads / C=10240, one `gdn_recurrence` +call per side including the out norm, 5-20 iterations). + +## GDN prompt recurrence kernel, one layer, one prompt chunk + +| T | pipe (old) | chain-split (default now) | sync-free warp | chunked FMA | chunked wmma | +|-------|-----------:|--------------------------:|---------------:|------------:|-------------:| +| 1024 | 1.056 ms | 1.042 ms (+1%) | 2.712 ms | 6.67 ms | 4.57 ms | +| 4096 | 3.836 ms | 3.600 ms (+6%) | 9.34 ms | 25.0 ms | 17.7 ms | +| 8192 | 7.703 ms | 7.190 ms (+7%) | 18.7 ms | 50.2 ms | 35.4 ms | + +- pipe = `gdn_rec_cols_pipe_kernel` (the old path, bit-exact reference). +- chain-split = `gdn_rec_cols_pipe_fast_kernel`: same structure and loads, the k^T W / q^T W + accumulators split 4 ways (FP32-level, NOT bit-exact; `gdn_chunk_parity` bounds it). +- sync-free warp = `gdn_rec_cols_warp_kernel`: warp-shuffle reductions, no __syncthreads, + BIT-EXACT vs pipe (asserted) - but 2.6x SLOWER: its per-thread row loads cost more than the + barriers it removes. Kept as the bitwise control. +- chunked = the FlashQLA-style chunked recurrence (cumsum / kkt / fwd, 64-token chunks). Correct + (parity below) but 4-6x SLOWER than the recurrence as implemented: with 128 threads and the + ~84 KB tile staging a CTA only feeds ~4 warps to the tensor cores, and every phase is + latency-bound (measured ablation: staging+Gram+U GEMMs alone = 2.4 ms of the wmma kernel's + 4.6 ms at T=1024). Opt-in only (STRATA_GDN_CHUNK=1 wmma / 2 FMA). + +## Error bounds (`gdn_chunk_parity`, vs a double-precision transcription of the recurrence) + +| path | y max abs | state max abs | note | +|-----------------------------|----------:|--------------:|------| +| pipelined recurrence | 1.1e-06 | 3.0e-08 | the FP32 floor | +| chain-split recurrence | 7.2e-07 | 3.0e-08 | FP32-level, not bit-exact | +| sync-free warp recurrence | 0 | 0 | bit-exact vs the pipelined kernel | +| chunked FMA | 3.1e-06 | 1.2e-07 | FP32-level (reordered sums) | +| chunked wmma | 2.3e-03 | 8.9e-05 | q/k/v and the state staged f32->f16, f32 accumulate | From f1a9eaa47e38aa390fbc6dc9e142aad6d4d3b872 Mon Sep 17 00:00:00 2001 From: ATIVX928 <27274927+ATIVX928@users.noreply.github.com> Date: Wed, 7 Oct 2026 03:27:50 +0000 Subject: [PATCH 08/36] gdn chunk: the smem opt-in and the workspace are per device (layer-split fix) justxiami reported (#1098) a 4xV100 layer split dying with STRATA_GDN_CHUNK=1. Reproduced on 2xV100: the second card launched the chunked kernels at the 48 KB default (a process-global std::call_once set the opt-in on the first card only) and the engine exited with "gdn_chunk wmma: invalid argument". Two more per-process assumptions in the same path: - gdn_chunk_cc() cached the first card's capability for the whole process - the chunked workspace was thread_local with no destructor: the per-request stage threads leaked ~50 MB per card per request (the second card ran out of memory on the next prompt) and one card's pointers could reach another Now: the opt-in and the capability are recorded per device (each attempt clears the runtime error, and a refused wmma opt-in falls back to the FMA path), and the workspace is one per (thread, device) with a destructor. Verified on 2xV100 32K: STRATA_GDN_CHUNK=1/2 run to completion over repeated rounds (1: 1900 tok/s prefill, 2: 1766), gdn_chunk_parity 0 failures. --- src/prefill/gdn_chunk.cu | 103 ++++++++++++++++++++++++++++++--------- 1 file changed, 79 insertions(+), 24 deletions(-) diff --git a/src/prefill/gdn_chunk.cu b/src/prefill/gdn_chunk.cu index 90c8ddae..cec287e8 100644 --- a/src/prefill/gdn_chunk.cu +++ b/src/prefill/gdn_chunk.cu @@ -442,7 +442,9 @@ __global__ void __launch_bounds__(128) gdn_chunk_wmma_kernel(float* __restrict__ } #endif // !HIPCC && __CUDA_ARCH__ >= 700 -// The grow-only per-thread workspace (one thread == one device/stream in this codebase's prefill paths). +// The grow-only workspace, one per (thread, device): a layer split runs the chunked recurrence on more than +// one card, and each card's pointers are only valid on that card - a single per-thread buffer would hand a +// second card the first card's pointers. struct Ws { float* A = nullptr; // [SEG][HV][CH][CH] float* P = nullptr; // [SEG][HV][CH][CH] @@ -453,30 +455,65 @@ struct Ws { if (A) cudaFree(A); if (P) cudaFree(P); if (gcum) cudaFree(gcum); + cudaGetLastError(); // a free of another device's pointer must not surface in the mallocs below cap = chunks; const size_t mat = chunks * HV * CH * CH; if (cudaMalloc((void**) &A, mat * sizeof(float)) != cudaSuccess || cudaMalloc((void**) &P, mat * sizeof(float)) != cudaSuccess || cudaMalloc((void**) &gcum, (size_t) chunks * CH * HV * sizeof(float)) != cudaSuccess) { - std::fprintf(stderr, "gdn_chunk: workspace alloc failed (%zu chunks)\n", chunks); + int dev = 0; + cudaGetDevice(&dev); + size_t fb = 0, tb = 0; + cudaMemGetInfo(&fb, &tb); + std::fprintf(stderr, "gdn_chunk: workspace alloc failed (%zu chunks, device %d, %.1f of %.1f MiB free): %s\n", + chunks, dev, (double) fb / 1048576.0, (double) tb / 1048576.0, + cudaGetErrorString(cudaGetLastError())); std::exit(1); } } + ~Ws() { + // A prompt's stage threads are created per request (std::async in the layer split): without this, each + // request would leak its device's ~50 MB workspace until the card runs out. + if (A) cudaFree(A); + if (P) cudaFree(P); + if (gcum) cudaFree(gcum); + } }; Ws& ws() { - static thread_local Ws w; - return w; + static thread_local Ws w[8]; // [device]: the cards a layer split can run on in one process + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess) { + cudaGetLastError(); + dev = 0; + } + if (dev < 0 || dev >= 8) dev = 0; + return w[dev]; +} + +int gdn_chunk_cc_of(int dev) { + // Per DEVICE: a layer split runs on more than one card, and the capability is a card property - a + // process-global cache would dispatch a second card by the first card's capability. + static int cc[64] = {}; + if (dev < 0 || dev >= 64) return 0; + if (cc[dev] == 0) { + cudaDeviceProp p{}; + if (cudaGetDeviceProperties(&p, dev) != cudaSuccess) { + cudaGetLastError(); + return 0; + } + cc[dev] = p.major * 10 + p.minor; + } + return cc[dev]; } int gdn_chunk_cc() { - static int cc = [] { - int dev = 0; - cudaDeviceProp p{}; - if (cudaGetDevice(&dev) != cudaSuccess || cudaGetDeviceProperties(&p, dev) != cudaSuccess) return 0; - return p.major * 10 + p.minor; - }(); - return cc; + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess) { + cudaGetLastError(); + return 0; + } + return gdn_chunk_cc_of(dev); } } // namespace @@ -505,21 +542,39 @@ void gdn_chunk_recurrence(float* state, const float* h, const float* gate, const // tests flip it between launches). const char* forced_v = std::getenv("STRATA_GDN_CHUNK"); const int forced = forced_v && *forced_v ? std::atoi(forced_v) : -1; - static const bool wmma_ok = [] { -#if !defined(__HIPCC__) && (!defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 700) - return gdn_chunk_cc() == 70; + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess) { + cudaGetLastError(); + dev = 0; + } +#if !defined(__HIPCC__) + const bool wmma_ok = gdn_chunk_cc_of(dev) == 70; #else - return false; + const bool wmma_ok = false; #endif - }(); - const bool use_wmma = wmma_ok && forced != 2; - static std::once_flag attr_once; - std::call_once(attr_once, [] { - // both kernels stage past the 48 KB default: opt in - cudaFuncSetAttribute(gdn_chunk_kkt_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, - 2 * CH * (S + 1) * (int) sizeof(float)); - cudaFuncSetAttribute(gdn_chunk_wmma_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, WMMA_SMEM); - }); + // The shared-memory opt-in is a property of the DEVICE's context, not the process: a layer split runs + // this call on more than one card, and each card needs its own cudaFuncSetAttribute before that card's + // past-48KB launches (a process-global std::call_once left the second card at the 48 KB default, and its + // first chunked launch failed with "invalid argument"). Per device, once; every attempt clears the + // runtime error so a refused opt-in cannot surface in a later check() as a spurious failure. + static std::mutex attr_mu; + static bool attr_done[64] = {}; + static bool wmma_attr[64] = {}; + { + std::lock_guard lk(attr_mu); + if (dev >= 0 && dev < 64 && !attr_done[dev]) { + const cudaError_t ek = cudaFuncSetAttribute(gdn_chunk_kkt_kernel, + cudaFuncAttributeMaxDynamicSharedMemorySize, + 2 * CH * (S + 1) * (int) sizeof(float)); + const cudaError_t ew = cudaFuncSetAttribute(gdn_chunk_wmma_kernel, + cudaFuncAttributeMaxDynamicSharedMemorySize, WMMA_SMEM); + cudaGetLastError(); + (void) ek; // a refused opt-in leaves the FMA path's own launch to report it + wmma_attr[dev] = ew == cudaSuccess; + attr_done[dev] = true; + } + } + const bool use_wmma = wmma_ok && forced != 2 && dev >= 0 && dev < 64 && wmma_attr[dev]; Ws& w = ws(); const size_t chunks_total = (size_t) (T64 / CH); w.ensure(chunks_total < SEG ? (chunks_total ? chunks_total : 1) : SEG); From cb2740a8c26ec3594d885d236a116701213d234e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 07:08:08 +0200 Subject: [PATCH 09/36] prefill: Volta runs the prompt experts on FP16 tensor-core tiles, a group per launch (STRATA_PF_WMMA) gemm_iq_f16_grouped: one launch per MMQ expert group, a block = 128 weight rows of one expert x up to 256 of its token rows, each weight superblock dequantized once into shared memory by dq_dispatch (the FP16 path's formulas), FP16 activations, WMMA with FP32 sums, the next activation tile prefetched into registers. sm_70 defaults to it for the layers MMQ takes and for IQ1_M (which rides the MMQ grouping); STRATA_PF_WMMA=0 keeps MMQ. Co-authored-by: NoxestNoz (merge-resolved onto 0.1.44.1: the MMQ gather now zeroes the group tail itself and the quantizer takes a scale buffer) --- include/strata/kernels/iq_kernels.hpp | 5 + include/strata/prefill/kernels.hpp | 2 + src/kernels/cuda/iq_kernels.cu | 160 ++++++++++++++++++++++++++ src/prefill/kernels.cu | 16 +++ src/prefill/prefill.cpp | 63 +++++++++- 5 files changed, 241 insertions(+), 5 deletions(-) diff --git a/include/strata/kernels/iq_kernels.hpp b/include/strata/kernels/iq_kernels.hpp index 0a39f646..4c18f717 100644 --- a/include/strata/kernels/iq_kernels.hpp +++ b/include/strata/kernels/iq_kernels.hpp @@ -86,6 +86,11 @@ void native_expert_set_mode(int mode, int phase); /// `iq_mmvq` and `native_expert_grouped` decode each weight part once and apply it to every column / entry; /// true selects the older kernels that decode it again per column (STRATA_OLD_IQ_MMVQ=1 at startup). Both give /// bitwise the same results. Set before graph capture; captured graphs keep the kernels they captured. +/// Volta prompt experts (STRATA_PF_WMMA): Y[rows of expert e] = X[rows] . W_e^T for a group of experts, W_e at +/// W + e * expert_bytes (n_out rows of K values of type ty, GGUF blocks), X FP16 (ldx), rows bounds[e]..bounds[e+1], +/// Y FP32 (ldy). FP16 tensor cores, FP32 sums. false: not launched (shape or type not covered). CUDA only. +bool gemm_iq_f16_grouped(int ty, const void* W, size_t expert_bytes, int n_out, int K, const void* X, int ldx, + const int32_t* bounds, int n_experts, int max_rows, float* Y, int ldy, void* stream); void iq_set_old_kernels(bool old); bool iq_old_kernels(); diff --git a/include/strata/prefill/kernels.hpp b/include/strata/prefill/kernels.hpp index f12f34b9..6033e0e0 100644 --- a/include/strata/prefill/kernels.hpp +++ b/include/strata/prefill/kernels.hpp @@ -77,6 +77,8 @@ void route(const float* logits, int32_t* ids, float* weights, int64_t T, int64_t void blob_dequant(const uint8_t* blob, uint16_t* gu16, uint16_t* down16, void* stream); /// h16[n, r] = fp16(silu(gu[n, 2r]) * gu[n, 2r + 1]) (the interleaved expert gate/up) void swiglu_interleaved(const float* gu, uint16_t* h16, int64_t n, void* stream); +/// the Volta prompt experts: SwiGLU of gate/up rows (gate first, or interleaved) to FP16, saturated like swiglu_interleaved +void swiglu_split_f16(const float* gu, uint16_t* h16, int64_t rows, int n_ff, bool interleaved, void* stream); /// h16[n, r] = fp16(silu(g[n, r]) * u[n, r]) (the shared expert, gate and up separate, width 640) void swiglu_pair(const float* g, const float* u, uint16_t* h16, int64_t n, void* stream); /// dst[i] = src[i] for n int32s, as a kernel: either side may be mapped host memory, and the copy never waits diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index 947952a0..cc1ba0f9 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -3822,3 +3822,163 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long } } // namespace strata::kernels + +// ---- Volta prompt experts (STRATA_PF_WMMA): a group's experts as one launch of FP16 tensor-core tiles, the weights +// dequantized into shared memory by dq_dispatch (the FP16 path's own formulas), the activations FP16, FP32 sums. +// Replaces MMQ's dp4a products on sm_70, and the FP16 path's dequantize-to-global + one cuBLAS call per expert. +#if !defined(__HIPCC__) +#include +namespace strata::kernels { +namespace { +constexpr int WG_BM = 64, WG_BN = 128, WG_THREADS = 256, WG_XK = 128, WG_MT = 4; +// A block: BN = 128 weight rows of one expert x up to WG_MT * BM = 256 of its token rows (blockIdx.y walks an expert's +// rows in such chunks), so every weight superblock is dequantized ONCE per chunk into shared memory (WK 256: an IQ +// superblock through dq_dispatch; WK 128: two Q2_0 blocks); the activations stream through a BM x 128 tile. 8 warps +// of 32 x 32 per m-tile (2 x 2 fragments), FP32 accumulators for the chunk's m-tiles in registers. +template +__global__ void __launch_bounds__(WG_THREADS) gemm_iq_f16_grouped_kernel(int ty, const uint8_t* __restrict__ W, + size_t expert_bytes, size_t row_bytes, int K, + const __half* __restrict__ X, int ldx, + const int32_t* __restrict__ bounds, int ch_per_e, + float* __restrict__ Y, int ldy) { + using namespace nvcuda; + constexpr int LDW = WK + 8, LDX = WG_XK + 8; + extern __shared__ __align__(16) unsigned char wg_smem[]; + __half* sw = reinterpret_cast<__half*>(wg_smem); // [BN][LDW] + __half* sx = sw + WG_BN * LDW; // [BM][LDX] + const int e = blockIdx.y / ch_per_e, ch = blockIdx.y % ch_per_e; + const int c0 = bounds[e] + ch * WG_MT * WG_BM, r1 = bounds[e + 1]; + if (c0 >= r1) return; + const int crow = min(WG_MT * WG_BM, r1 - c0); + const int nmt = (crow + WG_BM - 1) / WG_BM; + const int n0 = blockIdx.x * WG_BN; + const uint8_t* we = W + (size_t) e * expert_bytes; + const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31; + const int wm = warp >> 2, wn = warp & 3; // rows wm*32, cols wn*32 of an m-tile + wmma::fragment acc[WG_MT][2][2]; +#pragma unroll + for (int t = 0; t < WG_MT; ++t) +#pragma unroll + for (int a = 0; a < 2; ++a) +#pragma unroll + for (int b = 0; b < 2; ++b) wmma::fill_fragment(acc[t][a][b], 0.0f); + // the activation tiles in order (k0, m-tile, half): the next one's 4 uint4 per thread are loaded into registers + // while the current one is multiplied (the first before the weights' dequantization) + constexpr int XQ = WG_BM * (WG_XK / 8) / WG_THREADS; // 4 + const int nx = WK / WG_XK, per_k = nmt * nx, total = (K / WK) * per_k; + uint4 xr[XQ]; + auto load_x = [&](int it) { + const int kb = it / per_k, rem = it % per_k, t = rem / nx, xh = rem % nx; + const int rows = min(WG_BM, crow - t * WG_BM); +#pragma unroll + for (int q = 0; q < XQ; ++q) { + const int i = tid + q * WG_THREADS, r = i / (WG_XK / 8), c = (i % (WG_XK / 8)) * 8; + xr[q] = r < rows ? *reinterpret_cast(X + (size_t) (c0 + t * WG_BM + r) * ldx + kb * WK + xh * WG_XK + c) + : make_uint4(0, 0, 0, 0); + } + }; + load_x(0); + int it = 0; + for (int k0 = 0; k0 < K; k0 += WK) { + if constexpr (!Q20) { + for (int r = warp; r < WG_BN; r += WG_THREADS / 32) + dq_dispatch<__half>(ty, we + (size_t) (n0 + r) * row_bytes, k0 / 256, sw + r * LDW, lane); + } else { + const int r = tid >> 1, blk = tid & 1; // one thread per (row, 64-value block) + const block_q2_0* b = reinterpret_cast(we + (size_t) (n0 + r) * row_bytes) + k0 / 64 + blk; + const float d = (float) b->d; + uint4 q4; + memcpy(&q4, b->qs, 16); + const uint8_t* qb = reinterpret_cast(&q4); + __half* o = sw + r * LDW + blk * 64; +#pragma unroll + for (int c = 0; c < 16; ++c) { + const int v = qb[c]; + *reinterpret_cast<__half2*>(o + 4 * c) = __floats2half2_rn(d * (float) ((v & 3) - 1), d * (float) (((v >> 2) & 3) - 1)); + *reinterpret_cast<__half2*>(o + 4 * c + 2) = __floats2half2_rn(d * (float) (((v >> 4) & 3) - 1), d * (float) (((v >> 6) & 3) - 1)); + } + } +#pragma unroll + for (int t = 0; t < WG_MT; ++t) { + if (t >= nmt) break; +#pragma unroll 1 + for (int xh = 0; xh < WK / WG_XK; ++xh, ++it) { + __syncthreads(); // the previous X tile is consumed (and W is written) +#pragma unroll + for (int q = 0; q < XQ; ++q) { + const int i = tid + q * WG_THREADS, r = i / (WG_XK / 8), c = (i % (WG_XK / 8)) * 8; + *reinterpret_cast(sx + r * LDX + c) = xr[q]; + } + __syncthreads(); + if (it + 1 < total) load_x(it + 1); +#pragma unroll + for (int kk = 0; kk < WG_XK; kk += 16) { + wmma::fragment a[2]; + wmma::fragment b[2]; +#pragma unroll + for (int f = 0; f < 2; ++f) { + wmma::load_matrix_sync(a[f], sx + (wm * 32 + f * 16) * LDX + kk, LDX); + wmma::load_matrix_sync(b[f], sw + (wn * 32 + f * 16) * LDW + xh * WG_XK + kk, LDW); + } +#pragma unroll + for (int fa = 0; fa < 2; ++fa) +#pragma unroll + for (int fb = 0; fb < 2; ++fb) wmma::mma_sync(acc[t][fa][fb], a[fa], b[fb], acc[t][fa][fb]); + } + } + } + __syncthreads(); // W is consumed before the next superblock + } + float* so = reinterpret_cast(wg_smem); // [BM][BN + 4] per m-tile + constexpr int LDO = WG_BN + 4; +#pragma unroll + for (int t = 0; t < WG_MT; ++t) { + if (t >= nmt) break; + const int rows = min(WG_BM, crow - t * WG_BM); +#pragma unroll + for (int fa = 0; fa < 2; ++fa) +#pragma unroll + for (int fb = 0; fb < 2; ++fb) + wmma::store_matrix_sync(so + (wm * 32 + fa * 16) * LDO + wn * 32 + fb * 16, acc[t][fa][fb], LDO, wmma::mem_row_major); + __syncthreads(); + for (int i = tid; i < rows * (WG_BN / 4); i += WG_THREADS) { + const int r = i / (WG_BN / 4), c = (i % (WG_BN / 4)) * 4; + *reinterpret_cast(Y + (size_t) (c0 + t * WG_BM + r) * ldy + n0 + c) = *reinterpret_cast(so + r * LDO + c); + } + __syncthreads(); + } +} +} // namespace + +bool gemm_iq_f16_grouped(int ty, const void* W, size_t expert_bytes, int n_out, int K, const void* X, int ldx, + const int32_t* bounds, int n_experts, int max_rows, float* Y, int ldy, void* stream) { + if (n_out % WG_BN != 0 || n_experts <= 0 || max_rows <= 0 || ldy % 4 != 0) return false; + const bool q20 = ty == 42; + if (q20 ? K % 128 != 0 : (K % 256 != 0 || !is_iq(ty))) return false; + const size_t row_bytes = iq_row_bytes(ty, K); + const int mt = (max_rows + WG_MT * WG_BM - 1) / (WG_MT * WG_BM); // row chunks per expert + const dim3 grid((unsigned) (n_out / WG_BN), (unsigned) (n_experts * mt)); + cudaStream_t s = (cudaStream_t) stream; + auto smem = [](int wk) { return (size_t) WG_BN * (wk + 8) * 2 + (size_t) WG_BM * (WG_XK + 8) * 2; }; + static bool attr = false; + if (!attr) { + cudaFuncSetAttribute(gemm_iq_f16_grouped_kernel<256, false>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem(256)); + cudaFuncSetAttribute(gemm_iq_f16_grouped_kernel<128, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem(128)); + attr = true; + } + if (q20) + gemm_iq_f16_grouped_kernel<128, true><<>>(ty, (const uint8_t*) W, expert_bytes, row_bytes, K, + (const __half*) X, ldx, bounds, mt, Y, ldy); + else + gemm_iq_f16_grouped_kernel<256, false><<>>(ty, (const uint8_t*) W, expert_bytes, row_bytes, K, + (const __half*) X, ldx, bounds, mt, Y, ldy); + return cudaGetLastError() == cudaSuccess; +} +} // namespace strata::kernels +#else +namespace strata::kernels { +bool gemm_iq_f16_grouped(int, const void*, size_t, int, int, const void*, int, const int32_t*, int, int, float*, int, void*) { + return false; +} +} // namespace strata::kernels +#endif diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index c031ee08..435cac68 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -1681,6 +1681,17 @@ __global__ void swiglu_il_kernel(const float* __restrict__ gu, uint16_t* __restr const float g = gu[r * 1280 + 2 * k], u = gu[r * 1280 + 2 * k + 1]; h16[i] = hf_sat(g / (1.0f + __expf(-g)) * u); } +// The Volta prompt experts (gemm_iq_f16_grouped): SwiGLU of the gate/up product's rows (gate 0..n_ff, up n_ff..2 n_ff, +// or interleaved) to the FP16 input of the down product, saturated as swiglu_il_kernel +__global__ void swiglu_split_f16_kernel(const float* __restrict__ gu, uint16_t* __restrict__ h16, int64_t rows, int n_ff, + bool interleaved) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= rows * n_ff) return; + const int64_t r = i / n_ff, k = i % n_ff; + const float* row = gu + r * 2 * n_ff; + const float g = interleaved ? row[2 * k] : row[k], u = interleaved ? row[2 * k + 1] : row[n_ff + k]; + h16[i] = hf_sat(g / (1.0f + __expf(-g)) * u); +} __global__ void swiglu_pair_kernel(const float* __restrict__ g, const float* __restrict__ u, uint16_t* __restrict__ h16, int64_t n) { const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; @@ -2194,6 +2205,11 @@ void swiglu_interleaved(const float* gu, uint16_t* h16, int64_t n, void* stream) swiglu_il_kernel<<>>(gu, h16, n); check("swiglu_interleaved"); } +void swiglu_split_f16(const float* gu, uint16_t* h16, int64_t rows, int n_ff, bool interleaved, void* stream) { + if (rows <= 0) return; + swiglu_split_f16_kernel<<>>(gu, h16, rows, n_ff, interleaved); + check("swiglu_split_f16"); +} void swiglu_pair(const float* g, const float* u, uint16_t* h16, int64_t n, void* stream) { swiglu_pair_kernel<<>>(g, u, h16, n); check("swiglu_pair"); diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 2fa71c7c..749f1c59 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -1005,10 +1005,30 @@ constexpr size_t MMQ_TAIL = 4096; struct MmqPlan { bool any = false, fallback = true; std::vector layer; // per layer: MMQ + std::vector wmma_only; // per layer: in the MMQ grouping for the WMMA tiles only (pf_wmma: IQ1_M) 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; }; +// Volta (sm_70): MMQ runs on dp4a there (no int8 tensor cores). pf_wmma(): the layers MMQ would take, and the IQ1_M +// ones the FP16 path would, run as one launch per expert group on FP16 tensor-core tiles instead +// (strata::kernels::gemm_iq_f16_grouped: each weight superblock dequantized once into shared memory by the FP16 path's +// own formulas, FP16 activations, FP32 sums). STRATA_PF_WMMA=0 / 1: off / on on any CUDA card. +bool pf_wmma() { +#if defined(__HIPCC__) + return false; +#else + static const bool on = [] { + if (const char* e = std::getenv("STRATA_PF_WMMA")) return e[0] == '1'; + int dev = 0, major = 0, minor = 0; + if (cudaGetDevice(&dev) != cudaSuccess) return false; + cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev); + cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev); + return major == 7 && minor == 0; + }(); + return on; +#endif +} const MmqPlan& mmq_plan() { static const MmqPlan plan = [] { MmqPlan p; @@ -1018,11 +1038,21 @@ const MmqPlan& mmq_plan() { 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.wmma_only.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)) { + // pf_wmma: a format dq_dispatch takes (IQ1_M) rides the MMQ grouping, computed by the WMMA tiles only + if (pf_wmma() && lay.native && dt == 42 && strata::kernels::iq_row_bytes(gt, N) > 0) { + p.layer[(size_t) l] = 1; + p.wmma_only[(size_t) l] = 1; + p.any = true; + p.gu_max = std::max(p.gu_max, mmq::matrix_bytes(gt, 1280, N)); + p.d_max = std::max(p.d_max, mmq::matrix_bytes(dt, N, 640)); + continue; + } 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; } @@ -1037,6 +1067,8 @@ const MmqPlan& mmq_plan() { }(); return plan; } +// the FP16 buffers (Xs, Hh): the FP16 path's, or pf_wmma's activations and down input +bool fp16_bufs(const MmqPlan& mp) { return mp.fallback || pf_wmma(); } // #136 P3: a layout whose chunks run the fused experts (STRATA_PF_FUSED=1, the Q2_0 pack, a streamed chunk of // stream_all_min() tokens or more). Its GU, H and Xq hold only the fused path's grouping tables, int8 H and per-token // int8 activations, and Hq nothing: ~100 KB a token less than MMQ's FP32 GU / H and per-slot q8_1 rows, which is what @@ -1063,9 +1095,9 @@ uint64_t moe_set_bytes(size_t T, int64_t n_expert, bool fused) { Alloc a; a.count_only = true; bool ok = true; a.take(T * n_expert, ok); a.take(T * K, ok); a.take(T * K, ok); a.take(T * K, ok); a.take(T * K, ok); - if (mp.fallback) a.take(T * K * N, ok); + if (fp16_bufs(mp)) a.take(T * K * N, ok); a.take(mb.gu, ok); - if (mp.fallback) a.take(T * K * 640, ok); + if (fp16_bufs(mp)) a.take(T * K * 640, ok); a.take(T * K * N, ok); a.take(T * 640, ok); a.take(T * 640, ok); a.take(T * 640, ok); a.take(T * N, ok); a.take(T, ok); if (mp.any) { @@ -1288,9 +1320,9 @@ bool Prefill::carve(size_t T, void* alloc) { m.logits = c.take(T * m.g->n_expert, ok); m.w = c.take(T * K, ok); m.ids = c.take(T * K, ok); m.slot_dev = c.take(T * K, ok); m.src_dev = c.take(T * K, ok); const MmqPlan& mp = mmq_plan(); - m.Xs = mp.fallback ? c.take(T * K * N, ok) : nullptr; + m.Xs = fp16_bufs(mp) ? c.take(T * K * N, ok) : nullptr; m.GU = c.take(mb.gu, ok); - m.Hh = mp.fallback ? c.take(T * K * 640, ok) : nullptr; + m.Hh = fp16_bufs(mp) ? c.take(T * K * 640, ok) : nullptr; m.Dm = c.take(T * K * N, ok); m.sgate = c.take(T * 640, ok); m.sup = c.take(T * 640, ok); m.sh_h = c.take(T * 640, ok); m.shared = c.take(T * N, ok); m.sg = c.take(T, ok); @@ -3449,12 +3481,20 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri return true; }); } + // pf_wmma: this layer's groups on the FP16 tensor-core tiles (single GPU, native pack, Q2_0 down) + const bool wmma_l = use_mmq && pf_wmma() && !fused_l && on_peer.empty() && lay.native && + mmq_dt == 42 && strata::kernels::iq_row_bytes(mmq_gt, N) > 0; + if (use_mmq && mmq_plan().wmma_only[(size_t) l] && !wmma_l) { + err = "prefill: an IQ1_M layer in the MMQ grouping needs the WMMA tiles, which this chunk cannot take"; + return false; + } 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; pt.mark(kPfGather, cs); if (use_mmq) { // step 2b: the layer's activations as q8_1 rows in expert order, straight from `mixed` - mmq::quantize(m.mixed, m.src_dev, m.Xq, mmq_gt, N, N, T * K, m.cs, m.Xscale); + if (wmma_l) gather_rows16(m.mixed_h, m.src_dev, m.Xs, T * K, N, m.cs); // FP16 rows + else mmq::quantize(m.mixed, m.src_dev, m.Xq, mmq_gt, N, N, T * K, m.cs, m.Xscale); // each group's rows: absolute bounds (gate/up reads the layer's rows), relative ones (down // reads the group's own quantized H) const size_t n = order.size(), ng = (n + MMQ_GROUP - 1) / MMQ_GROUP; @@ -3905,6 +3945,19 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri int64_t maxr = 0; for (size_t i = j0; i <= j; ++i) maxr = std::max(maxr, m.cnt[(size_t) order[i]]); pt.mark(kPfGemmGU, cs); + if (wmma_l) { // pf_wmma: gate/up, SwiGLU to FP16, down - the group in 2 tile launches + const int32_t* dnb = m.bounds_dev + n + 1 + g * (MMQ_GROUP + 1); + const bool ok1 = strata::kernels::gemm_iq_f16_grouped( + mmq_gt, m.grp_gu, mmq_gub, 1280, (int) N, m.Xs, (int) N, m.bounds_dev + j0, ngx, + (int) maxr, m.GU, 1280, m.cs); + swiglu_split_f16(m.GU + r0 * 1280, m.Hh + r0 * 640, nr, 640, !lay.native, m.cs); + pt.mark(kPfGemmD, cs); + const bool ok2 = strata::kernels::gemm_iq_f16_grouped( + mmq_dt, m.grp_d, mmq_db, (int) N, 640, m.Hh + r0 * 640, 640, dnb, ngx, (int) maxr, + m.Dm + r0 * N, (int) N, m.cs); + if (!ok1 || !ok2) { err = "prefill: the WMMA expert tiles could not launch"; return false; } + return true; + } mmq::Product gu; gu.w = m.grp_gu; gu.type = mmq_gt; gu.w_rows = 1280; gu.w_cols = N; gu.expert_bytes = mmq_gub; gu.n = ngx; gu.xq = m.Xq; gu.bounds = m.bounds_dev + j0; gu.ids = m.ids_identity; From fb433c3a5779545f1597fbb72d0600586dda8558 Mon Sep 17 00:00:00 2001 From: NoxestNoz Date: Wed, 7 Oct 2026 21:26:05 +0000 Subject: [PATCH 10/36] pf_wmma_parity: gemm_iq_f16_grouped against a double reference over the FP16 path's weights --- CMakeLists.txt | 8 ++ src/kernels/pf_wmma_parity.cpp | 150 +++++++++++++++++++++++++++++++++ 2 files changed, 158 insertions(+) create mode 100644 src/kernels/pf_wmma_parity.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 4f72e459..4545bcc5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -891,6 +891,14 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_include_directories(native_grouped_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(native_grouped_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME native_grouped_parity COMMAND native_grouped_parity) + if(STRATA_ENABLE_CUDA) + # the Volta prompt experts (gemm_iq_f16_grouped, STRATA_PF_WMMA) against a double reference; skipped below sm_70 + add_executable(pf_wmma_parity src/kernels/pf_wmma_parity.cpp) + target_include_directories(pf_wmma_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(pf_wmma_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME pf_wmma_parity COMMAND pf_wmma_parity) + set_tests_properties(pf_wmma_parity PROPERTIES SKIP_RETURN_CODE 77) + endif() add_executable(shared_expert_parity src/kernels/shared_expert_parity.cpp) target_include_directories(shared_expert_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(shared_expert_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) diff --git a/src/kernels/pf_wmma_parity.cpp b/src/kernels/pf_wmma_parity.cpp new file mode 100644 index 00000000..d28b4d2f --- /dev/null +++ b/src/kernels/pf_wmma_parity.cpp @@ -0,0 +1,150 @@ +// src/kernels/pf_wmma_parity.cpp - gemm_iq_f16_grouped (the Volta prompt experts, STRATA_PF_WMMA) against a double +// reference over the same FP16 weights (iq_dequant_f16, the FP16 path's dequantization) and FP16 activations. +// +// build/pf_wmma_parity (needs a CUDA GPU with FP16 tensor cores: sm_70+; synthetic blobs, no model) +// +// Every gate/up format the prompt path gives it (IQ2_XXS, IQ2_S, IQ1_M: 1280 rows of 2560) and the Q2_0 down product +// (2560 rows of 640); a group of experts with 0, 1, 63, 64, 65, 200 and 300 rows (one past the 256-row chunk); the rows +// placed past a nonzero first bound. The sums are FP32 on tensor cores in another order than the reference, so the +// check is a tolerance: max |got - ref| <= 2e-3 * (max |ref| of the matrix) + 1e-6. +#include "strata/kernels/iq_kernels.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace k = strata::kernels; + +namespace { + +void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "CUDA error in %s: %s\n", what, cudaGetErrorString(e)); + std::exit(2); + } +} + +const char* name_of(int t) { + switch (t) { + case 16: return "IQ2_XXS"; + case 17: return "IQ2_XS"; + case 18: return "IQ3_XXS"; + case 20: return "IQ4_NL"; + case 21: return "IQ3_S"; + case 22: return "IQ2_S"; + case 23: return "IQ4_XS"; + case 29: return "IQ1_M"; + case 42: return "Q2_0"; + case 12: return "Q4_K"; + case 13: return "Q5_K"; + case 14: return "Q6_K"; + case 7: return "Q5_1"; + case 8: return "Q8_0"; + default: return "?"; + } +} +int block_values(int t) { return t == 20 || t == 7 || t == 8 ? 32 : t == 42 ? 64 : 256; } + +// `rows` rows of `n` values of format t: random bytes, then a finite fp16 scale in every block +std::vector random_rows(int t, int64_t rows, int64_t n, std::mt19937& rng) { + const size_t rb = k::iq_row_bytes(t, n), bs = k::iq_row_bytes(t, block_values(t)); + std::vector w((size_t) rows * rb); + std::uniform_int_distribution byte(0, 255), ex(2, 8), man(0, 1023), sgn(0, 1); + for (auto& b : w) b = (uint8_t) byte(rng); + for (size_t o = 0; o < w.size(); o += bs) { + if (t == 29) { + // IQ1_M: the fp16 scale is the top nibbles of its four scale words (bytes 48..55), the sign and the + // exponent's top bits in the last: 0x1 / 0x2 there (0x9 / 0xA negative) keeps it in 2^-11 .. 2^-3 + const uint8_t nib = (uint8_t) ((sgn(rng) ? 0x8 : 0x0) | (1 + (byte(rng) & 1))); + w[o + 55] = (uint8_t) ((w[o + 55] & 0x0F) | (nib << 4)); + } else { // the other formats start their block with the fp16 scale: 2^-13 .. 2^-6 + // (Q4_K / Q5_K: 2^-14 .. 2^-11, their 6-bit sub-scales multiply it by up to 63) + const int e = (t == 12 || t == 13) ? 1 + ex(rng) % 4 : ex(rng); + const uint16_t h = (uint16_t) ((sgn(rng) ? 0x8000 : 0) | (e << 10) | man(rng)); + std::memcpy(&w[o], &h, 2); + if (t == 12 || t == 13 || t == 7) { // Q4_K / Q5_K: dmin, Q5_1: m - the second fp16, as small + const int em = (t == 7) ? ex(rng) : 1 + ex(rng) % 4; + const uint16_t m = (uint16_t) ((sgn(rng) ? 0x8000 : 0) | (em << 10) | man(rng)); + std::memcpy(&w[o + 2], &m, 2); + } + } + } + return w; +} + + +int run(int ty, int n_out, int K, std::mt19937& rng) { + const std::vector rows = {0, 1, 63, 64, 65, 200, 300}; + const int E = (int) rows.size(), base = 5; + std::vector bounds(E + 1); + bounds[0] = base; + for (int e = 0; e < E; ++e) bounds[e + 1] = bounds[e] + rows[e]; + const int total = bounds[E]; + const size_t eb = k::iq_row_bytes(ty, K) * (size_t) n_out; + std::vector w; + for (int e = 0; e < E; ++e) { auto r = random_rows(ty, n_out, K, rng); w.insert(w.end(), r.begin(), r.end()); } + std::normal_distribution nd(0.f, 1.f); + std::vector<__half> x((size_t) total * K); + for (auto& v : x) v = __float2half(nd(rng)); + uint8_t* dw; __half* dx; int32_t* db; float* dy; uint16_t* dq; + ck(cudaMalloc(&dw, w.size() + 4096), "w"); + ck(cudaMemcpy(dw, w.data(), w.size(), cudaMemcpyHostToDevice), "w"); + ck(cudaMalloc(&dx, x.size() * 2), "x"); + ck(cudaMemcpy(dx, x.data(), x.size() * 2, cudaMemcpyHostToDevice), "x"); + ck(cudaMalloc(&db, bounds.size() * 4), "b"); + ck(cudaMemcpy(db, bounds.data(), bounds.size() * 4, cudaMemcpyHostToDevice), "b"); + ck(cudaMalloc(&dy, (size_t) total * n_out * 4), "y"); + ck(cudaMemset(dy, 0xff, (size_t) total * n_out * 4), "y"); + ck(cudaMalloc(&dq, (size_t) E * n_out * K * 2), "dq"); + const int maxr = *std::max_element(rows.begin(), rows.end()); + if (!k::gemm_iq_f16_grouped(ty, dw, eb, n_out, K, dx, K, db, E, maxr, dy, n_out, nullptr)) { + std::printf("%-8s %5d x %4d: not launched\n", name_of(ty), n_out, K); + return 1; + } + for (int e = 0; e < E; ++e) k::iq_dequant_f16(ty, dw + e * eb, (int64_t) n_out * K, dq + (size_t) e * n_out * K, nullptr); + ck(cudaDeviceSynchronize(), "run"); + std::vector y((size_t) total * n_out); + std::vector q((size_t) E * n_out * K); + ck(cudaMemcpy(y.data(), dy, y.size() * 4, cudaMemcpyDeviceToHost), "y"); + ck(cudaMemcpy(q.data(), dq, q.size() * 2, cudaMemcpyDeviceToHost), "dq"); + double worst = 0, scale = 0; + for (int e = 0; e < E; ++e) + for (int r = bounds[e]; r < bounds[e + 1]; ++r) + for (int n = 0; n < n_out; ++n) { + double s = 0; + const uint16_t* wr = &q[((size_t) e * n_out + n) * K]; + for (int kk = 0; kk < K; ++kk) { + __half h; std::memcpy(&h, &wr[kk], 2); + s += (double) __half2float(h) * (double) __half2float(x[(size_t) r * K + kk]); + } + scale = std::max(scale, std::fabs(s)); + worst = std::max(worst, std::fabs(s - (double) y[(size_t) r * n_out + n])); + } + const bool ok = worst <= 2e-3 * scale + 1e-6; + std::printf("%-8s %5d x %4d, %d rows in %d experts: max |err| %.3g of max |ref| %.3g %s\n", name_of(ty), n_out, K, + total - base, E, worst, scale, ok ? "ok" : "FAIL"); + cudaFree(dw); cudaFree(dx); cudaFree(db); cudaFree(dy); cudaFree(dq); + return ok ? 0 : 1; +} + +} // namespace + +int main() { + int dev = 0, major = 0; + cudaGetDevice(&dev); + cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev); + if (major < 7) { std::printf("pf_wmma_parity: needs sm_70+, skipped\n"); return 77; } + std::mt19937 rng(70); + int fails = 0; + for (int ty : {16, 22, 29}) fails += run(ty, 1280, 2560, rng); + fails += run(42, 2560, 640, rng); + std::printf("pf_wmma_parity: %d failures\n", fails); + return fails ? 1 : 0; +} From 140f011030e4854b24acfc49dd9694cea90ee70f Mon Sep 17 00:00:00 2001 From: NoxestNoz Date: Wed, 7 Oct 2026 21:46:35 +0000 Subject: [PATCH 11/36] bench/results: V100 prompt experts on FP16 tensor cores (+9.6% / +10.3% prompt speed); docs/NVIDIA_V100.md --- .../2026-10-07-v100-prompt-experts/README.md | 70 ++++++++++++++++++ .../ab-runs.jsonl | 72 +++++++++++++++++++ docs/NVIDIA_V100.md | 2 +- 3 files changed, 143 insertions(+), 1 deletion(-) create mode 100644 bench/results/2026-10-07-v100-prompt-experts/README.md create mode 100644 bench/results/2026-10-07-v100-prompt-experts/ab-runs.jsonl diff --git a/bench/results/2026-10-07-v100-prompt-experts/README.md b/bench/results/2026-10-07-v100-prompt-experts/README.md new file mode 100644 index 00000000..7be73e1b --- /dev/null +++ b/bench/results/2026-10-07-v100-prompt-experts/README.md @@ -0,0 +1,70 @@ +# V100 (sm_70): the prompt's experts on FP16 tensor cores (2026-10-07) + +On sm_70 the prompt path ran the routed experts on llama.cpp's MMQ, whose integer products are `dp4a` there (Volta has +no int8 tensor cores), and IQ1_M layers on the FP16 path (each expert dequantized to global memory, then one cuBLAS +call per product). `gemm_iq_f16_grouped` (`src/kernels/cuda/iq_kernels.cu`) runs a whole MMQ expert group per launch on +the FP16 tensor cores (WMMA, FP32 sums): a block takes 128 weight rows of one expert and up to 256 of its token rows, +dequantizes each weight superblock once into shared memory with `dq_dispatch` (the FP16 path's own formulas), and +streams the FP16 activations through it, the next tile prefetched into registers. sm_70 takes it by default for the +layers MMQ would take and for IQ1_M (which then rides MMQ's grouping); `STRATA_PF_WMMA=0` is the old path, +`STRATA_PF_WMMA=1` turns it on for any CUDA card (not measured elsewhere). + +## Rig + +As in [2026-10-07-v100-decode-kernels](../2026-10-07-v100-decode-kernels/README.md): V100-SXM2-32GB (PCIe gen3 x16), +2x Xeon Gold 6130 in a container with a ~15-CPU quota, CUDA 12.8; setup's IQ2_XS (gate/up IQ2_S on 34 layers, IQ2_XXS +on 11, IQ1_M on 3; down Q2_0), setup's config (`--prefill auto`: 8,192-token chunks here) plus `--pool-workers 14`. + +## Prompt speed + +`tools/ab_engine.py`, 3 rounds, the arms' order alternating, one server start per arm and round; the server's own +prompt tokens/s. `orig`: `e8ca9af` as setup built it; `off`: this branch with `STRATA_PF_WMMA=0`; `new`: this branch. + +| Prompt | orig | off | new | new vs orig | +| --- | ---: | ---: | ---: | ---: | +| 26,359 tokens (median of 3) | 1,467 tok/s | 1,462 | 1,608 | **+9.6%** | +| 6,345 tokens (median of 3) | 1,390 tok/s | 1,393 | 1,534 | **+10.3%** | + +All runs: `ab-runs.jsonl` (the spread between rounds is under 1%). The engine's phase table +(`STRATA_PREFILL_TIMING=1`, the 26,352-token prompt, ms): + +| | orig | new | +| --- | ---: | ---: | +| experts gate/up | 3,913 | 3,670 | +| experts down | 2,229 | 1,212 | +| dequant (the IQ1_M layers' FP16 path, and the rest of that phase) | 740 | 575 | +| GPU timeline | 17,391 | 15,847 | + +Decode does not use this path (decode tok/s in the same runs: within the noise). + +## Accuracy + +- `pf_wmma_parity` (synthetic, no model): every format it takes (IQ2_XXS, IQ2_S, IQ1_M gate/up, 1280 x 2560; Q2_0 down, + 2560 x 640), 7 experts with 0-300 rows, against a double-precision product of the same FP16 weights and activations: + max error 4.4e-4 to 5.2e-4 of outputs up to ~110 (Q2_0: 2.8e-6 of 1.16) - FP32 summation order. +- **Teacher-forced** (`STRATA_LOGPOS` with `STRATA_LOGPOS_TOPK=20`; a long random-word prompt read by the batched path, + then a continuation read through the decode windows with `--short-read 1024`, each token's log-probability against + the text). MMQ is not a reference either - its activations are q8_1, these are FP16 - so the table puts the change + next to what MMQ alone does when only the chunk size changes: + +| Continuation (after) | Compared | argmax agreement | KL (top 20) | perplexity | +| --- | --- | ---: | ---: | --- | +| 363 tokens of prose (26,359-token prompt) | MMQ vs this | 98.3% | 0.0083 | 50.7 / 60.5 | +| | MMQ 8,192 vs 32,768-token chunks | 98.3% | 0.0084 | 50.7 / 50.6 | +| | MMQ 8,192 vs 16,384-token chunks | 93.6% | 0.0177 | 50.7 / 39.2 | +| 327 tokens of Python (12,676-token prompt) | MMQ vs this | 94.5% | 0.0312 | 3.98 / 3.38 | +| | MMQ 8,192 vs 4,096-token chunks | 96.3% | 0.0253 | 3.98 / 3.49 | +| | MMQ 4,096 chunks vs this | 96.3% | 0.0170 | 3.49 / 3.38 | + + Two MMQ runs of the same configuration were bit for bit the same. After a long prompt these continuations move this + much from any change of the prompt path's arithmetic (the perplexities swing both ways); the change sits inside + what the chunk size alone does. Two texts are not a quality benchmark; a run against a full-precision reference + (llama.cpp, as in [UNSLOTH_Q4](../../../docs/UNSLOTH_Q4.md)) was not made. + +## Notes + +- One observation from these runs, not followed up: on the 12,676-token prompt MMQ with `--prefill 4096` read + 1,560 tok/s against 1,370 with `auto` (8,192 here) - a single run each. +- Tried and dropped on the way: the FP16 path for chunks of 16K+ tokens (+10% at `--prefill auto:32768`, but superseded + by this, which also wins at setup's chunk size); a row-per-warp hyper-connection down projection (no gain in the + engine). Groups of 32 experts instead of 16: no gain. diff --git a/bench/results/2026-10-07-v100-prompt-experts/ab-runs.jsonl b/bench/results/2026-10-07-v100-prompt-experts/ab-runs.jsonl new file mode 100644 index 00000000..938d3fab --- /dev/null +++ b/bench/results/2026-10-07-v100-prompt-experts/ab-runs.jsonl @@ -0,0 +1,72 @@ +{"round": 0, "arm": "orig", "req": "chat0", "decode": 84.7, "prompt": 106.9, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "} +{"round": 0, "arm": "orig", "req": "chat1", "decode": 58.8, "prompt": 93.4, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"} +{"round": 0, "arm": "orig", "req": "chat2", "decode": 75.4, "prompt": 103.5, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"} +{"round": 0, "arm": "orig", "req": "long", "decode": 60.9, "prompt": 1469.9, "prompt_n": 26359, "n": 32, "text": "The list consists entirely of single-word nouns that evoke a variety of natural,"} +{"round": 0, "arm": "off", "req": "chat0", "decode": 90.5, "prompt": 110.7, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "} +{"round": 0, "arm": "off", "req": "chat1", "decode": 61.6, "prompt": 95.0, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"} +{"round": 0, "arm": "off", "req": "chat2", "decode": 79.7, "prompt": 106.5, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"} +{"round": 0, "arm": "off", "req": "long", "decode": 63.7, "prompt": 1458.4, "prompt_n": 26359, "n": 32, "text": "The list consists entirely of single-word nouns that evoke a variety of natural,"} +{"round": 0, "arm": "new", "req": "chat0", "decode": 90.7, "prompt": 110.6, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "} +{"round": 0, "arm": "new", "req": "chat1", "decode": 61.6, "prompt": 95.2, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"} +{"round": 0, "arm": "new", "req": "chat2", "decode": 79.7, "prompt": 107.1, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"} +{"round": 0, "arm": "new", "req": "long", "decode": 61.6, "prompt": 1608.4, "prompt_n": 26359, "n": 32, "text": "The list consists entirely of single-word nouns that evoke a variety of natural,"} +{"round": 1, "arm": "new", "req": "chat0", "decode": 89.8, "prompt": 110.6, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "} +{"round": 1, "arm": "new", "req": "chat1", "decode": 61.2, "prompt": 94.0, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"} +{"round": 1, "arm": "new", "req": "chat2", "decode": 79.1, "prompt": 107.1, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"} +{"round": 1, "arm": "new", "req": "long", "decode": 61.0, "prompt": 1607.2, "prompt_n": 26359, "n": 32, "text": "The list consists entirely of single-word nouns that evoke a variety of natural,"} +{"round": 1, "arm": "off", "req": "chat0", "decode": 90.8, "prompt": 110.9, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "} +{"round": 1, "arm": "off", "req": "chat1", "decode": 61.5, "prompt": 95.5, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"} +{"round": 1, "arm": "off", "req": "chat2", "decode": 79.8, "prompt": 107.0, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"} +{"round": 1, "arm": "off", "req": "long", "decode": 63.8, "prompt": 1473.8, "prompt_n": 26359, "n": 32, "text": "The list consists entirely of single-word nouns that evoke a variety of natural,"} +{"round": 1, "arm": "orig", "req": "chat0", "decode": 84.9, "prompt": 106.6, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "} +{"round": 1, "arm": "orig", "req": "chat1", "decode": 58.9, "prompt": 92.9, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"} +{"round": 1, "arm": "orig", "req": "chat2", "decode": 75.5, "prompt": 103.6, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"} +{"round": 1, "arm": "orig", "req": "long", "decode": 61.0, "prompt": 1467.3, "prompt_n": 26359, "n": 32, "text": "The list consists entirely of single-word nouns that evoke a variety of natural,"} +{"round": 2, "arm": "orig", "req": "chat0", "decode": 84.0, "prompt": 106.8, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "} +{"round": 2, "arm": "orig", "req": "chat1", "decode": 58.8, "prompt": 93.2, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"} +{"round": 2, "arm": "orig", "req": "chat2", "decode": 75.5, "prompt": 103.7, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"} +{"round": 2, "arm": "orig", "req": "long", "decode": 60.7, "prompt": 1458.4, "prompt_n": 26359, "n": 32, "text": "The list consists entirely of single-word nouns that evoke a variety of natural,"} +{"round": 2, "arm": "off", "req": "chat0", "decode": 90.5, "prompt": 110.4, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "} +{"round": 2, "arm": "off", "req": "chat1", "decode": 61.5, "prompt": 95.1, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"} +{"round": 2, "arm": "off", "req": "chat2", "decode": 79.7, "prompt": 107.2, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"} +{"round": 2, "arm": "off", "req": "long", "decode": 63.4, "prompt": 1462.2, "prompt_n": 26359, "n": 32, "text": "The list consists entirely of single-word nouns that evoke a variety of natural,"} +{"round": 2, "arm": "new", "req": "chat0", "decode": 90.7, "prompt": 109.7, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "} +{"round": 2, "arm": "new", "req": "chat1", "decode": 61.6, "prompt": 95.2, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"} +{"round": 2, "arm": "new", "req": "chat2", "decode": 79.8, "prompt": 106.8, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"} +{"round": 2, "arm": "new", "req": "long", "decode": 61.9, "prompt": 1608.2, "prompt_n": 26359, "n": 32, "text": "The list consists entirely of single-word nouns that evoke a variety of natural,"} +{"round": 0, "arm": "orig", "req": "chat0", "decode": 85.0, "prompt": 106.9, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "} +{"round": 0, "arm": "orig", "req": "chat1", "decode": 58.5, "prompt": 93.2, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"} +{"round": 0, "arm": "orig", "req": "chat2", "decode": 75.6, "prompt": 103.9, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"} +{"round": 0, "arm": "orig", "req": "long", "decode": 69.1, "prompt": 1390.1, "prompt_n": 6345, "n": 32, "text": "The list consists entirely of single, lowercase English words that appear to be "} +{"round": 0, "arm": "off", "req": "chat0", "decode": 89.8, "prompt": 110.8, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "} +{"round": 0, "arm": "off", "req": "chat1", "decode": 61.6, "prompt": 94.2, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"} +{"round": 0, "arm": "off", "req": "chat2", "decode": 79.8, "prompt": 105.2, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"} +{"round": 0, "arm": "off", "req": "long", "decode": 72.9, "prompt": 1392.7, "prompt_n": 6345, "n": 32, "text": "The list consists entirely of single, lowercase English words that appear to be "} +{"round": 0, "arm": "new", "req": "chat0", "decode": 70.1, "prompt": 102.0, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "} +{"round": 0, "arm": "new", "req": "chat1", "decode": 48.3, "prompt": 80.6, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"} +{"round": 0, "arm": "new", "req": "chat2", "decode": 56.1, "prompt": 90.1, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"} +{"round": 0, "arm": "new", "req": "long", "decode": 57.9, "prompt": 1533.9, "prompt_n": 6345, "n": 32, "text": "The list consists entirely of single, lowercase English nouns that appear to be "} +{"round": 1, "arm": "new", "req": "chat0", "decode": 90.5, "prompt": 110.6, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "} +{"round": 1, "arm": "new", "req": "chat1", "decode": 61.1, "prompt": 95.4, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"} +{"round": 1, "arm": "new", "req": "chat2", "decode": 79.6, "prompt": 106.9, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"} +{"round": 1, "arm": "new", "req": "long", "decode": 74.9, "prompt": 1534.9, "prompt_n": 6345, "n": 32, "text": "The list consists entirely of single, lowercase English nouns that appear to be "} +{"round": 1, "arm": "off", "req": "chat0", "decode": 54.9, "prompt": 92.0, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "} +{"round": 1, "arm": "off", "req": "chat1", "decode": 41.8, "prompt": 69.1, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"} +{"round": 1, "arm": "off", "req": "chat2", "decode": 48.9, "prompt": 79.0, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"} +{"round": 1, "arm": "off", "req": "long", "decode": 49.3, "prompt": 1387.5, "prompt_n": 6345, "n": 32, "text": "The list consists entirely of single, lowercase English words that appear to be "} +{"round": 1, "arm": "orig", "req": "chat0", "decode": 65.2, "prompt": 99.3, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "} +{"round": 1, "arm": "orig", "req": "chat1", "decode": 45.7, "prompt": 76.8, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"} +{"round": 1, "arm": "orig", "req": "chat2", "decode": 53.8, "prompt": 86.3, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"} +{"round": 1, "arm": "orig", "req": "long", "decode": 51.6, "prompt": 1380.8, "prompt_n": 6345, "n": 32, "text": "The list consists entirely of single, lowercase English words that appear to be "} +{"round": 2, "arm": "orig", "req": "chat0", "decode": 65.4, "prompt": 99.2, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "} +{"round": 2, "arm": "orig", "req": "chat1", "decode": 46.8, "prompt": 78.5, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"} +{"round": 2, "arm": "orig", "req": "chat2", "decode": 54.6, "prompt": 87.3, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"} +{"round": 2, "arm": "orig", "req": "long", "decode": 51.0, "prompt": 1392.7, "prompt_n": 6345, "n": 32, "text": "The list consists entirely of single, lowercase English words that appear to be "} +{"round": 2, "arm": "off", "req": "chat0", "decode": 77.5, "prompt": 107.6, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "} +{"round": 2, "arm": "off", "req": "chat1", "decode": 51.7, "prompt": 86.6, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"} +{"round": 2, "arm": "off", "req": "chat2", "decode": 61.0, "prompt": 94.8, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"} +{"round": 2, "arm": "off", "req": "long", "decode": 55.5, "prompt": 1397.5, "prompt_n": 6345, "n": 32, "text": "The list consists entirely of single, lowercase English words that appear to be "} +{"round": 2, "arm": "new", "req": "chat0", "decode": 78.1, "prompt": 107.7, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "} +{"round": 2, "arm": "new", "req": "chat1", "decode": 52.4, "prompt": 87.4, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"} +{"round": 2, "arm": "new", "req": "chat2", "decode": 61.9, "prompt": 96.5, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"} +{"round": 2, "arm": "new", "req": "long", "decode": 59.7, "prompt": 1532.3, "prompt_n": 6345, "n": 32, "text": "The list consists entirely of single, lowercase English nouns that appear to be "} diff --git a/docs/NVIDIA_V100.md b/docs/NVIDIA_V100.md index 15514a8b..4a504227 100644 --- a/docs/NVIDIA_V100.md +++ b/docs/NVIDIA_V100.md @@ -27,7 +27,7 @@ select "old" kernels everywhere: which kernel runs is decided per architecture w | Part of the prompt path | On sm_70 | | --- | --- | -| MoE experts (ggml MMQ) | `dp4a` kernels (Volta has no int8 tensor cores) | +| MoE experts | `gemm_iq_f16_grouped`: a group of experts per launch on the FP16 tensor cores, the weights dequantized in shared memory (+10% prompt speed against MMQ's `dp4a` kernels, [bench](../bench/results/2026-10-07-v100-prompt-experts/README.md); `STRATA_PF_WMMA=0`: MMQ) | | Dense projections (dequantized weights) | FP16 tensor-core GEMMs (cuBLAS / CUTLASS `s884`) | | BF16 projections (hyper-connection, router, indexer, ...) | converted to FP16 and run on the FP16 tensor cores (#655, #540; `STRATA_BF16_TC=0`: cuBLAS BF16, an FP32 SIMT kernel on Volta) | | QSA attention for decode and verify windows (and prompts with `STRATA_PROMPT_ATTN_OLD=1`) | #540's kernel (fewer shuffles, bit-exact; `STRATA_ATTN_PRE75=0`: the one other cards run) | From cb73a0538a7f7dbabbe21f0d536c78c3e9224e8c Mon Sep 17 00:00:00 2001 From: g0 Date: Sat, 10 Oct 2026 04:53:52 +0800 Subject: [PATCH 12/36] pf_wmma: IQ4_NL (type 20) WK=128 lane for the down product (K=640); parity cases --- src/kernels/cuda/iq_kernels.cu | 31 ++++++++++++++++++++++++++----- src/kernels/pf_wmma_parity.cpp | 11 +++++++---- 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index cc1ba0f9..47ee1513 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -3833,9 +3833,9 @@ namespace { constexpr int WG_BM = 64, WG_BN = 128, WG_THREADS = 256, WG_XK = 128, WG_MT = 4; // A block: BN = 128 weight rows of one expert x up to WG_MT * BM = 256 of its token rows (blockIdx.y walks an expert's // rows in such chunks), so every weight superblock is dequantized ONCE per chunk into shared memory (WK 256: an IQ -// superblock through dq_dispatch; WK 128: two Q2_0 blocks); the activations stream through a BM x 128 tile. 8 warps -// of 32 x 32 per m-tile (2 x 2 fragments), FP32 accumulators for the chunk's m-tiles in registers. -template +// superblock through dq_dispatch; WK 128: two Q2_0 blocks, or four IQ4_NL blocks); the activations stream through a +// BM x 128 tile. 8 warps of 32 x 32 per m-tile (2 x 2 fragments), FP32 accumulators for the chunk's m-tiles in registers. +template __global__ void __launch_bounds__(WG_THREADS) gemm_iq_f16_grouped_kernel(int ty, const uint8_t* __restrict__ W, size_t expert_bytes, size_t row_bytes, int K, const __half* __restrict__ X, int ldx, @@ -3880,7 +3880,23 @@ __global__ void __launch_bounds__(WG_THREADS) gemm_iq_f16_grouped_kernel(int ty, load_x(0); int it = 0; for (int k0 = 0; k0 < K; k0 += WK) { - if constexpr (!Q20) { + if constexpr (IQNL) { + // IQ4_NL down (WK 128 = 4 x block_iq4_nl): one thread per (row, 64-value half) - the four blocks of the + // 128-value window sit in two halves of two blocks, and each thread's values are exactly dq_iq4_nl's + const int r = tid >> 1, half = tid & 1; + const block_iq4_nl* bp = reinterpret_cast(we + (size_t) (n0 + r) * row_bytes) + k0 / 32 + half * 2; + __half* o = sw + r * LDW + half * 64; +#pragma unroll + for (int bl = 0; bl < 2; ++bl) { + const block_iq4_nl* b = bp + bl; + const float d = (float) b->d; +#pragma unroll + for (int p = 0; p < 16; ++p) { + o[bl * 32 + p] = cvt<__half>(d * kvalues_iq4nl[b->qs[p] & 0xf]); + o[bl * 32 + p + 16] = cvt<__half>(d * kvalues_iq4nl[b->qs[p] >> 4]); + } + } + } else if constexpr (!Q20) { for (int r = warp; r < WG_BN; r += WG_THREADS / 32) dq_dispatch<__half>(ty, we + (size_t) (n0 + r) * row_bytes, k0 / 256, sw + r * LDW, lane); } else { @@ -3954,7 +3970,8 @@ bool gemm_iq_f16_grouped(int ty, const void* W, size_t expert_bytes, int n_out, const int32_t* bounds, int n_experts, int max_rows, float* Y, int ldy, void* stream) { if (n_out % WG_BN != 0 || n_experts <= 0 || max_rows <= 0 || ldy % 4 != 0) return false; const bool q20 = ty == 42; - if (q20 ? K % 128 != 0 : (K % 256 != 0 || !is_iq(ty))) return false; + const bool nl = ty == 20 && K % 256 != 0; // IQ4_NL down (K=640): there is no WK=256 path for this K + if (q20 || nl ? K % 128 != 0 : (K % 256 != 0 || !is_iq(ty))) return false; const size_t row_bytes = iq_row_bytes(ty, K); const int mt = (max_rows + WG_MT * WG_BM - 1) / (WG_MT * WG_BM); // row chunks per expert const dim3 grid((unsigned) (n_out / WG_BN), (unsigned) (n_experts * mt)); @@ -3964,11 +3981,15 @@ bool gemm_iq_f16_grouped(int ty, const void* W, size_t expert_bytes, int n_out, if (!attr) { cudaFuncSetAttribute(gemm_iq_f16_grouped_kernel<256, false>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem(256)); cudaFuncSetAttribute(gemm_iq_f16_grouped_kernel<128, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem(128)); + cudaFuncSetAttribute(gemm_iq_f16_grouped_kernel<128, false, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem(128)); attr = true; } if (q20) gemm_iq_f16_grouped_kernel<128, true><<>>(ty, (const uint8_t*) W, expert_bytes, row_bytes, K, (const __half*) X, ldx, bounds, mt, Y, ldy); + else if (nl) + gemm_iq_f16_grouped_kernel<128, false, true><<>>(ty, (const uint8_t*) W, expert_bytes, row_bytes, K, + (const __half*) X, ldx, bounds, mt, Y, ldy); else gemm_iq_f16_grouped_kernel<256, false><<>>(ty, (const uint8_t*) W, expert_bytes, row_bytes, K, (const __half*) X, ldx, bounds, mt, Y, ldy); diff --git a/src/kernels/pf_wmma_parity.cpp b/src/kernels/pf_wmma_parity.cpp index d28b4d2f..090c37ca 100644 --- a/src/kernels/pf_wmma_parity.cpp +++ b/src/kernels/pf_wmma_parity.cpp @@ -3,10 +3,11 @@ // // build/pf_wmma_parity (needs a CUDA GPU with FP16 tensor cores: sm_70+; synthetic blobs, no model) // -// Every gate/up format the prompt path gives it (IQ2_XXS, IQ2_S, IQ1_M: 1280 rows of 2560) and the Q2_0 down product -// (2560 rows of 640); a group of experts with 0, 1, 63, 64, 65, 200 and 300 rows (one past the 256-row chunk); the rows -// placed past a nonzero first bound. The sums are FP32 on tensor cores in another order than the reference, so the -// check is a tolerance: max |got - ref| <= 2e-3 * (max |ref| of the matrix) + 1e-6. +// Every gate/up format the prompt path gives it (IQ2_XXS, IQ2_S, IQ1_M, and this pack's IQ4_NL / IQ3_S / IQ4_XS: 1280 +// rows of 2560) and the down products (Q2_0, and IQ4_NL: 2560 rows of 640); a group of experts with 0, 1, 63, 64, 65, +// 200 and 300 rows (one past the 256-row chunk); the rows placed past a nonzero first bound. The sums are FP32 on +// tensor cores in another order than the reference, so the check is a tolerance: max |got - ref| <= 2e-3 * (max |ref| +// of the matrix) + 1e-6. #include "strata/kernels/iq_kernels.hpp" #include @@ -145,6 +146,8 @@ int main() { int fails = 0; for (int ty : {16, 22, 29}) fails += run(ty, 1280, 2560, rng); fails += run(42, 2560, 640, rng); + for (int ty : {20, 21, 23}) fails += run(ty, 1280, 2560, rng); // this pack's gate/up formats, generic WK=256 path + fails += run(20, 2560, 640, rng); // the IQ4_NL down, the new WK=128 lane std::printf("pf_wmma_parity: %d failures\n", fails); return fails ? 1 : 0; } From 2d9b1b348a96f7c02644d520245a69c78464a630 Mon Sep 17 00:00:00 2001 From: g0 Date: Sat, 10 Oct 2026 04:54:05 +0800 Subject: [PATCH 13/36] pf_wmma: take the FP16 prompt path for IQ4_NL down too (mmq_dt == 20) --- src/prefill/prefill.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 749f1c59..23616ae2 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -1044,8 +1044,8 @@ const MmqPlan& mmq_plan() { 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)) { - // pf_wmma: a format dq_dispatch takes (IQ1_M) rides the MMQ grouping, computed by the WMMA tiles only - if (pf_wmma() && lay.native && dt == 42 && strata::kernels::iq_row_bytes(gt, N) > 0) { + // pf_wmma: a format dq_dispatch takes (IQ1_M, an IQ4_NL down) rides the MMQ grouping, computed by the WMMA tiles only + if (pf_wmma() && lay.native && (dt == 42 || dt == 20) && strata::kernels::iq_row_bytes(gt, N) > 0) { p.layer[(size_t) l] = 1; p.wmma_only[(size_t) l] = 1; p.any = true; @@ -3481,9 +3481,9 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri return true; }); } - // pf_wmma: this layer's groups on the FP16 tensor-core tiles (single GPU, native pack, Q2_0 down) + // pf_wmma: this layer's groups on the FP16 tensor-core tiles (single GPU, native pack, Q2_0 / IQ4_NL down) const bool wmma_l = use_mmq && pf_wmma() && !fused_l && on_peer.empty() && lay.native && - mmq_dt == 42 && strata::kernels::iq_row_bytes(mmq_gt, N) > 0; + (mmq_dt == 42 || mmq_dt == 20) && strata::kernels::iq_row_bytes(mmq_gt, N) > 0; if (use_mmq && mmq_plan().wmma_only[(size_t) l] && !wmma_l) { err = "prefill: an IQ1_M layer in the MMQ grouping needs the WMMA tiles, which this chunk cannot take"; return false; From caa3c8425a9acc0598aa35c1ec6f26093131ab47 Mon Sep 17 00:00:00 2001 From: Warabii1248 <93115877+Warabii1248@users.noreply.github.com> Date: Tue, 13 Oct 2026 00:17:22 +0900 Subject: [PATCH 14/36] pf_wmma_parity: run on every sm_70+ card in one process, in turn (a layer split launches the tiles on its second card after the first) --- src/kernels/pf_wmma_parity.cpp | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/src/kernels/pf_wmma_parity.cpp b/src/kernels/pf_wmma_parity.cpp index 090c37ca..bd4897c5 100644 --- a/src/kernels/pf_wmma_parity.cpp +++ b/src/kernels/pf_wmma_parity.cpp @@ -138,16 +138,23 @@ int run(int ty, int n_out, int K, std::mt19937& rng) { } // namespace int main() { - int dev = 0, major = 0; - cudaGetDevice(&dev); - cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev); - if (major < 7) { std::printf("pf_wmma_parity: needs sm_70+, skipped\n"); return 77; } - std::mt19937 rng(70); - int fails = 0; - for (int ty : {16, 22, 29}) fails += run(ty, 1280, 2560, rng); - fails += run(42, 2560, 640, rng); - for (int ty : {20, 21, 23}) fails += run(ty, 1280, 2560, rng); // this pack's gate/up formats, generic WK=256 path - fails += run(20, 2560, 640, rng); // the IQ4_NL down, the new WK=128 lane - std::printf("pf_wmma_parity: %d failures\n", fails); + // every sm_70+ card in one process, in turn: a layer split launches the tiles on its second card after the first + int n_dev = 0, ran = 0, fails = 0; + cudaGetDeviceCount(&n_dev); + for (int dev = 0; dev < n_dev; ++dev) { + int major = 0; + cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev); + if (major < 7) continue; + cudaSetDevice(dev); + std::printf("device %d\n", dev); + ++ran; + std::mt19937 rng(70); + for (int ty : {16, 22, 29}) fails += run(ty, 1280, 2560, rng); + fails += run(42, 2560, 640, rng); + for (int ty : {20, 21, 23}) fails += run(ty, 1280, 2560, rng); // this pack's gate/up formats, generic WK=256 path + fails += run(20, 2560, 640, rng); // the IQ4_NL down, the new WK=128 lane + } + if (!ran) { std::printf("pf_wmma_parity: needs sm_70+, skipped\n"); return 77; } + std::printf("pf_wmma_parity: %d failures on %d devices\n", fails, ran); return fails ? 1 : 0; } From 4dc32064022d79ab1759ee86d9ae7afe78b66b86 Mon Sep 17 00:00:00 2001 From: Warabii1248 <93115877+Warabii1248@users.noreply.github.com> Date: Tue, 13 Oct 2026 00:17:26 +0900 Subject: [PATCH 15/36] pf_wmma: set the tiles shared-memory attribute on each card, not once per process (a layer split stopped on its second card: "the WMMA expert tiles could not launch") --- src/kernels/cuda/iq_kernels.cu | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index 47ee1513..701f433d 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -3977,12 +3977,16 @@ bool gemm_iq_f16_grouped(int ty, const void* W, size_t expert_bytes, int n_out, const dim3 grid((unsigned) (n_out / WG_BN), (unsigned) (n_experts * mt)); cudaStream_t s = (cudaStream_t) stream; auto smem = [](int wk) { return (size_t) WG_BN * (wk + 8) * 2 + (size_t) WG_BM * (WG_XK + 8) * 2; }; - static bool attr = false; - if (!attr) { + // the shared-memory attribute belongs to the current device, so it is set on each card: with one flag for the + // process a layer split's second card launched without it and the prompt stopped ("the WMMA expert tiles could not launch") + static bool attr[64]; + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return false; + if (!attr[dev]) { cudaFuncSetAttribute(gemm_iq_f16_grouped_kernel<256, false>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem(256)); cudaFuncSetAttribute(gemm_iq_f16_grouped_kernel<128, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem(128)); cudaFuncSetAttribute(gemm_iq_f16_grouped_kernel<128, false, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem(128)); - attr = true; + attr[dev] = true; } if (q20) gemm_iq_f16_grouped_kernel<128, true><<>>(ty, (const uint8_t*) W, expert_bytes, row_bytes, K, From dca6a6532f57bfa54c8920196b7f60bc7aac34b1 Mon Sep 17 00:00:00 2001 From: Warabii1248 <93115877+Warabii1248@users.noreply.github.com> Date: Tue, 13 Oct 2026 19:21:00 +0900 Subject: [PATCH 16/36] pf_wmma: STRATA_PF_WMMA2=1 (opt-in), a second Volta prompt-expert kernel for IQ2_S gate/up and IQ4_NL down - the dequantization spread over the whole block from a raw stage in shared memory (bitwise dq_iq2_s / dq_iq4_nl; prompt +2.5-4.3% with the IQ3_XXS pack on a V100 + PG500 split) --- src/kernels/cuda/iq_kernels.cu | 216 +++++++++++++++++++++++++++++++++ 1 file changed, 216 insertions(+) diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index 701f433d..332809a8 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -3964,11 +3964,227 @@ __global__ void __launch_bounds__(WG_THREADS) gemm_iq_f16_grouped_kernel(int ty, __syncthreads(); } } + +// ---- STRATA_PF_WMMA2=1 (opt-in): IQ2_S gate/up and IQ4_NL down, tiled after a llama.cpp fork's Volta MoE kernel. +// A block: W2_RB = 128 weight rows of one expert x W2_CB = 64 of its sorted rows, K stages of W2_KT = 64. Thread t dequantizes +// row t % 128, 32-value sub-block t / 128 of each K stage from the raw stage in shared memory (one IQ2_S super-block or four IQ4_NL +// blocks per row, read by the whole block as 4-byte words, the next one already in registers). 8 warps = 4 (32 weight rows) x 2 +// (32 sorted rows), 2 x 2 wmma 16x16x16 fragments each, FP32 sums. +constexpr int W2_RB = 128, W2_CB = 64, W2_KT = 64, W2_NT = 256, W2_LD = W2_KT + 8; +template struct w2_traits; +template <> struct w2_traits<22> { static constexpr int raw_k = 256, raw_b = 82, segw = 21, segw_s = 21, ntab = 1024 + 16; }; +template <> struct w2_traits<20> { static constexpr int raw_k = 128, raw_b = 72, segw = 18, segw_s = 19, ntab = 128; }; +template __host__ __device__ constexpr int w2_nl() { return (W2_RB * w2_traits::segw + W2_NT - 1) / W2_NT; } + +__device__ __forceinline__ uint32_t w2_ld_b2(const uint8_t* p) { // 4 bytes at a 2-byte aligned address + const uint16_t* q = reinterpret_cast(p); + return (uint32_t) q[0] | ((uint32_t) q[1] << 16); +} +__device__ __forceinline__ half2 w2_h2(uint32_t v) { half2 h; memcpy(&h, &v, 4); return h; } +__device__ __forceinline__ uint32_t w2_u32(half2 h) { uint32_t v; memcpy(&v, &h, 4); return v; } + +// the raw stage rs of the block's 128 rows: segw words per row from the 4-byte aligned start at or below rs * raw_b +template +__device__ __forceinline__ void w2_raw_ld(uint32_t (&R)[w2_nl()], const uint8_t* __restrict__ xb, size_t row_bytes, int rs, int tid) { + using tr = w2_traits; + const int off = (rs * tr::raw_b) & ~3; +#pragma unroll + for (int i = 0; i < w2_nl(); ++i) { + const int w = tid + i * W2_NT; + if ((W2_RB * tr::segw) % W2_NT == 0 || w < W2_RB * tr::segw) + R[i] = *reinterpret_cast(xb + (size_t) (w / tr::segw) * row_bytes + off + 4 * (w % tr::segw)); + } +} +template +__device__ __forceinline__ void w2_raw_st(const uint32_t (&R)[w2_nl()], uint32_t* __restrict__ raw, int tid) { + using tr = w2_traits; +#pragma unroll + for (int i = 0; i < w2_nl(); ++i) { + const int w = tid + i * W2_NT; + if ((W2_RB * tr::segw) % W2_NT == 0 || w < W2_RB * tr::segw) raw[(w / tr::segw) * tr::segw_s + w % tr::segw] = R[i]; + } +} + +// sub-block `sb` (0..7) of the IQ2_S super-block at rr -> 32 halves at o, natural order, bit for bit dq_iq2_s's values: +// cvt<__half>(dl * grid[j] * +-1) with dl = d * (0.5 + scale) * 0.25 in FP32 (the sign flips the rounded half, which is the same) +__device__ __forceinline__ float w2_b2f(uint32_t w, int j) { return __int_as_float(0x4B000000 | ((w >> 8 * j) & 0xff)) - 8388608.0f; } +__device__ __forceinline__ void w2_dq_iq2_s(const uint8_t* rr, int sb, __half* o, const uint2* __restrict__ tab) { + const uint2* sgn = tab + 1024; + const uint32_t sc = rr[2 + 64 + 8 + sb], qh = rr[2 + 64 + sb]; + const uint32_t qs = w2_ld_b2(rr + 2 + 4 * sb), sg = w2_ld_b2(rr + 2 + 32 + 4 * sb); + const float d = __half2float(__ushort_as_half(*reinterpret_cast(rr))); + const float dl0 = d * (0.5f + (float) (sc & 0xf)) * 0.25f; + const float dl1 = d * (0.5f + (float) (sc >> 4)) * 0.25f; +#pragma unroll + for (int il = 0; il < 4; ++il) { + const float dl = il < 2 ? dl0 : dl1; + const int idx = (int) (((qs >> 8 * il) & 0xff) | ((qh << (8 - 2 * il)) & 0x300)); + const uint2 gw = tab[idx]; + const uint32_t sbits = (sg >> 8 * il) & 0xff; + const uint2 s0 = sgn[sbits & 15], s1 = sgn[sbits >> 4]; + uint4 out; + out.x = w2_u32(__floats2half2_rn(dl * w2_b2f(gw.x, 0), dl * w2_b2f(gw.x, 1))) ^ s0.x; + out.y = w2_u32(__floats2half2_rn(dl * w2_b2f(gw.x, 2), dl * w2_b2f(gw.x, 3))) ^ s0.y; + out.z = w2_u32(__floats2half2_rn(dl * w2_b2f(gw.y, 0), dl * w2_b2f(gw.y, 1))) ^ s1.x; + out.w = w2_u32(__floats2half2_rn(dl * w2_b2f(gw.y, 2), dl * w2_b2f(gw.y, 3))) ^ s1.y; + *reinterpret_cast(o + 8 * il) = out; + } +} +// IQ4_NL block at b -> 32 halves at o, natural order (value j: the low nibble of byte j, value j + 16: its high nibble); the product +// of two exact halves rounded once, as cvt<__half>(d * kvalues_iq4nl[q]) +__device__ __forceinline__ void w2_dq_iq4_nl(const uint8_t* b, __half* o, const half2* __restrict__ kv) { + const half2 d2 = __half2half2(__ushort_as_half(*reinterpret_cast(b))); +#pragma unroll + for (int i = 0; i < 4; ++i) { + const uint32_t q = w2_ld_b2(b + 2 + 4 * i); + const half2 t0 = kv[q & 0xff], t1 = kv[(q >> 8) & 0xff], t2 = kv[(q >> 16) & 0xff], t3 = kv[q >> 24]; + uint2 lo, hi; + lo.x = w2_u32(__hmul2(__lows2half2(t0, t1), d2)); + lo.y = w2_u32(__hmul2(__lows2half2(t2, t3), d2)); + hi.x = w2_u32(__hmul2(__highs2half2(t0, t1), d2)); + hi.y = w2_u32(__hmul2(__highs2half2(t2, t3), d2)); + *reinterpret_cast(o + 4 * i) = lo; + *reinterpret_cast(o + 16 + 4 * i) = hi; + } +} + +template +__global__ void __launch_bounds__(W2_NT, 2) gemm_iq_f16_w2_kernel(const uint8_t* __restrict__ W, size_t expert_bytes, size_t row_bytes, + int K, const __half* __restrict__ X, int ldx, + const int32_t* __restrict__ bounds, int ch_per_e, + float* __restrict__ Y, int ldy) { + using namespace nvcuda; + using tr = w2_traits; + constexpr int NL = w2_nl(), NSUB = tr::raw_k / W2_KT; + __shared__ __align__(128) __half xs[W2_RB * W2_LD]; + __shared__ __align__(128) __half ys[W2_CB * W2_LD]; + __shared__ uint2 tab[tr::ntab]; + __shared__ uint32_t raw[W2_RB * tr::segw_s]; + + const int e = blockIdx.y / ch_per_e, ch = blockIdx.y % ch_per_e; + const int c0 = bounds[e] + ch * W2_CB, r1 = bounds[e + 1]; + if (c0 >= r1) return; + const int ncol = min(W2_CB, r1 - c0); + const int n0 = blockIdx.x * W2_RB; + const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31; + const int wr = warp & 3, wc = warp >> 2; // weight rows wr*32, sorted rows wc*32 + const uint8_t* xb = W + (size_t) e * expert_bytes + (size_t) n0 * row_bytes; + const int nrs = K / tr::raw_k; + + uint32_t R[NL]; + w2_raw_ld(R, xb, row_bytes, 0, tid); + const int yq = tid & 7, yc = tid >> 3; // 16-byte part yq of sorted rows yc and yc + 32 + uint4 Yr[2]; + auto load_y = [&](int k0) { +#pragma unroll + for (int u = 0; u < 2; ++u) { + const int c = yc + 32 * u; + Yr[u] = c < ncol ? *reinterpret_cast(X + (size_t) (c0 + c) * ldx + k0 + 8 * yq) : make_uint4(0, 0, 0, 0); + } + }; + load_y(0); + if constexpr (TY == 20) { + reinterpret_cast(tab)[tid] = __halves2half2(__int2half_rn(kvalues_iq4nl[tid & 15]), __int2half_rn(kvalues_iq4nl[tid >> 4])); + } else { + for (int i = tid; i < 1024; i += W2_NT) tab[i] = reinterpret_cast(iq2s_grid)[i]; + if (tid < 16) // a sign nibble -> masks of its bits 0-1 and 2-3 (bit 2p -> bit 15, bit 2p + 1 -> bit 31) + tab[1024 + tid] = make_uint2(((tid >> 0) & 1u) << 15 | ((tid >> 1) & 1u) << 31, ((tid >> 2) & 1u) << 15 | ((tid >> 3) & 1u) << 31); + } + w2_raw_st(R, raw, tid); + if (nrs > 1) w2_raw_ld(R, xb, row_bytes, 1, tid); + __syncthreads(); + + wmma::fragment acc[2][2]; +#pragma unroll + for (int a = 0; a < 2; ++a) +#pragma unroll + for (int b = 0; b < 2; ++b) wmma::fill_fragment(acc[a][b], 0.0f); + const int xr = tid % W2_RB, sub = tid / W2_RB; + __half* xrow = xs + xr * W2_LD + 32 * sub; + const uint8_t* rawrow = reinterpret_cast(raw + xr * tr::segw_s); + + for (int rs = 0; rs < nrs; ++rs) { + const uint8_t* rr = rawrow + ((rs * tr::raw_b) & 3); +#pragma unroll + for (int h = 0; h < NSUB; ++h) { + const int k0 = (rs * NSUB + h) * W2_KT; + if constexpr (TY == 20) w2_dq_iq4_nl(rr + 18 * (2 * h + sub), xrow, reinterpret_cast(tab)); + else w2_dq_iq2_s(rr, 2 * h + sub, xrow, tab); +#pragma unroll + for (int u = 0; u < 2; ++u) *reinterpret_cast(ys + (yc + 32 * u) * W2_LD + 8 * yq) = Yr[u]; + __syncthreads(); + if (k0 + W2_KT < K) load_y(k0 + W2_KT); + if (wc * 32 < ncol) { // warp-uniform: sorted rows past the expert's skip their mma +#pragma unroll + for (int kk = 0; kk < W2_KT; kk += 16) { + wmma::fragment a[2]; + wmma::fragment b[2]; +#pragma unroll + for (int f = 0; f < 2; ++f) { + wmma::load_matrix_sync(a[f], ys + (wc * 32 + f * 16) * W2_LD + kk, W2_LD); + wmma::load_matrix_sync(b[f], xs + (wr * 32 + f * 16) * W2_LD + kk, W2_LD); + } +#pragma unroll + for (int fa = 0; fa < 2; ++fa) { + if (wc * 32 + fa * 16 >= ncol) break; +#pragma unroll + for (int fb = 0; fb < 2; ++fb) wmma::mma_sync(acc[fa][fb], a[fa], b[fb], acc[fa][fb]); + } + } + } + if (h == NSUB - 1 && rs + 1 < nrs) { // nobody reads raw between the barrier above and the one below + w2_raw_st(R, raw, tid); + if (rs + 2 < nrs) w2_raw_ld(R, xb, row_bytes, rs + 2, tid); + } + __syncthreads(); + } + } + // full 16-row tiles straight to Y; the expert's last partial one through the warp's 16 x 16 scratch (ys is free now) + float* scr = reinterpret_cast(ys) + warp * 256; +#pragma unroll + for (int fa = 0; fa < 2; ++fa) { + const int t0 = wc * 32 + fa * 16; + if (t0 >= ncol) break; +#pragma unroll + for (int fb = 0; fb < 2; ++fb) { + const int nb = n0 + wr * 32 + fb * 16; + if (t0 + 16 <= ncol) { + wmma::store_matrix_sync(Y + (size_t) (c0 + t0) * ldy + nb, acc[fa][fb], ldy, wmma::mem_row_major); + } else { + wmma::store_matrix_sync(scr, acc[fa][fb], 16, wmma::mem_row_major); + __syncwarp(); + for (int i = lane; i < 256; i += 32) + if (t0 + i / 16 < ncol) Y[(size_t) (c0 + t0 + i / 16) * ldy + nb + i % 16] = scr[i]; + __syncwarp(); + } + } + } +} + +bool w2_on() { + static const bool v = [] { const char* e = std::getenv("STRATA_PF_WMMA2"); return e && e[0] == '1'; }(); + return v; +} } // namespace bool gemm_iq_f16_grouped(int ty, const void* W, size_t expert_bytes, int n_out, int K, const void* X, int ldx, const int32_t* bounds, int n_experts, int max_rows, float* Y, int ldy, void* stream) { if (n_out % WG_BN != 0 || n_experts <= 0 || max_rows <= 0 || ldy % 4 != 0) return false; + // STRATA_PF_WMMA2=1 (opt-in): IQ2_S gate/up and IQ4_NL down through gemm_iq_f16_w2_kernel (above) + if (w2_on() && n_out % W2_RB == 0 && ldx % 8 == 0 && ldy % 8 == 0 && (uintptr_t) X % 16 == 0 && (uintptr_t) Y % 32 == 0 && + (uintptr_t) W % 4 == 0 && expert_bytes % 4 == 0 && ((ty == 22 && K % 512 == 0) || (ty == 20 && K % 128 == 0))) { + const size_t rb = iq_row_bytes(ty, K); + const int ch = (max_rows + W2_CB - 1) / W2_CB; + if (rb % 4 == 0 && (long long) n_experts * ch <= 65535) { + const dim3 grid2((unsigned) (n_out / W2_RB), (unsigned) (n_experts * ch)); + cudaStream_t s2 = (cudaStream_t) stream; + if (ty == 22) + gemm_iq_f16_w2_kernel<22><<>>((const uint8_t*) W, expert_bytes, rb, K, (const __half*) X, ldx, bounds, ch, Y, ldy); + else + gemm_iq_f16_w2_kernel<20><<>>((const uint8_t*) W, expert_bytes, rb, K, (const __half*) X, ldx, bounds, ch, Y, ldy); + return cudaGetLastError() == cudaSuccess; + } + } const bool q20 = ty == 42; const bool nl = ty == 20 && K % 256 != 0; // IQ4_NL down (K=640): there is no WK=256 path for this K if (q20 || nl ? K % 128 != 0 : (K % 256 != 0 || !is_iq(ty))) return false; From ab5ea838de3c15802008f92aec01b6e76e81f4d4 Mon Sep 17 00:00:00 2001 From: Warabii1248 <93115877+Warabii1248@users.noreply.github.com> Date: Tue, 13 Oct 2026 22:55:12 +0900 Subject: [PATCH 17/36] pf_wmma: say in the comment where the WMMA2 tile layout comes from --- src/kernels/cuda/iq_kernels.cu | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index 332809a8..9445fb40 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -3965,7 +3965,8 @@ __global__ void __launch_bounds__(WG_THREADS) gemm_iq_f16_grouped_kernel(int ty, } } -// ---- STRATA_PF_WMMA2=1 (opt-in): IQ2_S gate/up and IQ4_NL down, tiled after a llama.cpp fork's Volta MoE kernel. +// ---- STRATA_PF_WMMA2=1 (opt-in): IQ2_S gate/up and IQ4_NL down, tiled like a Volta MoE kernel in the +// PR author's own unpublished llama.cpp patches. // A block: W2_RB = 128 weight rows of one expert x W2_CB = 64 of its sorted rows, K stages of W2_KT = 64. Thread t dequantizes // row t % 128, 32-value sub-block t / 128 of each K stage from the raw stage in shared memory (one IQ2_S super-block or four IQ4_NL // blocks per row, read by the whole block as 4-byte words, the next one already in registers). 8 warps = 4 (32 weight rows) x 2 From 83081577e549800a57f633be33b843b40bc1f389 Mon Sep 17 00:00:00 2001 From: Warabii1248 <93115877+Warabii1248@users.noreply.github.com> Date: Tue, 13 Oct 2026 19:20:29 +0900 Subject: [PATCH 18/36] sm_70: the multi-block greedy pick (argmax_rows) as an opt-in, STRATA_ARGMAX_ROWS_SM70=1 (bitwise the one-block pick; decode +0.7-0.8% on a V100 + PG500 split) --- src/kernels/cuda/verify_kernels.cu | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/kernels/cuda/verify_kernels.cu b/src/kernels/cuda/verify_kernels.cu index 39fdda2d..bf6282da 100644 --- a/src/kernels/cuda/verify_kernels.cu +++ b/src/kernels/cuda/verify_kernels.cu @@ -943,6 +943,10 @@ bool argmax_rows_wanted() { int dev = 0, major = 0; if (cudaGetDevice(&dev) != cudaSuccess || cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess) return false; + if (major == 7) { // STRATA_ARGMAX_ROWS_SM70=1: opt-in on Volta (measured on sm_70 only) + const char* e = std::getenv("STRATA_ARGMAX_ROWS_SM70"); + return e != nullptr && std::atoi(e) != 0; + } return major == 8; }(); return want && multi_block_head_ops(); From ab7c977216516f82458b0b3a3c21d01bd0366ca8 Mon Sep 17 00:00:00 2001 From: Warabii1248 <93115877+Warabii1248@users.noreply.github.com> Date: Tue, 13 Oct 2026 22:37:45 +0900 Subject: [PATCH 19/36] verify: say in the comments that sm_7x takes argmax_rows with STRATA_ARGMAX_ROWS_SM70=1 --- src/core/verify.cpp | 2 +- src/kernels/cuda/verify_kernels.cu | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/verify.cpp b/src/core/verify.cpp index a8791cc6..d6ebf608 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -1818,7 +1818,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { // Greedy, the default, is recorded here as before (no extra launch or sync per window). A request that // samples or penalizes is sampled again host-side after the replay (run()) with its own parameters and a // fresh draw counter: a captured sampler would bake them in and replay the same draws forever. - if (argmax_rows_wanted()) { // sm_80 to sm_89: the pick over many blocks a row (bitwise the one-block kernel's) + if (argmax_rows_wanted()) { // sm_80 to sm_89 (sm_7x opt-in): the pick over many blocks a row (bitwise the one-block kernel's) argmax_rows(head_logits_, T, (int) n_vocab_, arg_scratch_, m_out_, cs); } else { SamplerParams sp; diff --git a/src/kernels/cuda/verify_kernels.cu b/src/kernels/cuda/verify_kernels.cu index bf6282da..b3b1e644 100644 --- a/src/kernels/cuda/verify_kernels.cu +++ b/src/kernels/cuda/verify_kernels.cu @@ -938,7 +938,7 @@ bool argmax_rows_wanted() { #if defined(__HIPCC__) return false; #else - // sm_80 to sm_89: sample_tokens' greedy pick there is the one-block kernel (sm_90+ has the cluster kernel) + // sm_80 to sm_89, and sm_7x with STRATA_ARGMAX_ROWS_SM70=1: sample_tokens' greedy pick there is the one-block kernel (sm_90+ has the cluster kernel) static const bool want = [] { int dev = 0, major = 0; if (cudaGetDevice(&dev) != cudaSuccess || cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess) From fec7d1cae2c0c078da754f78edbf0acf737f7a90 Mon Sep 17 00:00:00 2001 From: Warabii1248 <93115877+Warabii1248@users.noreply.github.com> Date: Tue, 13 Oct 2026 19:20:29 +0900 Subject: [PATCH 20/36] fused_gr: STRATA_GR_NORM_FAST=1 on CUDA too (opt-in; the register split norm is bitwise the default; decode +0.5-0.6% on a V100 + PG500 split) --- src/kernels/cuda/fused_gr.cu | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cu index c3c2fc8d..ff8f4f36 100644 --- a/src/kernels/cuda/fused_gr.cu +++ b/src/kernels/cuda/fused_gr.cu @@ -1020,7 +1020,9 @@ bool norm_fast_on() { } return per_dev[dev] == 2; #else - return false; + // CUDA: opt-in with STRATA_GR_NORM_FAST=1 (measured on sm_70 only) + static const bool on = [] { const char* e = std::getenv("STRATA_GR_NORM_FAST"); return e != nullptr && std::atoi(e) != 0; }(); + return on; #endif } From 1327c0916c54901108aa9b8c243321b39fc3f251 Mon Sep 17 00:00:00 2001 From: Warabii1248 <93115877+Warabii1248@users.noreply.github.com> Date: Tue, 13 Oct 2026 22:37:45 +0900 Subject: [PATCH 21/36] fused_gr: say in the comment that CUDA opts in to the register split norm --- src/kernels/cuda/fused_gr.cu | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cu index ff8f4f36..c38c1071 100644 --- a/src/kernels/cuda/fused_gr.cu +++ b/src/kernels/cuda/fused_gr.cu @@ -1005,7 +1005,7 @@ bool gr_down_max4() { return on; } -// the split norm with registers (gr_norm_split_fast_kernel): gfx12 only until another arch is measured; +// the split norm with registers (gr_norm_split_fast_kernel): on by default on gfx12; CUDA opt-in (measured on sm_70 only); // STRATA_GR_NORM_FAST=0 / 1 forces it off / on bool norm_fast_on() { #if defined(__HIPCC__) From 96cb96aced62ee5c5464e36fb9f797b89c8000a4 Mon Sep 17 00:00:00 2001 From: ruibeikaa <126486262+ruibeikaa@users.noreply.github.com> Date: Wed, 7 Oct 2026 19:10:19 +0000 Subject: [PATCH 22/36] sm_60: stage IQ3_XXS's codebook and sign masks in shared memory (grouped expert kernels) Ported from shinbunbun/llama-cpp-p100-patches (MIT), patches 29 `mmvq-iq3xxs-grid-smem` and 30 `mmvq-ksigns-smem`: the grouped expert kernels stage the 256-word iq3xxs_grid and two 128-word tables of per-byte sign masks once per block, and apply a mask as (g ^ mask) + (mask & 0x01010101) instead of the per-lookup unpack_ksigns / __vcmpne4 / __vsub4 chain (iq3xxs_grid's bytes are all >= 4, so no carry crosses a byte). Bitwise the same output: checked end to end on a PH402 (GP100), greedy, three prompts x three interleaved rounds, identical replies with and without. Measured only on GP100, where it is within noise (+0-4% decode), so it is the default on compute capability 6.x only; STRATA_IQ_STAGE_GRID18=1 / 0 forces it on / off on any card. --- src/kernels/cuda/iq_kernels.cu | 70 +++++++++++++++++++++++++++++----- 1 file changed, 60 insertions(+), 10 deletions(-) diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index 9445fb40..ed1f5328 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -701,7 +701,7 @@ template struct Split; // per-entry ones, which call Fmt::dot per column exactly as before #242 (the launchers test kSplit at compile // time, so the multi kernels are never instantiated for a type without a Split). template inline constexpr bool kSplit = false; -template inline constexpr bool kStageIqGrid = (TY == 16 || TY == 17 || TY == 22 || TY == 29); +template inline constexpr bool kStageIqGrid = (TY == 16 || TY == 17 || TY == 18 || TY == 22 || TY == 29); template<> inline constexpr bool kSplit<16> = true; template<> struct Split<16> { // IQ2_XXS @@ -810,20 +810,30 @@ template<> inline constexpr bool kSplit<18> = true; template<> struct Split<18> { // IQ3_XXS struct W { int g[8]; int ls; float dw; }; template - __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ = nullptr) { + __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ s_grid = nullptr) { const block_iq3_xxs* bq3 = (const block_iq3_xxs*) vbq + kbx; const int2 q3_packed = make_int2(get_int_b2(bq3->qs, iqs), get_int_b2(bq3->qs, iqs + 1)); const uint8_t* q3 = (const uint8_t*) &q3_packed; const uint32_t aux32 = get_int_b2(bq3->qs, QK_K / 16 + iqs / 2); + const uint32_t* grid = STAGE_GRID ? s_grid : iq3xxs_grid; W r; #pragma unroll for (int l0 = 0; l0 < 8; l0 += 2) { - const int2 grid_pos = make_int2(iq3xxs_grid[q3[l0 + 0]], iq3xxs_grid[q3[l0 + 1]]); - const uint32_t signs = unpack_ksigns(aux32 >> (7 * l0 / 2)); - const int signs0 = __vcmpne4(signs & 0x08040201, 0); - r.g[l0 + 0] = __vsub4(grid_pos.x ^ signs0, signs0); - const int signs1 = __vcmpne4(signs & 0x80402010, 0); - r.g[l0 + 1] = __vsub4(grid_pos.y ^ signs1, signs1); + const int2 grid_pos = make_int2(grid[q3[l0 + 0]], grid[q3[l0 + 1]]); + if constexpr (STAGE_GRID) { + // The staged tables hold one mask per 7-bit sign field; bit 7 of the field is the next group's + // first sign, which unpack_ksigns cancels, so masking it off is the same value. + const uint32_t v = (aux32 >> (7 * l0 / 2)) & 0x7f; + const uint32_t ml = s_grid[256 + v], mh = s_grid[384 + v]; + r.g[l0 + 0] = (int) ((grid_pos.x ^ ml) + (ml & 0x01010101u)); + r.g[l0 + 1] = (int) ((grid_pos.y ^ mh) + (mh & 0x01010101u)); + } else { + const uint32_t signs = unpack_ksigns(aux32 >> (7 * l0 / 2)); + const int signs0 = __vcmpne4(signs & 0x08040201, 0); + r.g[l0 + 0] = __vsub4(grid_pos.x ^ signs0, signs0); + const int signs1 = __vcmpne4(signs & 0x80402010, 0); + r.g[l0 + 1] = __vsub4(grid_pos.y ^ signs1, signs1); + } } r.ls = aux32 >> 28; r.dw = __half2float(bq3->d); @@ -1264,6 +1274,27 @@ __device__ __forceinline__ const uint32_t* stage_iq_grid(uint32_t* s_buf, int ti for (int i = tid; i < 1024; i += nthreads) dst[i] = src[i]; __syncthreads(); return s_buf; + } else if constexpr (TY == 18) { + // 256 codebook words, then two 128-word tables of the per-byte sign masks (signs 0-3, signs 4-7). A + // mask depends only on the 7 bits it is unpacked from, and iq3xxs_grid's bytes are all >= 4, so the + // consumer applies it as (g ^ mask) + (mask & 0x01010101): a negate per set byte, with no carry into + // the next. One pass per block replaces the per-lookup unpack_ksigns / __vcmpne4 / __vsub4 chain. + // Ported from shinbunbun/llama-cpp-p100-patches (MIT), patches 29 `mmvq-iq3xxs-grid-smem` and 30 + // `mmvq-ksigns-smem`, measured there on a Tesla P100 (sm_60). + for (int i = tid; i < 256; i += nthreads) s_buf[i] = iq3xxs_grid[i]; + for (int u = tid; u < 128; u += nthreads) { + const uint32_t s = (uint32_t) u | ((__popc((uint32_t) u) & 1u) << 7); // 8th sign = parity of the 7 + uint32_t ml = 0, mh = 0; +#pragma unroll + for (int i = 0; i < 4; ++i) { + ml |= ((s >> i) & 1u) * (0xffu << (8 * i)); + mh |= ((s >> (4 + i)) & 1u) * (0xffu << (8 * i)); + } + s_buf[256 + u] = ml; + s_buf[384 + u] = mh; + } + __syncthreads(); + return s_buf; } else { return nullptr; } @@ -1271,7 +1302,7 @@ __device__ __forceinline__ const uint32_t* stage_iq_grid(uint32_t* s_buf, int ti template> struct IqGridWords { - static constexpr int value = !STAGE_GRID ? 4 : (TY == 22 || TY == 29) ? 2048 : (TY == 17) ? 1024 : (TY == 16) ? 512 : 4; + static constexpr int value = !STAGE_GRID ? 4 : (TY == 22 || TY == 29) ? 2048 : (TY == 17) ? 1024 : (TY == 16 || TY == 18) ? 512 : 4; }; // mmvq_kernel with the columns taken NC at a time. After warp_sum every lane holds the same sum, so lane c stores @@ -2144,6 +2175,25 @@ bool g_stage_grid_mmvq = g_stage_grid && [] { const char* v = std::getenv("STRATA_IQ_STAGE_GRID_MMVQ"); return v != nullptr && v[0] == '1'; }(); +// IQ3_XXS's codebook and sign-mask tables staged in shared memory by the grouped expert kernels (the single-matrix +// mmvq does not): bitwise the same either way. Measured on Pascal GP100 only, so it is the default on compute +// capability 6.x and off elsewhere; STRATA_IQ_STAGE_GRID18=1 / 0 forces it on / off on any card. +bool stage_grid18_on() { + if (!g_stage_grid) return false; + static const int forced = [] { + const char* v = std::getenv("STRATA_IQ_STAGE_GRID18"); + return (v && v[0]) ? (v[0] != '0' ? 1 : 0) : -1; + }(); + if (forced >= 0) return forced == 1; + static int by_device[64]; // 0 unknown, 1 on, 2 off + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return false; + if (by_device[dev] == 0) { + int major = 0; + by_device[dev] = (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess && major == 6) ? 1 : 2; + } + return by_device[dev] == 1; +} template> void launch_mmvq_multi_nc(dim3 grid, dim3 block, cudaStream_t s, const uint8_t* W, size_t rb, const block_q8_1* X, @@ -2847,7 +2897,7 @@ void launch_gu(dim3 grid, cudaStream_t s, const unsigned long long* grp_ptr, con if constexpr (!kSplit) native_gu_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (g_old_kernels) native_gu_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if constexpr (kStageIqGrid) { - if (!g_stage_grid) { + if (!g_stage_grid || (TG == 18 && !stage_grid18_on())) { if (g_no_sub16_gu) native_gu_multi_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_multi_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); return; From 6e29a5d3141fafd74e2eed88fc4314cc34ab8f7c Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 07:08:58 +0200 Subject: [PATCH 23/36] sm_60: a Q8_0 decode GEMV for Pascal GP100 (STRATA_Q8_SM60=1, opt-in) GP100 has no __dp4a, and on a GP100 die the verify window's dense projections read their weights at 40-80 GB/s of ~730. With STRATA_Q8_SM60=1 every Q8_0 dense matrix (any shape) and the head get the packed planes of STRATA_Q8_PACKED and run src/kernels/cuda/q8_sm60.cuh: a warp (half / quarter warp for narrow rows) per row, 16-byte weight loads through the read-only cache, the window's q8_1 activations copied once per workgroup into shared memory as an int8 plane plus float scales, STRATA_DP4A (vmad on sm_60), a shuffle sum with no barrier per row, persistent workgroups (4 per SM, STRATA_Q8_SM60_BPS). Shapes it declines (> 48 KiB of shared memory: a 6144-wide row with 7-8 columns) keep the usual kernel. Not bitwise the exact kernels (summation order); the packed copies cost their size in VRAM (Flash-Next: 2.9 GiB of dense projections over the stages, 0.6 GiB head). The GSQ-RCO packs have no Q8_0 dense matrices: tools/q8_dense_gguf.py writes a shard 1 whose natively served projections and head are Q8_0, keeping the tensor-info block's length so every expert keeps its offset (the native pack is reused) and hard-linking the other shards beside it. PH402 SKU 200 (four GP100 dies), clocks locked at 1050 MHz, Flash-Next IQ3_XXS, 32K, layer split 12,24,36, --prefill 2048, greedy, decode tok/s (medians, interleaved starts): GSQ-RCO shard 28.3, Q8_0 shard with STRATA_Q8_PACKED 31.1, Q8_0 shard with STRATA_Q8_SM60 38.9 (+37%); per window dense 19.2 -> 11.2 ms, head 4.25 -> 2.1 ms; prompt reads unchanged. tools/q8_sm60_check.cu: 57 shape x column cases against a CPU reference, max relative error < 1e-5. docs/OLDER_GPUS.md has the table, the conditions and how to use it. Co-authored-by: ruibeikaa <126486262+ruibeikaa@users.noreply.github.com> --- docs/OLDER_GPUS.md | 46 +++++++- include/strata/kernels/native_mmvq.hpp | 5 + src/core/native_head.cpp | 3 + src/kernels/cuda/native_mmvq.cu | 96 +++++++++++++++- src/kernels/cuda/q8_sm60.cuh | 148 +++++++++++++++++++++++++ tools/q8_dense_gguf.py | 146 ++++++++++++++++++++++++ tools/q8_sm60_check.cu | 108 ++++++++++++++++++ 7 files changed, 547 insertions(+), 5 deletions(-) create mode 100644 src/kernels/cuda/q8_sm60.cuh create mode 100644 tools/q8_dense_gguf.py create mode 100644 tools/q8_sm60_check.cu diff --git a/docs/OLDER_GPUS.md b/docs/OLDER_GPUS.md index dc811c9b..b653dcd0 100644 --- a/docs/OLDER_GPUS.md +++ b/docs/OLDER_GPUS.md @@ -11,7 +11,7 @@ and their output stay exactly as they were. Numbers are the reporters' own, on o | Cards | Compute capability | How it runs | What is different on it | Reported | | --- | --- | --- | --- | --- | -| Tesla P100 | 6.0 | the CUDA 12 engine | `__dp4a` emulated (bit-exact); BF16 projections through fp32 | 2x P100, IQ3_S, engine 0.1.39: prompt 526-532 tok/s, decode 28-32 tok/s at 128K prompt tokens, 3 of 3 needle checks at 122K ([report](../bench/results/2026-10-06-community-2x-p100/README.md), #1157) | +| Tesla P100 | 6.0 | the CUDA 12 engine | `__dp4a` emulated (bit-exact); BF16 projections through fp32; opt-in: `STRATA_Q8_SM60=1` runs the Q8_0 dense projections and head on a GP100 kernel ([below](#pascal-gp100-a-q8_0-decode-kernel-opt-in)) | 2x P100, IQ3_S, engine 0.1.39: prompt 526-532 tok/s, decode 28-32 tok/s at 128K prompt tokens, 3 of 3 needle checks at 122K ([report](../bench/results/2026-10-06-community-2x-p100/README.md), #1157); PH402 (4 GP100 dies), IQ3_XXS: decode 28.3 -> 38.9 tok/s with `STRATA_Q8_SM60=1` and a Q8_0 dense shard | | Tesla P40 / P4, GTX 10 series | 6.1 | the CUDA 12 engine | BF16 projections through fp32 (cuBLAS has no BF16 GEMM there, #395); the dense weights dequantized by a wide kernel, expert mode 8 and its own interleaved-matvec table; opt-in `STRATA_DENSE_F32=1`: the large dense GEMMs as `cublasSgemm` ([below](#tesla-p40-sm_61-what-was-measured-and-changed)) | P40, IQ3_S, engine 0.1.30: prompt 217-374 tok/s, decode 30-33 tok/s (#395); 0.1.43.1 with the sm_61 changes: prompt 255 tok/s at 565 tokens (was 205), decode 37-38 tok/s (was 34-35); with `STRATA_DENSE_F32=1` 464-474 tok/s at 7K tokens (was 360-432) | | Tesla V100, Titan V | 7.0 | the CUDA 12 engine | BF16 projections on the FP16 tensor cores (#655, #540); the prompt attention on `mma.m8n8k4` (#600); a leaner attention kernel (#540) | V100-PCIE-32GB, UD-IQ4_XS: prompt 1,123-1,251 tok/s (#600); V100 32GB, IQ2_XS: prompt +22% from #540 | | RTX 20 (Turing) | 7.5 | **supported**, the ready-made engine | opt-in: `STRATA_BF16_TC=1` runs the BF16 projections on the FP16 tensor cores | RTX 2080 Ti, Q2_0: prompt +15-18% (#655) | @@ -95,8 +95,50 @@ sums round differently): #540 measured a mean KL of 8.4e-3 on the next-token dis (the same top-1 in 23), the size of other summation-order changes; #655 a worst relative difference of 3.5e-5 per product on an RTX 2080 Ti. +### Pascal GP100: a Q8_0 decode kernel (opt-in) + +GP100 (P100, PH402) is the one Pascal chip without `__dp4a`, and the decode kernels are written for the cards that have +it: on a GP100 die the dense projections of a verify window read their weights at 40-80 GB/s of its ~730, decoding K- +and i-quant blocks (Q6_K, IQ4_XS, Q4_K, IQ3_S, ...) one int at a time. Two changes, both measured on a PH402 only: + +- **`STRATA_Q8_SM60=1`** packs every Q8_0 dense matrix and the head into the planes of `STRATA_Q8_PACKED` (any shape) + and runs them on `src/kernels/cuda/q8_sm60.cuh`: a warp (half or quarter warp for narrow rows) per row, 16-byte + weight loads, the window's q8_1 activations copied once per workgroup into shared memory as an int8 plane, the dot + on `STRATA_DP4A` (vmad), a shuffle sum - no barrier per row. Shapes it declines (a 6144-wide row with 7-8 columns) + keep the usual kernel. Not bitwise the exact kernels (the per-32 products are added in another order). The packed + copies cost their size in VRAM beside the GGUF layout the prompt path reads (Flash-Next: 2.9 GiB of dense + projections over the stages and 0.6 GiB for the head). +- The GSQ-RCO packs have no Q8_0 dense matrices, so the kernel needs a shard whose dense projections and head are + Q8_0: `python tools/q8_dense_gguf.py -00001-of-00002.gguf ` writes one (+3.5 GiB; the experts keep + their offsets, so the native pack is reused; the other shards are hard-linked beside it). Point `--native` and + `--ple-gguf` at the new folder. Requantizing costs at most 0.4% of a tensor's |w|max (Q8_0 is finer than the + sources). +- IQ3_XXS's codebook and sign-mask tables are staged in shared memory by the grouped expert kernels on compute + capability 6.x (ported from shinbunbun/llama-cpp-p100-patches 29 and 30; bitwise the same output; + `STRATA_IQ_STAGE_GRID18=0|1` forces it off or on, on any card). Within noise on the PH402 (+0-4%). + +Measured on a PH402 SKU 200 (two boards, four GP100 dies of 48 SMs and 32 GB HBM2), application clocks locked at +1050 MHz, Windows 11, driver 581.80 (TCC), CUDA 12.9, engine 0.1.40.2; Flash-Next IQ3_XXS, 32K, `--layer-split 12,24,36 +--prefill 2048`; greedy, 256 tokens, medians of 2-3 interleaved starts, decode tok/s: + +| | ~10.7K-token document | the same, cached | short reasoning | code | mean | +| --- | ---: | ---: | ---: | ---: | ---: | +| GSQ-RCO shard, exact kernels | 28.8 | 29.4 | 28.4 | 26.8 | 28.3 | +| Q8_0 dense shard, `STRATA_Q8_PACKED=1` | 27.5 | 31.0 | 34.4 | 31.8 | 31.1 | +| Q8_0 dense shard, `STRATA_Q8_SM60=1` | 37.5 | 38.4 | 41.2 | 38.5 | 38.9 | + +GPU time per verify window (`STRATA_VERIFY_PROFILE`): dense projections 19.2 -> 11.2 ms, head 4.25 -> 2.1 ms; the +draft policy then picks longer windows (2.10 -> 2.31 tokens per window). Prompt reads are unchanged (437-438 tok/s at +10.7K). `tools/q8_sm60_check.cu` checks the kernel against a CPU reference on these shapes (1-8 columns) and times it. + +Two things that mattered as much on this card: its default application clock is 759 MHz, and a layer split leaves +each die idle most of a window, so the dies decode below 1050 MHz unless the clocks are locked +(`nvidia-smi -i -ac 715,1050` as administrator; 25.0 -> 29.1 tok/s at 10.7K context). And a second engine on +the same PC that pins its threads to the same logical CPUs halves this one's decode while it runs (the host thread +is time-sliced); keeping the two on different logical CPUs (SMT siblings) avoided it. + A/B switches: `STRATA_DEQUANT_WIDE=0`, `STRATA_SM61_TABLE=0` (sm_61: the kernels 0.1.43.1 ran), `STRATA_DENSE_F32=1` (Pascal, opt-in), -`STRATA_BF16_TC=0|1`, `STRATA_PROMPT_ATTN_OLD=1` (the decode kernel for prompts), `STRATA_ATTN_PRE75=0` +`STRATA_Q8_SM60=0|1` (Pascal GP100, opt-in), `STRATA_BF16_TC=0|1`, `STRATA_PROMPT_ATTN_OLD=1` (the decode kernel for prompts), `STRATA_ATTN_PRE75=0` (#540's kernel off; on gfx103x with HIP that kernel is the default, see the AMD table above, and `=1` turns it on for another wave32 AMD card). [NVIDIA_V100.md](NVIDIA_V100.md) has the V100 build, its measurements and the parity test. diff --git a/include/strata/kernels/native_mmvq.hpp b/include/strata/kernels/native_mmvq.hpp index fef71027..b9534ebf 100644 --- a/include/strata/kernels/native_mmvq.hpp +++ b/include/strata/kernels/native_mmvq.hpp @@ -102,6 +102,11 @@ 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); +/// STRATA_Q8_SM60=1 (opt-in, Pascal GP100): every Q8_0 dense matrix is packed as above whatever its shape, and the +/// Q8_0 decode GEMVs run a kernel written for compute capability 6.0 (q8_sm60.cuh; not bitwise the exact kernels). +/// native_q8_0_sm60_pack packs a device matrix here (the head) and owns the copy until native_q8_0_sm60_release. +bool native_q8_0_sm60_pack(const void* weights, int n_in, int n_out, const char* what); +void native_q8_0_sm60_release(const void* 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 diff --git a/src/core/native_head.cpp b/src/core/native_head.cpp index 8e239d3d..a1fb1944 100644 --- a/src/core/native_head.cpp +++ b/src/core/native_head.cpp @@ -18,6 +18,7 @@ NativeHead::~NativeHead() { void NativeHead::unload() { if (weights_) strata::kernels::native_q6_k_unpack(weights_); + if (weights_) strata::kernels::native_q8_0_sm60_release(weights_); if (scratch_) cudaFree(scratch_); if (weights_) cudaFree(weights_); scratch_ = nullptr; @@ -73,6 +74,8 @@ bool NativeHead::load(const std::vector& shards, int64_t n_in, int6 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"); + if (type_ == 8) // STRATA_Q8_SM60=1 (a no-op otherwise); the MTP draft head reads the same matrix + strata::kernels::native_q8_0_sm60_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 d537fd5f..c83323d1 100644 --- a/src/kernels/cuda/native_mmvq.cu +++ b/src/kernels/cuda/native_mmvq.cu @@ -1726,6 +1726,25 @@ 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_SM60=1 (opt-in, written for Pascal GP100): every Q8_0 dense matrix and the head get the packed planes +// below and run q8sm60::kernel on them (q8_sm60.cuh) instead of the exact kernels. +bool q8_sm60_on() { +#if defined(__HIPCC__) + return false; // a CUDA kernel for one NVIDIA chip: HIP builds never compile it +#else + static const bool on = [] { + const char* v = std::getenv("STRATA_Q8_SM60"); + const bool yes = v && v[0] == '1' && v[1] == '\0'; + if (yes) std::fprintf(stderr, "strata q8 sm60: Q8_0 decode GEMVs on the Pascal kernel (STRATA_Q8_SM60=1)\n"); + return yes; + }(); + return on; +#endif +} +#if !defined(__HIPCC__) +#include "q8_sm60.cuh" +#endif + // ============================ 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) @@ -1825,8 +1844,30 @@ void q8_packed_launch(const Q8Packed& w, const Q81Block* x, float* y, cudaStream persist ? grid : w.n_out); } +bool q8_packed_shape(int n_in, int n_out) { // the shapes native_q8_0_packed_kernel was measured on + return n_in > 0 && n_in % 32 == 0 && n_in / 32 >= 2 * WARPS * WARP / 8 && n_in <= Q8P_PERSIST_MAX_IN && + n_out >= 2048; +} + 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 !defined(__HIPCC__) + if (q8_sm60_on() && !registry.empty()) { + const auto found = registry.find(weights); + if (found != registry.end() && found->second.n_in == n_in && found->second.n_out == n_out) { + validate_pointer(x_q8_1); + validate_pointer(y); + validate_stream(stream); + if (q8sm60::launch(found->second.qs, found->second.d, static_cast(x_q8_1), y, n_in, + n_out, ncols, static_cast(stream))) { + launch_check(); + return true; + } + // a shape the Pascal kernel declines: the exact packed kernel only where it was measured, else the GGUF layout + if (!q8_packed_shape(n_in, n_out)) return false; + } + } +#endif 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; @@ -1992,12 +2033,61 @@ bool native_q8_0_packed_enabled() { const char* v = std::getenv("STRATA_Q8_PACKED"); return v && v[0] == '1' && v[1] == '\0'; }(); - return enabled; + return enabled || q8_sm60_on(); } 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; + if (q8_sm60_on()) return n_in >= 128 && n_in % 32 == 0 && n_out > 0; // the Pascal kernel takes any of them + return q8_packed_shape(n_in, n_out); +} + +namespace { +std::unordered_map& q8_sm60_owned() { // packed copies made here (the head), freed by release + static std::unordered_map owned; + return owned; +} +} // namespace + +bool native_q8_0_sm60_pack(const void* weights, int n_in, int n_out, const char* what) { +#if defined(__HIPCC__) + (void) weights; (void) n_in; (void) n_out; (void) what; + return false; +#else + if (!q8_sm60_on() || !weights || !native_q8_0_packed_eligible(n_in, n_out)) return false; + if (q8_packed_registry().count(weights)) return true; + const std::size_t count = std::size_t(n_in / 32) * std::size_t(n_out); + const std::size_t bytes = count * 34; + void* packed = nullptr; + if (cudaMalloc(&packed, bytes) != cudaSuccess) { + cudaGetLastError(); + std::fprintf(stderr, "strata q8 sm60: no VRAM for the packed %s (%.0f MiB); it keeps the GGUF layout\n", what, + double(bytes) / 1048576.0); + return false; + } + auto* qs = static_cast(packed); + auto* d = reinterpret_cast(qs + std::size_t(n_in) * n_out); + q8sm60::pack_kernel<<>>(static_cast(weights), qs, d, count); + if (cudaDeviceSynchronize() != cudaSuccess) { + cudaGetLastError(); + cudaFree(packed); + std::fprintf(stderr, "strata q8 sm60: packing the %s failed; it keeps the GGUF layout\n", what); + return false; + } + q8_packed_registry()[weights] = Q8Packed{qs, d, n_in, n_out}; + q8_sm60_owned()[weights] = packed; + std::fprintf(stderr, "strata q8 sm60: packed %s (%d x %d, %.0f MiB more VRAM)\n", what, n_out, n_in, + double(bytes) / 1048576.0); + return true; +#endif +} + +void native_q8_0_sm60_release(const void* weights) { + auto& owned = q8_sm60_owned(); + const auto it = owned.find(weights); + if (it == owned.end()) return; + q8_packed_registry().erase(weights); + cudaFree(it->second); + owned.erase(it); } void native_q8_0_pack_host(const void* gguf_blocks, void* out, int n_in, int n_out) { diff --git a/src/kernels/cuda/q8_sm60.cuh b/src/kernels/cuda/q8_sm60.cuh new file mode 100644 index 00000000..a45b8409 --- /dev/null +++ b/src/kernels/cuda/q8_sm60.cuh @@ -0,0 +1,148 @@ +// src/kernels/cuda/q8_sm60.cuh - a Q8_0 decode GEMV for Pascal GP100 (compute capability 6.0), opt-in with +// STRATA_Q8_SM60=1. Included by native_mmvq.cu, and by a standalone parity/speed check, so both run this code. +// +// Reads the packed planes of STRATA_Q8_PACKED (the SAME int8 values row-major, n_in bytes per row, then one fp16 scale +// per 32 of them) for every Q8_0 dense matrix and the head, whatever their shape. Why the packed kernel above is slow +// on a GP100 die (measured on PH402, 1050 MHz: ~137 GB/s for the dense projections, ~160 for the head, against +// 220-270 for this layout): one workgroup per row, eight bytes per thread per pass and a __syncthreads() per row - a +// 2560-wide row is 80 blocks, so the reduction costs more than the row - and the window's activations read as single +// ints, because a q8_1 block is 36 bytes and its values start at byte 4. +// +// Here: +// * a workgroup first copies the window's activations into shared memory as an int8 plane per column and a float +// scale per 32 (once; the workgroup then loops over rows), so every activation read is a 16-byte shared load; +// * TPR threads own a row (a whole warp for n_in >= 2048, a half or a quarter for narrower rows) and read its +// weights 16 bytes at a time through the read-only cache; the dot of 4 ints is STRATA_DP4A (vmad on sm_60); +// * the sum is a shuffle within those TPR lanes - no shared memory, no barrier per row. +// The per-32 products are added in another order than the exact kernels', so outputs are not bitwise theirs (float +// rounding only; the int8 dots are exact). +#pragma once + +namespace q8sm60 { + +constexpr int THREADS = 256; +constexpr std::size_t MAX_SMEM = 48 * 1024; // a Pascal workgroup's static + dynamic limit + +inline std::size_t smem_bytes(int ncols, int n_in) { + return std::size_t(ncols) * std::size_t(n_in) + std::size_t(ncols) * std::size_t(n_in / 32) * sizeof(float); +} + +template +__launch_bounds__(THREADS) +__global__ void kernel(const int8_t* __restrict__ qs, const half* __restrict__ dpl, const Q81Block* __restrict__ x, + float* __restrict__ y, int n_in, int n_out) { + extern __shared__ int4 q8sm60_smem[]; + int8_t* sx = reinterpret_cast(q8sm60_smem); // [NCOLS][n_in] + float* sd = reinterpret_cast(sx + std::size_t(NCOLS) * n_in); // [NCOLS][n_in / 32] + const int nb = n_in / 32; + for (int b = int(threadIdx.x); b < NCOLS * nb; b += THREADS) { // column j = b / nb, block b % nb + const Q81Block* xb = x + b; + const int* src = reinterpret_cast(xb->qs); + int* dst = reinterpret_cast(sx + std::size_t(b) * 32); +#pragma unroll + for (int i = 0; i < 8; ++i) dst[i] = src[i]; + sd[b] = __low2float(xb->ds); + } + __syncthreads(); + + constexpr int RPB = THREADS / TPR; + const int lane = int(threadIdx.x) % TPR; + const int rloc = int(threadIdx.x) / TPR; + const int nch = n_in / 16; // 16-byte chunks, two per block + const int groups = (n_out + RPB - 1) / RPB; + for (int g = int(blockIdx.x); g < groups; g += int(gridDim.x)) { + const int row = g * RPB + rloc; + float acc[NCOLS]; +#pragma unroll + for (int j = 0; j < NCOLS; ++j) acc[j] = 0.0f; + if (row < n_out) { + const int4* w = reinterpret_cast(qs + std::size_t(row) * n_in); + const half* d = dpl + std::size_t(row) * nb; + for (int c = lane; c < nch; c += TPR) { + const int4 wv = __ldg(w + c); + const float dw = __half2float(d[c >> 1]); +#pragma unroll + for (int j = 0; j < NCOLS; ++j) { + const int4 xv = reinterpret_cast(sx + std::size_t(j) * n_in)[c]; + int s = STRATA_DP4A(wv.x, xv.x, 0); + s = STRATA_DP4A(wv.y, xv.y, s); + s = STRATA_DP4A(wv.z, xv.z, s); + s = STRATA_DP4A(wv.w, xv.w, s); + acc[j] += dw * sd[j * nb + (c >> 1)] * float(s); + } + } + } +#pragma unroll + for (int j = 0; j < NCOLS; ++j) { // every lane takes part, row or not + float v = acc[j]; +#pragma unroll + for (int o = TPR / 2; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o, TPR); + if (lane == 0 && row < n_out) y[std::size_t(j) * n_out + row] = v; + } + } +} + +// One workgroup per SM would leave too few rows in flight on a 48-SM die; four per SM is what the shapes of +// Qwen3.8-Flash-Next measured best (STRATA_Q8_SM60_BPS overrides it). +inline int blocks_per_sm() { + static const int v = [] { + const char* e = std::getenv("STRATA_Q8_SM60_BPS"); + const int n = e ? std::atoi(e) : 0; + return n > 0 ? n : 4; + }(); + return v; +} + +inline int sm_count() { + int dev = 0, n = 0; + if (cudaGetDevice(&dev) != cudaSuccess || cudaDeviceGetAttribute(&n, cudaDevAttrMultiProcessorCount, dev) != cudaSuccess) + return 48; + return n > 0 ? n : 48; +} + +template +void launch_one(const int8_t* qs, const half* d, const Q81Block* x, float* y, int n_in, int n_out, cudaStream_t s) { + constexpr int RPB = THREADS / TPR; + const int groups = (n_out + RPB - 1) / RPB; + const int grid = (std::min)(groups, sm_count() * blocks_per_sm()); + kernel<<>>(qs, d, x, y, n_in, n_out); +} + +template +void launch_cols(const int8_t* qs, const half* d, const Q81Block* x, float* y, int n_in, int n_out, cudaStream_t s) { + if (n_in >= 2048) launch_one(qs, d, x, y, n_in, n_out, s); + else if (n_in >= 1024) launch_one(qs, d, x, y, n_in, n_out, s); + else launch_one(qs, d, x, y, n_in, n_out, s); +} + +// false: a shape this kernel does not take (the caller runs its usual kernel) +inline bool launch(const int8_t* qs, const half* d, const Q81Block* x, float* y, int n_in, int n_out, int ncols, + cudaStream_t s) { + if (n_in % 32 != 0 || n_in < 128 || ncols < 1 || ncols > 8 || smem_bytes(ncols, n_in) > MAX_SMEM) return false; + switch (ncols) { + case 1: launch_cols<1>(qs, d, x, y, n_in, n_out, s); break; + case 2: launch_cols<2>(qs, d, x, y, n_in, n_out, s); break; + case 3: launch_cols<3>(qs, d, x, y, n_in, n_out, s); break; + case 4: launch_cols<4>(qs, d, x, y, n_in, n_out, s); break; + case 5: launch_cols<5>(qs, d, x, y, n_in, n_out, s); break; + case 6: launch_cols<6>(qs, d, x, y, n_in, n_out, s); break; + case 7: launch_cols<7>(qs, d, x, y, n_in, n_out, s); break; + default: launch_cols<8>(qs, d, x, y, n_in, n_out, s); break; + } + return true; +} + +// GGUF Q8_0 blocks (34 bytes, 2-byte aligned) -> the packed planes, on the device (the head's 0.6 GiB stays off the host) +__global__ void pack_kernel(const Q80Block* __restrict__ blocks, int8_t* __restrict__ qs, half* __restrict__ d, + std::size_t count) { + const std::size_t b = std::size_t(blockIdx.x) * blockDim.x + threadIdx.x; + if (b >= count) return; + const Q80Block& src = blocks[b]; + const uint16_t* in = reinterpret_cast(src.qs); + uint16_t* out = reinterpret_cast(qs + b * 32); +#pragma unroll + for (int i = 0; i < 16; ++i) out[i] = in[i]; + d[b] = src.d; +} + +} // namespace q8sm60 diff --git a/tools/q8_dense_gguf.py b/tools/q8_dense_gguf.py new file mode 100644 index 00000000..e094cd32 --- /dev/null +++ b/tools/q8_dense_gguf.py @@ -0,0 +1,146 @@ +"""tools/q8_dense_gguf.py - a copy of a model's first shard whose natively served dense projections and head are Q8_0, +for the Pascal GP100 decode kernel (STRATA_Q8_SM60=1, docs/OLDER_GPUS.md). + +The GSQ-RCO packs keep those matrices in K- and i-quants (Q6_K, IQ4_XS, Q4_K, IQ3_S, Q5_K, Q2_0, IQ4_NL), whose +decode is what a GP100 die is slowest at; STRATA_Q8_SM60 only runs Q8_0 matrices. This writes: + + * the tensor-info block with the SAME byte length: names and dims are unchanged, only the u32 type and the u64 + offset of each converted tensor change, so the data section starts where it did and every other tensor - the + routed experts above all - keeps its absolute offset. An existing native pack (its native_experts.txt) stays + valid; nothing is repacked. + * the original data section, then each converted tensor's Q8_0 blocks appended (the old bytes stay, unused). + Qwen3.8-Flash-Next IQ3_XXS: 301 tensors, +3.5 GiB, the worst requantization error 0.41% of a tensor's |w|max + (Q8_0 is finer than every source format). + +The other shards of the model are hard-linked into the output folder (--copy copies them): the engine finds them +beside --native, so --ple-gguf must name the one in the new folder too (it refuses two shard 2s). + + python tools/q8_dense_gguf.py /-00001-of-00002.gguf [--copy] + +Then point the config's --native and --ple-gguf at the new folder and run the engine with STRATA_Q8_SM60=1. +""" +from __future__ import annotations + +import argparse +import os +import re +import shutil +import struct +import sys +import time +from pathlib import Path + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import _paths # noqa: E402 + +_paths.add_gguf_py() +from gguf import GGUFReader, GGMLQuantizationType as QT # noqa: E402 +from gguf.quants import dequantize, quantize # noqa: E402 +from gguf_writer import dequantize_q2_0 # noqa: E402 + +# what src/core/native_dense.cpp serves natively (eligible()), and the head +SUFFIXES = (".attn_qkv.weight", ".attn_gate.weight", ".ssm_out.weight", ".attn_q.weight", ".attn_k.weight", + ".attn_v.weight", ".attn_output.weight", ".ffn_gate_shexp.weight", ".ffn_up_shexp.weight", + ".ffn_down_shexp.weight") +Q2_0 = 42 # GSQ's 2-bit type: gguf-py has no member for it + + +def is_target(name: str) -> bool: + return name == "output.weight" or (name.startswith("blk.") and name.endswith(SUFFIXES)) + + +def to_f32(t) -> np.ndarray: + ne0, ne1 = int(t.shape[0]), int(t.shape[1]) + raw = np.asarray(t.data) + if int(t.tensor_type) == Q2_0: + return np.asarray(dequantize_q2_0(raw.tobytes()), dtype=np.float32).reshape(ne1, ne0) + return np.asarray(dequantize(raw, t.tensor_type), dtype=np.float32).reshape(ne1, ne0) + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("shard1", type=Path, help="the model's first GGUF shard (the one --native names)") + ap.add_argument("out_dir", type=Path, help="folder for the new shard 1 and the other shards' links") + ap.add_argument("--copy", action="store_true", help="copy the other shards instead of hard-linking them") + a = ap.parse_args() + src = a.shard1.resolve() + out = a.out_dir.resolve() + if out == src.parent: + sys.exit("the output folder must not be the model's own folder") + dst = out / src.name + + t0 = time.time() + r = GGUFReader(src) + align, data_start, src_size = r.alignment, r.data_offset, os.path.getsize(src) + mm = r.data + jobs = [] + for t in r.tensors: + if not is_target(t.name) or int(t.tensor_type) == int(QT.Q8_0): + continue + p = t.field.offset # the tensor-info entry: name, n_dims, dims, type, offset + nlen = struct.unpack_from(" q8sm60::pack_kernel -> the kernel, against a CPU double reference of +// sum over blocks of d_w * d_x * dot_int8, for 1..8 columns (max relative error < 1e-5). Speed: a 1 GiB rotation so +// the weights come from DRAM, as in the engine. No CMake target; build by hand: +// +// nvcc -O3 -arch=sm_60 -std=c++17 -Iinclude -Isrc/kernels/cuda tools/q8_sm60_check.cu -o q8_sm60_check && ./q8_sm60_check +// +// Exit status 0 = every case within tolerance and no CUDA error. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#define CK(x) do { cudaError_t e_ = (x); if (e_ != cudaSuccess) { printf("CUDA %s at %d\n", cudaGetErrorString(e_), __LINE__); exit(1); } } while (0) +struct Q81Block { half2 ds; int8_t qs[32]; }; +struct Q80Block { half d; int8_t qs[32]; }; +#include "strata/kernels/dp4a.hpp" +#include "q8_sm60.cuh" + +static float h2f(half h) { return __half2float(h); } + +static bool parity(int n_in, int n_out, int ncols) { + const int nb = n_in / 32; + std::vector w((size_t) n_out * nb); + std::vector x((size_t) ncols * nb); + srand(n_in * 7 + n_out + ncols); + for (auto& b : w) { b.d = __float2half((rand() % 1000 + 1) * 1e-5f); for (auto& q : b.qs) q = (int8_t) (rand() % 255 - 127); } + for (auto& b : x) { b.ds = __halves2half2(__float2half((rand() % 1000 + 1) * 1e-4f), __float2half(0.f)); for (auto& q : b.qs) q = (int8_t) (rand() % 255 - 127); } + std::vector ref((size_t) ncols * n_out); + for (int j = 0; j < ncols; ++j) for (int r = 0; r < n_out; ++r) { + double s = 0; + for (int b = 0; b < nb; ++b) { + const Q80Block& wb = w[(size_t) r * nb + b]; const Q81Block& xb = x[(size_t) j * nb + b]; + int dot = 0; for (int i = 0; i < 32; ++i) dot += wb.qs[i] * xb.qs[i]; + s += (double) h2f(wb.d) * __low2float(xb.ds) * dot; + } + ref[(size_t) j * n_out + r] = s; + } + Q80Block* dw; Q81Block* dx; float* dy; int8_t* qs; + CK(cudaMalloc(&dw, w.size() * sizeof(Q80Block))); CK(cudaMemcpy(dw, w.data(), w.size() * sizeof(Q80Block), cudaMemcpyHostToDevice)); + CK(cudaMalloc(&dx, x.size() * sizeof(Q81Block))); CK(cudaMemcpy(dx, x.data(), x.size() * sizeof(Q81Block), cudaMemcpyHostToDevice)); + CK(cudaMalloc(&dy, ref.size() * 4)); CK(cudaMemset(dy, 0xff, ref.size() * 4)); + const size_t count = (size_t) n_out * nb; + CK(cudaMalloc(&qs, count * 34)); + half* d = reinterpret_cast(qs + (size_t) n_in * n_out); + q8sm60::pack_kernel<<>>(dw, qs, d, count); + const bool took = q8sm60::launch(qs, d, dx, dy, n_in, n_out, ncols, 0); + CK(cudaDeviceSynchronize()); + bool ok = true; + if (took) { + std::vector y(ref.size()); CK(cudaMemcpy(y.data(), dy, y.size() * 4, cudaMemcpyDeviceToHost)); + double m = 0, e = 0; for (size_t i = 0; i < y.size(); ++i) { m = std::max(m, std::fabs(ref[i])); e = std::max(e, std::fabs(y[i] - ref[i])); } + ok = e / m < 1e-5 && std::isfinite(e); + if (!ok) printf(" FAIL %d -> %d, %d cols: max rel err %.2e\n", n_in, n_out, ncols, e / m); + } + cudaFree(dw); cudaFree(dx); cudaFree(dy); cudaFree(qs); + return ok; +} + +int main() { + cudaDeviceProp p; CK(cudaGetDeviceProperties(&p, 0)); + printf("%s, %d SMs, %d MHz\n", p.name, p.multiProcessorCount, p.clockRate / 1000); + struct S { const char* name; int n_in, n_out; } shapes[] = { + {"gdn attn_qkv", 2560, 10240}, {"gdn attn_gate", 2560, 6144}, {"ssm_out / attn_output", 6144, 2560}, + {"qsa attn_q", 2560, 12288}, {"qsa attn_k / v", 2560, 512}, {"shexp gate / up", 2560, 640}, + {"shexp down", 640, 2560}, {"head", 2560, 248320}}; + bool ok = true; int checked = 0, declined = 0; + for (const S& s : shapes) for (int c = 1; c <= 8; ++c) { + if (s.n_out > 20000 && c > 2) continue; // the head's CPU reference is slow; 1-2 columns cover its path + if (q8sm60::smem_bytes(c, s.n_in) > q8sm60::MAX_SMEM) { ++declined; continue; } + ok = parity(s.n_in, s.n_out, c) && ok; ++checked; + } + printf("parity: %d shape x column cases %s (%d declined: shared memory)\n\n", checked, ok ? "PASS (max rel err < 1e-5)" : "FAIL", declined); + if (!ok) return 1; + + const size_t POOL = 1ull << 30; + int8_t* pool; CK(cudaMalloc(&pool, POOL)); CK(cudaMemset(pool, 1, POOL)); + Q81Block* dx; CK(cudaMalloc(&dx, 8 * (6144 / 32) * sizeof(Q81Block))); CK(cudaMemset(dx, 0, 8 * (6144 / 32) * sizeof(Q81Block))); + float* dy; CK(cudaMalloc(&dy, (size_t) 8 * 248320 * 4)); + int8_t* head; const size_t head_bytes = (size_t) 248320 * 2560 / 32 * 34; CK(cudaMalloc(&head, head_bytes)); CK(cudaMemset(head, 0, head_bytes)); + cudaEvent_t a, b; CK(cudaEventCreate(&a)); CK(cudaEventCreate(&b)); + printf("%-22s %6s %7s |", "matrix", "n_in", "n_out"); for (int c = 1; c <= 6; ++c) printf(" T=%d us GB/s", c); printf("\n"); + for (const S& s : shapes) { + printf("%-22s %6d %7d |", s.name, s.n_in, s.n_out); + const size_t bytes = (size_t) s.n_in / 32 * 34 * s.n_out; + for (int c = 1; c <= 6; ++c) { + if (q8sm60::smem_bytes(c, s.n_in) > q8sm60::MAX_SMEM) { printf(" %14s", "-"); continue; } + const int iters = s.n_out > 20000 ? 10 : 100; + auto at = [&](int i) -> int8_t* { if (s.n_out > 20000) return head; const size_t span = (POOL - bytes) / 256; + return pool + ((size_t) i * ((bytes + 255) / 256) % span) * 256; }; + for (int i = 0; i < 3; ++i) { int8_t* q = at(i); q8sm60::launch(q, (half*) (q + (size_t) s.n_in * s.n_out), dx, dy, s.n_in, s.n_out, c, 0); } + CK(cudaEventRecord(a)); + for (int i = 0; i < iters; ++i) { int8_t* q = at(i + 3); q8sm60::launch(q, (half*) (q + (size_t) s.n_in * s.n_out), dx, dy, s.n_in, s.n_out, c, 0); } + CK(cudaEventRecord(b)); CK(cudaEventSynchronize(b)); + float ms; CK(cudaEventElapsedTime(&ms, a, b)); const double us = ms * 1000.0 / iters; + printf(" %7.1f %6.0f", us, bytes / (us * 1e3)); + } + printf("\n"); + } + return 0; +} From 080abf86a41345297acfa497fab781b9263acd06 Mon Sep 17 00:00:00 2001 From: ruibeikaa <126486262+ruibeikaa@users.noreply.github.com> Date: Wed, 7 Oct 2026 21:12:28 +0000 Subject: [PATCH 24/36] tools/q8_dense_gguf.py: convert every shard that holds dense matrices The tool converted only the shard it was given and hard-linked the others, which is enough for Flash-Next (every natively served projection and the head are in shard 1) but not for Swift 1.5 IQ3_XXS, which keeps 78 of them in shard 1 and 223 in shard 2: one run left three quarters of them in their K- / i-quants, silently, and the kernel only runs Q8_0 matrices. Now any shard of the model may be named; every shard that holds such a matrix is written as before (same tensor-info length, Q8_0 blocks appended, offsets checked) and the others are hard-linked. Checked: Swift 1.5 IQ3_XXS in one run gives both shards byte-identical to two single-shard runs (301 tensors); Flash-Next IQ3_XXS converts 301 tensors in shard 1 and links shard 2. --- docs/OLDER_GPUS.md | 7 +-- tools/q8_dense_gguf.py | 96 ++++++++++++++++++++++++++---------------- 2 files changed, 63 insertions(+), 40 deletions(-) diff --git a/docs/OLDER_GPUS.md b/docs/OLDER_GPUS.md index b653dcd0..1ed72cc6 100644 --- a/docs/OLDER_GPUS.md +++ b/docs/OLDER_GPUS.md @@ -108,9 +108,10 @@ and i-quant blocks (Q6_K, IQ4_XS, Q4_K, IQ3_S, ...) one int at a time. Two chang keep the usual kernel. Not bitwise the exact kernels (the per-32 products are added in another order). The packed copies cost their size in VRAM beside the GGUF layout the prompt path reads (Flash-Next: 2.9 GiB of dense projections over the stages and 0.6 GiB for the head). -- The GSQ-RCO packs have no Q8_0 dense matrices, so the kernel needs a shard whose dense projections and head are - Q8_0: `python tools/q8_dense_gguf.py -00001-of-00002.gguf ` writes one (+3.5 GiB; the experts keep - their offsets, so the native pack is reused; the other shards are hard-linked beside it). Point `--native` and +- The GSQ-RCO packs have no Q8_0 dense matrices, so the kernel needs a copy of the model whose dense projections and head are + Q8_0: `python tools/q8_dense_gguf.py -00001-of-00002.gguf ` writes one: every shard that holds + such matrices is converted (Swift 1.5 keeps them in both of its shards) and the rest are hard-linked beside them + (+3.5 GiB; the experts keep their offsets, so the native pack is reused). Point `--native` and `--ple-gguf` at the new folder. Requantizing costs at most 0.4% of a tensor's |w|max (Q8_0 is finer than the sources). - IQ3_XXS's codebook and sign-mask tables are staged in shared memory by the grouped expert kernels on compute diff --git a/tools/q8_dense_gguf.py b/tools/q8_dense_gguf.py index e094cd32..e39f2351 100644 --- a/tools/q8_dense_gguf.py +++ b/tools/q8_dense_gguf.py @@ -1,8 +1,10 @@ -"""tools/q8_dense_gguf.py - a copy of a model's first shard whose natively served dense projections and head are Q8_0, -for the Pascal GP100 decode kernel (STRATA_Q8_SM60=1, docs/OLDER_GPUS.md). +"""tools/q8_dense_gguf.py - a copy of a model whose natively served dense projections and head are Q8_0, for the +Pascal GP100 decode kernel (STRATA_Q8_SM60=1, docs/OLDER_GPUS.md). The GSQ-RCO packs keep those matrices in K- and i-quants (Q6_K, IQ4_XS, Q4_K, IQ3_S, Q5_K, Q2_0, IQ4_NL), whose -decode is what a GP100 die is slowest at; STRATA_Q8_SM60 only runs Q8_0 matrices. This writes: +decode is what a GP100 die is slowest at; STRATA_Q8_SM60 only runs Q8_0 matrices. Every shard of the model is +handled, because a model may keep dense matrices in more than one (Swift 1.5 IQ3_XXS: 78 in shard 1, 223 in +shard 2). A shard that holds any of them is written as: * the tensor-info block with the SAME byte length: names and dims are unchanged, only the u32 type and the u64 offset of each converted tensor change, so the data section starts where it did and every other tensor - the @@ -12,12 +14,13 @@ decode is what a GP100 die is slowest at; STRATA_Q8_SM60 only runs Q8_0 matrices Qwen3.8-Flash-Next IQ3_XXS: 301 tensors, +3.5 GiB, the worst requantization error 0.41% of a tensor's |w|max (Q8_0 is finer than every source format). -The other shards of the model are hard-linked into the output folder (--copy copies them): the engine finds them -beside --native, so --ple-gguf must name the one in the new folder too (it refuses two shard 2s). +A shard that holds none is hard-linked into the output folder (--copy copies it): the engine finds the shards beside +--native, so --native and --ple-gguf must both name files in the new folder (it refuses two shard 2s). python tools/q8_dense_gguf.py /-00001-of-00002.gguf [--copy] -Then point the config's --native and --ple-gguf at the new folder and run the engine with STRATA_Q8_SM60=1. +Any shard of the model may be named. Then point the config's --native and --ple-gguf at the new folder and run the +engine with STRATA_Q8_SM60=1. """ from __future__ import annotations @@ -59,23 +62,17 @@ def to_f32(t) -> np.ndarray: return np.asarray(dequantize(raw, t.tensor_type), dtype=np.float32).reshape(ne1, ne0) -def main() -> int: - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("shard1", type=Path, help="the model's first GGUF shard (the one --native names)") - ap.add_argument("out_dir", type=Path, help="folder for the new shard 1 and the other shards' links") - ap.add_argument("--copy", action="store_true", help="copy the other shards instead of hard-linking them") - a = ap.parse_args() - src = a.shard1.resolve() - out = a.out_dir.resolve() - if out == src.parent: - sys.exit("the output folder must not be the model's own folder") - dst = out / src.name +def shards_of(path: Path) -> list[Path]: + """Every shard of the model `path` belongs to (just `path` for an unsplit file).""" + m = re.match(r"(.*-)(\d{5})-of-(\d{5})(\.gguf)$", path.name) + if not m: + return [path] + return [path.parent / f"{m[1]}{k:05d}-of-{m[3]}{m[4]}" for k in range(1, int(m[3]) + 1)] - t0 = time.time() - r = GGUFReader(src) - align, data_start, src_size = r.alignment, r.data_offset, os.path.getsize(src) - mm = r.data - jobs = [] + +def jobs_of(r) -> list: + """The shard's convertible tensors and where each one's type/offset fields sit in its tensor-info block.""" + data_start, mm, jobs = r.data_offset, r.data, [] for t in r.tensors: if not is_target(t.name) or int(t.tensor_type) == int(QT.Q8_0): continue @@ -89,8 +86,12 @@ def main() -> int: print(f" {t.name}: rows of {int(t.shape[0])} are not whole Q8_0 blocks, kept") continue jobs.append((t, p)) - print(f"{src.name}: {len(r.tensors)} tensors, {len(jobs)} to convert to Q8_0", flush=True) + return jobs + +def convert(src: Path, dst: Path, r, jobs) -> int: + t0 = time.time() + align, data_start, src_size = r.alignment, r.data_offset, os.path.getsize(src) blobs, worst = [], 0.0 for t, p in jobs: f = to_f32(t) @@ -99,10 +100,9 @@ def main() -> int: back = dequantize(q, QT.Q8_0).reshape(f.shape) worst = max(worst, float(np.abs(back - f).max() / max(float(np.abs(f).max()), 1e-30))) blobs.append((t, p, q)) - print(f"converted in {time.time() - t0:.0f} s; worst requantization error {worst:.2e} of a tensor's |w|max; " + print(f" converted in {time.time() - t0:.0f} s; worst requantization error {worst:.2e} of a tensor's |w|max; " f"{sum(b[2].nbytes for b in blobs) / 2**30:.2f} GiB to append", flush=True) - out.mkdir(parents=True, exist_ok=True) tmp = dst.with_name(dst.name + ".part") shutil.copyfile(src, tmp) with open(tmp, "r+b") as fh: @@ -125,20 +125,42 @@ def main() -> int: assert t.tensor_type == QT.Q8_0 and np.array_equal(np.asarray(t.data).view(np.uint8).reshape(-1), conv[t.name]), t.name else: assert t.tensor_type == orig[t.name].tensor_type and t.data_offset == orig[t.name].data_offset, t.name - print(f"wrote {dst} ({os.path.getsize(dst) / 2**30:.2f} GiB): {len(conv)} converted, {len(v.tensors) - len(conv)} " + print(f" wrote {dst} ({os.path.getsize(dst) / 2**30:.2f} GiB): {len(conv)} converted, {len(v.tensors) - len(conv)} " "untouched, offsets checked", flush=True) + return len(conv) - m = re.match(r"(.*-)(\d{5})-of-(\d{5})(\.gguf)$", src.name) - if m: - for k in range(1, int(m[3]) + 1): - name = f"{m[1]}{k:05d}-of-{m[3]}{m[4]}" - if k == int(m[2]) or (out / name).exists(): - continue - if a.copy: - shutil.copyfile(src.parent / name, out / name) - else: - os.link(src.parent / name, out / name) - print(f"{'copied' if a.copy else 'linked'} {name}") + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("shard", type=Path, help="any GGUF shard of the model (or the model's only file)") + ap.add_argument("out_dir", type=Path, help="folder for the converted shards and the others' links") + ap.add_argument("--copy", action="store_true", help="copy the shards with nothing to convert instead of linking them") + a = ap.parse_args() + out = a.out_dir.resolve() + shards = shards_of(a.shard.resolve()) + if out == shards[0].parent: + sys.exit("the output folder must not be the model's own folder") + missing = [s for s in shards if not s.is_file()] + if missing: + sys.exit(f"missing shard(s): {', '.join(str(s) for s in missing)}") + out.mkdir(parents=True, exist_ok=True) + total = 0 + for src in shards: + dst = out / src.name + r = GGUFReader(src) + jobs = jobs_of(r) + print(f"{src.name}: {len(r.tensors)} tensors, {len(jobs)} to convert to Q8_0", flush=True) + if jobs: + total += convert(src, dst, r, jobs) + continue + if dst.exists(): + dst.unlink() # a link or copy from an earlier run + if a.copy: + shutil.copyfile(src, dst) + else: + os.link(src, dst) + print(f" {'copied' if a.copy else 'linked'} (nothing to convert)", flush=True) + print(f"{total} tensors converted over {len(shards)} shard(s) in {out}") return 0 From ac35eebf30aa17a8ca170366ff608a385cdfb406 Mon Sep 17 00:00:00 2001 From: ruibeikaa <126486262+ruibeikaa@users.noreply.github.com> Date: Wed, 7 Oct 2026 22:26:45 +0000 Subject: [PATCH 25/36] sm_60: stage IQ3_S's codebook and sign masks in shared memory too IQ3_S was the one i-quant gate/up format whose codebook the grouped expert kernels still read from global memory (IQ2_XXS / IQ2_XS / IQ2_S stage theirs everywhere, IQ3_XXS on 6.x since the first commit of this branch). Its 512 codebook words are now staged per block with two 256-word tables of byte masks - IQ3_S keeps one explicit sign byte per 8 values, so the tables hold the masks of a sign byte's bits 0-3 and 4-7 - applied as (g ^ mask) + (mask & 0x01010101): every iq3s_grid byte is odd, so a negated byte never carries into the next. Bitwise the same output (iq_multi_parity and native_grouped_parity on a GP100 die, with and without STRATA_IQ_STAGE_GRID_MMVQ=1). One GP100 die, a verify window's layer of real Swift 1.5 IQ3_S experts (20 experts, 24 entries): 517 -> 393 us with Q2_0 down, 492 -> 369 us with IQ4_NL down. Swift 1.5 IQ3_XXS (13 of 48 layers IQ3_S), four GP100 dies, 1M context, decode tok/s, medians of three interleaved engine starts: 36.0 -> 37.2 (10.7K document), 36.3 -> 37.4 (cached), 43.1 -> 44.5 (reasoning), 41.6 -> 43.0 (code), with the same drafts accepted. The switch covers both formats and is renamed accordingly: stage_tables_on(), STRATA_IQ_STAGE_TABLES=1|0 (was STRATA_IQ_STAGE_GRID18). Still the default on compute capability 6.x only. --- docs/OLDER_GPUS.md | 11 +++++-- src/kernels/cuda/iq_kernels.cu | 56 +++++++++++++++++++++++++--------- 2 files changed, 49 insertions(+), 18 deletions(-) diff --git a/docs/OLDER_GPUS.md b/docs/OLDER_GPUS.md index 1ed72cc6..42eb6156 100644 --- a/docs/OLDER_GPUS.md +++ b/docs/OLDER_GPUS.md @@ -114,9 +114,14 @@ and i-quant blocks (Q6_K, IQ4_XS, Q4_K, IQ3_S, ...) one int at a time. Two chang (+3.5 GiB; the experts keep their offsets, so the native pack is reused). Point `--native` and `--ple-gguf` at the new folder. Requantizing costs at most 0.4% of a tensor's |w|max (Q8_0 is finer than the sources). -- IQ3_XXS's codebook and sign-mask tables are staged in shared memory by the grouped expert kernels on compute - capability 6.x (ported from shinbunbun/llama-cpp-p100-patches 29 and 30; bitwise the same output; - `STRATA_IQ_STAGE_GRID18=0|1` forces it off or on, on any card). Within noise on the PH402 (+0-4%). +- IQ3_XXS's and IQ3_S's codebooks and sign-mask tables are staged in shared memory by the grouped expert kernels on + compute capability 6.x (IQ3_XXS's ported from shinbunbun/llama-cpp-p100-patches 29 and 30, IQ3_S's the same for its + sign bytes; bitwise the same output; `STRATA_IQ_STAGE_TABLES=0|1` forces it off or on, on any card). IQ3_S was the + one gate/up format whose codebook those kernels still read from global memory: a verify window's layer of IQ3_S + experts (20 experts, 24 entries) takes 24% less on a GP100 die (517 -> 393 us with a Q2_0 down projection, 492 -> + 369 us with IQ4_NL), and Swift 1.5 IQ3_XXS (13 of its 48 layers are IQ3_S) decodes 3.2% faster with the settings + below at 1M context (39.3 -> 40.5 tok/s, mean of the four prompts; the same drafts accepted). IQ3_XXS's tables + alone were within noise (+0-4%). Measured on a PH402 SKU 200 (two boards, four GP100 dies of 48 SMs and 32 GB HBM2), application clocks locked at 1050 MHz, Windows 11, driver 581.80 (TCC), CUDA 12.9, engine 0.1.40.2; Flash-Next IQ3_XXS, 32K, `--layer-split 12,24,36 diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index ed1f5328..a28c974b 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -701,7 +701,7 @@ template struct Split; // per-entry ones, which call Fmt::dot per column exactly as before #242 (the launchers test kSplit at compile // time, so the multi kernels are never instantiated for a type without a Split). template inline constexpr bool kSplit = false; -template inline constexpr bool kStageIqGrid = (TY == 16 || TY == 17 || TY == 18 || TY == 22 || TY == 29); +template inline constexpr bool kStageIqGrid = (TY == 16 || TY == 17 || TY == 18 || TY == 21 || TY == 22 || TY == 29); template<> inline constexpr bool kSplit<16> = true; template<> struct Split<16> { // IQ2_XXS @@ -852,22 +852,31 @@ template<> inline constexpr bool kSplit<21> = true; template<> struct Split<21> { // IQ3_S struct W { int g[8]; int ls; float dw; }; template - __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ = nullptr) { + __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ s_grid = nullptr) { 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; + const uint32_t* grid = STAGE_GRID ? s_grid : iq3s_grid; 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); + const int2 grid_pos = make_int2(grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)], + grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]); + if constexpr (STAGE_GRID) { + // The staged tables hold the byte masks of a sign byte's bits 0-3 and 4-7; every iq3s_grid byte is + // odd, so (g ^ mask) + (mask & 0x01010101) negates the masked bytes with no carry into the next. + const uint32_t ml = s_grid[512 + signs_packed_8[l0 / 2]], mh = s_grid[768 + signs_packed_8[l0 / 2]]; + r.g[l0 + 0] = (int) (((uint32_t) grid_pos.x ^ ml) + (ml & 0x01010101u)); + r.g[l0 + 1] = (int) (((uint32_t) grid_pos.y ^ mh) + (mh & 0x01010101u)); + } else { + 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); @@ -1295,6 +1304,23 @@ __device__ __forceinline__ const uint32_t* stage_iq_grid(uint32_t* s_buf, int ti } __syncthreads(); return s_buf; + } else if constexpr (TY == 21) { + // 512 codebook words, then two 256-word tables: the byte masks of a sign byte's bits 0-3 and of its bits + // 4-7 (IQ3_S stores one sign byte per 8 values). As for IQ3_XXS, one pass per block replaces the + // per-lookup __vcmpne4 / __vsub4 chain, and the codebook reads leave global memory. + for (int i = tid; i < 512; i += nthreads) s_buf[i] = iq3s_grid[i]; + for (int u = tid; u < 256; u += nthreads) { + uint32_t ml = 0, mh = 0; +#pragma unroll + for (int i = 0; i < 4; ++i) { + ml |= (((uint32_t) u >> i) & 1u) * (0xffu << (8 * i)); + mh |= (((uint32_t) u >> (4 + i)) & 1u) * (0xffu << (8 * i)); + } + s_buf[512 + u] = ml; + s_buf[768 + u] = mh; + } + __syncthreads(); + return s_buf; } else { return nullptr; } @@ -1302,7 +1328,7 @@ __device__ __forceinline__ const uint32_t* stage_iq_grid(uint32_t* s_buf, int ti template> struct IqGridWords { - static constexpr int value = !STAGE_GRID ? 4 : (TY == 22 || TY == 29) ? 2048 : (TY == 17) ? 1024 : (TY == 16 || TY == 18) ? 512 : 4; + static constexpr int value = !STAGE_GRID ? 4 : (TY == 22 || TY == 29) ? 2048 : (TY == 17 || TY == 21) ? 1024 : (TY == 16 || TY == 18) ? 512 : 4; }; // mmvq_kernel with the columns taken NC at a time. After warp_sum every lane holds the same sum, so lane c stores @@ -2175,13 +2201,13 @@ bool g_stage_grid_mmvq = g_stage_grid && [] { const char* v = std::getenv("STRATA_IQ_STAGE_GRID_MMVQ"); return v != nullptr && v[0] == '1'; }(); -// IQ3_XXS's codebook and sign-mask tables staged in shared memory by the grouped expert kernels (the single-matrix -// mmvq does not): bitwise the same either way. Measured on Pascal GP100 only, so it is the default on compute -// capability 6.x and off elsewhere; STRATA_IQ_STAGE_GRID18=1 / 0 forces it on / off on any card. -bool stage_grid18_on() { +// IQ3_XXS's and IQ3_S's codebooks and sign-mask tables staged in shared memory by the grouped expert kernels (the +// single-matrix mmvq does not): bitwise the same either way. Measured on Pascal GP100 only, so it is the default on +// compute capability 6.x and off elsewhere; STRATA_IQ_STAGE_TABLES=1 / 0 forces it on / off on any card. +bool stage_tables_on() { if (!g_stage_grid) return false; static const int forced = [] { - const char* v = std::getenv("STRATA_IQ_STAGE_GRID18"); + const char* v = std::getenv("STRATA_IQ_STAGE_TABLES"); return (v && v[0]) ? (v[0] != '0' ? 1 : 0) : -1; }(); if (forced >= 0) return forced == 1; @@ -2897,7 +2923,7 @@ void launch_gu(dim3 grid, cudaStream_t s, const unsigned long long* grp_ptr, con if constexpr (!kSplit) native_gu_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (g_old_kernels) native_gu_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if constexpr (kStageIqGrid) { - if (!g_stage_grid || (TG == 18 && !stage_grid18_on())) { + if (!g_stage_grid || ((TG == 18 || TG == 21) && !stage_tables_on())) { if (g_no_sub16_gu) native_gu_multi_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_multi_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); return; From a87fb80e13b3f509b3bfe90e9064d6ba00ff3256 Mon Sep 17 00:00:00 2001 From: ruibeikaa <126486262+ruibeikaa@users.noreply.github.com> Date: Thu, 8 Oct 2026 02:25:00 +0000 Subject: [PATCH 26/36] sm_60: stage the IQ3 tables by default on compute capability 6.0 only The staged IQ3_XXS / IQ3_S tables trade a per-block copy and barrier for cheaper lookups, which pays only where the grouped expert kernels are decode-bound. On GP100 (6.0: no __dp4a, 70-140 GB/s) it does; on an RTX 3090 Ti (sm_86), forced on with STRATA_IQ_STAGE_TABLES=1, the same real Swift 1.5 IQ3_S layers (20 experts, 24 entries) took 3-13% longer (71-76 -> 75-84 us; those kernels read at 490-665 GB/s there) and IQ3_XXS was unchanged, the output bitwise the same. 6.1 cards (P40, GTX 10) have __dp4a and are unmeasured, so the default now asks for 6.0 rather than any 6.x; STRATA_IQ_STAGE_TABLES=1 still turns it on anywhere. docs/OLDER_GPUS.md says so, and that neither STRATA_Q8_SM60 nor the tables is measured on 6.1: both build for sm_61, and tools/q8_sm60_check.cu passes on an RTX 3090 Ti, where the kernel's dot is the hardware __dp4a. --- docs/OLDER_GPUS.md | 10 ++++++++-- src/kernels/cuda/iq_kernels.cu | 13 +++++++++---- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/docs/OLDER_GPUS.md b/docs/OLDER_GPUS.md index 42eb6156..c4cd2a73 100644 --- a/docs/OLDER_GPUS.md +++ b/docs/OLDER_GPUS.md @@ -115,13 +115,19 @@ and i-quant blocks (Q6_K, IQ4_XS, Q4_K, IQ3_S, ...) one int at a time. Two chang `--ple-gguf` at the new folder. Requantizing costs at most 0.4% of a tensor's |w|max (Q8_0 is finer than the sources). - IQ3_XXS's and IQ3_S's codebooks and sign-mask tables are staged in shared memory by the grouped expert kernels on - compute capability 6.x (IQ3_XXS's ported from shinbunbun/llama-cpp-p100-patches 29 and 30, IQ3_S's the same for its + compute capability 6.0 (IQ3_XXS's ported from shinbunbun/llama-cpp-p100-patches 29 and 30, IQ3_S's the same for its sign bytes; bitwise the same output; `STRATA_IQ_STAGE_TABLES=0|1` forces it off or on, on any card). IQ3_S was the one gate/up format whose codebook those kernels still read from global memory: a verify window's layer of IQ3_S experts (20 experts, 24 entries) takes 24% less on a GP100 die (517 -> 393 us with a Q2_0 down projection, 492 -> 369 us with IQ4_NL), and Swift 1.5 IQ3_XXS (13 of its 48 layers are IQ3_S) decodes 3.2% faster with the settings below at 1M context (39.3 -> 40.5 tok/s, mean of the four prompts; the same drafts accepted). IQ3_XXS's tables - alone were within noise (+0-4%). + alone were within noise (+0-4%). It is a trade that only pays where the decode is the limit: on an RTX 3090 Ti + (sm_86), forced on, the same IQ3_S layers took 3-13% longer (those kernels already read at 490-665 GB/s there), so + the default is 6.0 only. +- Neither change is measured on compute capability 6.1 (P40, P4, GTX 10 series), which has `__dp4a`. Both build for + sm_61, and on a card with `__dp4a` the Q8_0 kernel's dot is the hardware instruction (`tools/q8_sm60_check.cu` + passes on an RTX 3090 Ti); numbers from a 6.1 card with `STRATA_Q8_SM60=1` or `STRATA_IQ_STAGE_TABLES=1` would + show whether either helps there. Measured on a PH402 SKU 200 (two boards, four GP100 dies of 48 SMs and 32 GB HBM2), application clocks locked at 1050 MHz, Windows 11, driver 581.80 (TCC), CUDA 12.9, engine 0.1.40.2; Flash-Next IQ3_XXS, 32K, `--layer-split 12,24,36 diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index a28c974b..92328351 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -2202,8 +2202,10 @@ bool g_stage_grid_mmvq = g_stage_grid && [] { return v != nullptr && v[0] == '1'; }(); // IQ3_XXS's and IQ3_S's codebooks and sign-mask tables staged in shared memory by the grouped expert kernels (the -// single-matrix mmvq does not): bitwise the same either way. Measured on Pascal GP100 only, so it is the default on -// compute capability 6.x and off elsewhere; STRATA_IQ_STAGE_TABLES=1 / 0 forces it on / off on any card. +// single-matrix mmvq does not): bitwise the same either way. The default on compute capability 6.0 (GP100: no +// __dp4a, these kernels decode-bound at 70-140 GB/s) and off elsewhere: on an RTX 3090 Ti, where they run at +// 490-665 GB/s, the staging made the IQ3_S layers 3-13% slower, and 6.1 cards (which have __dp4a) are unmeasured. +// STRATA_IQ_STAGE_TABLES=1 / 0 forces it on / off on any card. bool stage_tables_on() { if (!g_stage_grid) return false; static const int forced = [] { @@ -2215,8 +2217,11 @@ bool stage_tables_on() { int dev = 0; if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return false; if (by_device[dev] == 0) { - int major = 0; - by_device[dev] = (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess && major == 6) ? 1 : 2; + int major = 0, minor = 0; + const bool gp100 = cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess && + cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) == cudaSuccess && + major == 6 && minor == 0; + by_device[dev] = gp100 ? 1 : 2; } return by_device[dev] == 1; } From a6bdc3fb5b85546376a162ccd593cfc086a25778 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 07:14:39 +0200 Subject: [PATCH 27/36] pf_wmma: compile the WMMA kernel bodies only for sm_70+ device passes (a multi-arch 60;70 build failed in the sm_60 pass: no nvcuda::wmma there) --- src/kernels/cuda/iq_kernels.cu | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index 92328351..632de825 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -3922,6 +3922,7 @@ __global__ void __launch_bounds__(WG_THREADS) gemm_iq_f16_grouped_kernel(int ty, const __half* __restrict__ X, int ldx, const int32_t* __restrict__ bounds, int ch_per_e, float* __restrict__ Y, int ldy) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 700 // the sm_60 pass of a multi-arch build has no nvcuda::wmma (the host never launches these there) using namespace nvcuda; constexpr int LDW = WK + 8, LDX = WG_XK + 8; extern __shared__ __align__(16) unsigned char wg_smem[]; @@ -4044,6 +4045,7 @@ __global__ void __launch_bounds__(WG_THREADS) gemm_iq_f16_grouped_kernel(int ty, } __syncthreads(); } +#endif } // ---- STRATA_PF_WMMA2=1 (opt-in): IQ2_S gate/up and IQ4_NL down, tiled like a Volta MoE kernel in the @@ -4135,6 +4137,7 @@ __global__ void __launch_bounds__(W2_NT, 2) gemm_iq_f16_w2_kernel(const uint8_t* int K, const __half* __restrict__ X, int ldx, const int32_t* __restrict__ bounds, int ch_per_e, float* __restrict__ Y, int ldy) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 700 // the sm_60 pass of a multi-arch build has no nvcuda::wmma (the host never launches these there) using namespace nvcuda; using tr = w2_traits; constexpr int NL = w2_nl(), NSUB = tr::raw_k / W2_KT; @@ -4241,6 +4244,7 @@ __global__ void __launch_bounds__(W2_NT, 2) gemm_iq_f16_w2_kernel(const uint8_t* } } } +#endif } bool w2_on() { From c0d02ba96a1ee603f08da89e63dfa576470fa840 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 15 Oct 2026 08:39:46 +0200 Subject: [PATCH 28/36] V100 fusions (#1097) behind STRATA_FUSE_DECODE=1; pf_wmma opt-in and only when every visible card is cc 7+; WMMA path skips NVFP4 layers; docs --- docs/NVIDIA_V100.md | 15 +++++- include/strata/kernels/fuse_decode.hpp | 16 ++++++ src/core/layer.cpp | 67 +++++++++++++++++--------- src/kernels/cuda/iq_kernels.cu | 6 +++ src/kernels/cuda/s2_expert_grouped.cu | 31 ++++++++---- src/kernels/cuda/shared_expert.cu | 8 ++- src/prefill/prefill.cpp | 22 ++++++--- 7 files changed, 120 insertions(+), 45 deletions(-) create mode 100644 include/strata/kernels/fuse_decode.hpp diff --git a/docs/NVIDIA_V100.md b/docs/NVIDIA_V100.md index 4a504227..b2ee3ca1 100644 --- a/docs/NVIDIA_V100.md +++ b/docs/NVIDIA_V100.md @@ -27,7 +27,7 @@ select "old" kernels everywhere: which kernel runs is decided per architecture w | Part of the prompt path | On sm_70 | | --- | --- | -| MoE experts | `gemm_iq_f16_grouped`: a group of experts per launch on the FP16 tensor cores, the weights dequantized in shared memory (+10% prompt speed against MMQ's `dp4a` kernels, [bench](../bench/results/2026-10-07-v100-prompt-experts/README.md); `STRATA_PF_WMMA=0`: MMQ) | +| MoE experts | opt-in (`STRATA_PF_WMMA=1`, only when every visible card is compute capability 7+; MMQ otherwise): `gemm_iq_f16_grouped`: a group of experts per launch on the FP16 tensor cores, the weights dequantized in shared memory (+10% prompt speed against MMQ's `dp4a` kernels, [bench](../bench/results/2026-10-07-v100-prompt-experts/README.md); FP16 activations instead of MMQ's q8_1, so the answers differ) | | Dense projections (dequantized weights) | FP16 tensor-core GEMMs (cuBLAS / CUTLASS `s884`) | | BF16 projections (hyper-connection, router, indexer, ...) | converted to FP16 and run on the FP16 tensor cores (#655, #540; `STRATA_BF16_TC=0`: cuBLAS BF16, an FP32 SIMT kernel on Volta) | | QSA attention for decode and verify windows (and prompts with `STRATA_PROMPT_ATTN_OLD=1`) | #540's kernel (fewer shuffles, bit-exact; `STRATA_ATTN_PRE75=0`: the one other cards run) | @@ -89,3 +89,16 @@ kernels' output, GPU work per verify window 22.8 -> 21.2 ms on a V100-SXM2 in th sm_70 only when `STRATA_SM70_TABLE=1` is set. They become the default once the contributor has confirmed them on a V100 with the 0.1.41 code. Without the variable sm_70 runs what 0.1.40.3 ran. The single switches (`STRATA_EXP_MODE`, `STRATA_MMVQ_IL`, `STRATA_GR_FAST`) still apply on top. + +## More opt-in switches (CUDA 12 experimental build) + +None of these is on by default. Each was measured by its contributor on a V100, not by the maintainers. + +| Switch | What it does | Contributor's number | +| --- | --- | --- | +| `STRATA_FUSE_DECODE=1` | the decode GEMV / MoE operator fusions of #1097 (gate/up + SwiGLU in one kernel, SwiGLU + quantizer in one kernel, all activation images of a vector in one pass, two BF16 projections in one kernel); bitwise the unfused kernels | 4-16 us per token saved, not visible end to end | +| `STRATA_PF_WMMA=1` | the FP16 tensor-core prompt experts (above); also takes IQ4_NL down projections (K=640, #1771) | +10% prompt speed (#1401) | +| `STRATA_PF_WMMA2=1` | a second prompt-expert kernel for IQ2_S gate/up and IQ4_NL down (#2356) | +2.5-4.3% prompt speed | +| `STRATA_ARGMAX_ROWS_SM70=1` | the multi-block greedy pick on sm_7x (#2357), bitwise the one-block pick | +0.7-0.8% decode | +| `STRATA_GR_NORM_FAST=1` | the register-split hyper-connection norm on CUDA (#2358) | +0.5-0.6% decode | +| `STRATA_Q8_GATHER_WIDE=0` | turns off the 8-wide int8 KV gather (#1095) that the experimental build uses below compute capability 7.5 | +11% on the gather kernel | diff --git a/include/strata/kernels/fuse_decode.hpp b/include/strata/kernels/fuse_decode.hpp new file mode 100644 index 00000000..04d475a7 --- /dev/null +++ b/include/strata/kernels/fuse_decode.hpp @@ -0,0 +1,16 @@ +#pragma once +// STRATA_FUSE_DECODE=1: the operator fusions of PR #1097 (gate/up GEMV + SwiGLU in one kernel, SwiGLU + intermediate +// quantizer in one kernel, every activation image of x in one pass, two BF16 projections in one kernel). They are +// compiled only into the experimental build (STRATA_EXPERIMENTAL_SM60, the CUDA 12 engine for Pascal / Volta) and are +// bitwise what the unfused sequences produce. Opt-in: unset or 0 keeps the unfused kernels. +#include + +namespace strata::kernels { +inline bool fuse_decode() { + static const bool on = [] { + const char* e = std::getenv("STRATA_FUSE_DECODE"); + return e != nullptr && e[0] == '1'; + }(); + return on; +} +} // namespace strata::kernels diff --git a/src/core/layer.cpp b/src/core/layer.cpp index e2667817..9f6be2d8 100644 --- a/src/core/layer.cpp +++ b/src/core/layer.cpp @@ -11,6 +11,7 @@ #include "strata/kernels/kv_q4.hpp" #include "strata/kernels/kv_q8.hpp" #include "strata/kernels/quantize_act.hpp" +#include "strata/kernels/fuse_decode.hpp" #include "strata/kernels/rope.hpp" #include "strata/kernels/router_top10.hpp" #include "strata/kernels/s2_gemv_q8.hpp" @@ -256,11 +257,14 @@ st_begin(layer, 8, stream); // Plan v0.3 P3: the canonical activation images only when a canonical projection reads them. if (!w_qkv->native_data || !w_gate->native_data) { #if defined(STRATA_EXPERIMENTAL_SM60) + if (strata::kernels::fuse_decode()) { quantize_act_images(mixed, g.n_embd, b.x_q8_0, b.x_q8k, nullptr, stream); // ONE pass, was two kernels -#else + } else +#endif + { quantize_q8_K(mixed, b.x_q8k, g.n_embd, stream); quantize_q8_0(mixed, b.x_q8_0, g.n_embd, stream); -#endif + } } st_end(layer, 8, stream); // ---- 2. qkv = wqkv @ x, with the activation THIS layer's `attn_qkv` asks for @@ -315,12 +319,15 @@ st_begin(layer, 12, stream); } else { if (!native_bf16_projections) f32_to_bf16_bulk(mixed, b.x_bf16, g.n_embd, stream); #if defined(STRATA_EXPERIMENTAL_SM60) + if (strata::kernels::fuse_decode()) { project_bf16_pair(mixed, b.x_bf16, (const uint16_t*) w_alpha->data, b.alpha, g.ssm_v_heads, (const uint16_t*) w_beta->data, b.beta, g.ssm_v_heads, g.n_embd, true, stream); -#else + } else +#endif + { project_bf16(mixed, b.x_bf16, (const uint16_t*) w_alpha->data, b.alpha, g.n_embd, g.ssm_v_heads, true, stream); project_bf16(mixed, b.x_bf16, (const uint16_t*) w_beta->data, b.beta, g.n_embd, g.ssm_v_heads, true, stream); -#endif + } } if (!fused_pre) try { if (native_gdn_enabled()) { @@ -360,11 +367,14 @@ st_end(layer, 14, stream); st_begin(layer, 15, stream); if (!w_out->native_data) { #if defined(STRATA_EXPERIMENTAL_SM60) + if (strata::kernels::fuse_decode()) { quantize_act_images(b.y, g.ssm_value_dim, b.y_q8_0, b.y_q8k, nullptr, stream); // ONE pass, was two -#else + } else +#endif + { quantize_q8_K(b.y, b.y_q8k, g.ssm_value_dim, stream); quantize_q8_0(b.y, b.y_q8_0, g.ssm_value_dim, stream); -#endif + } } if (!gemv_quantized(*w_out, p_out, f_out, b.y_q8_0, b.y_q8k, out, g.ssm_value_dim, g.n_embd, v.name("ssm_out.weight"), stream, err, b.y)) return false; st_end(layer, 15, stream); return true;} // ================================ the MoE block ================================ uint64_t moe_buffers_bytes(const ModelGeometry& g, int64_t k) { const uint64_t parts[] = { (uint64_t) g.n_embd * 2, @@ -466,12 +476,15 @@ if (w_ginp->kind != WeightKind::Bf16InF32) { err = v.name("ffn_gate_inp_s // one is wanted is a property of the TENSOR and the pack mixes them by layer, so both are produced. if (!w_sgate->native_data || !w_sup->native_data) { #if defined(STRATA_EXPERIMENTAL_SM60) + if (strata::kernels::fuse_decode()) { quantize_act_images(x, g.n_embd, b.x_q8_0, b.x_q8k, b.x_bf16, stream); // ONE pass, was three kernels -#else + } else +#endif + { f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream); quantize_q8_K(x, b.x_q8k, g.n_embd, stream); quantize_q8_0(x, b.x_q8_0, g.n_embd, stream); -#endif + } } else { f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream); } @@ -1082,17 +1095,21 @@ struct Req { const char* suf; }; const WeightRef* w_idxk = v.get("indexer.k_p // Reading one as f32 would walk 2x its length inside the arena without faulting. if (w_idxk->kind != WeightKind::Bf16InF32 || w_idxq->kind != WeightKind::Bf16InF32) { err = v.name("indexer.*_proj.weight") + " must be engine form 1 (bf16); they are " + std::to_string((int) w_idxk->kind) + " and " + std::to_string((int) w_idxq->kind); return false; } // ---- 1. the three activation formats, once each -if (!w_attnk->native_data || !w_attnv->native_data || !w_attnq->native_data) { +bool images_fused = false; #if defined(STRATA_EXPERIMENTAL_SM60) - quantize_act_images(x, g.n_embd, b.x_q8_0, b.x_q8k, - native_bf16_projections ? nullptr : b.x_bf16, stream); // ONE pass, was two or three - } else if (!native_bf16_projections) f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream); -#else +if (strata::kernels::fuse_decode() && (!w_attnk->native_data || !w_attnv->native_data || !w_attnq->native_data)) { + quantize_act_images(x, g.n_embd, b.x_q8_0, b.x_q8k, + native_bf16_projections ? nullptr : b.x_bf16, stream); // ONE pass, was two or three + images_fused = true; +} +#endif +if (!images_fused) { + if (!w_attnk->native_data || !w_attnv->native_data || !w_attnq->native_data) { quantize_q8_K(x, b.x_q8k, g.n_embd, stream); quantize_q8_0(x, b.x_q8_0, g.n_embd, stream); } if (!native_bf16_projections) f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream); -#endif +} // ---- 2. the step state: ONE H2D carries every per-token count the kernels need. Nothing below passes a // per-token scalar as an argument, which is what keeps this layer capturable. // @@ -1110,15 +1127,19 @@ if (!w_attnk->native_data || !w_attnv->native_data || !w_attnq->native_data) { } else if (cudaMemcpyAsync(st.step, st.host_step, qsa_step_bytes(), cudaMemcpyHostToDevice, (cudaStream_t) stream) != cudaSuccess || cudaMemcpyAsync(st.pos_dev, st.host_pos, (size_t) g.n_head * 4, cudaMemcpyHostToDevice, (cudaStream_t) stream) != cudaSuccess) { err = "qsa_layer: the step-state upload failed"; return false; } } // ---- 3. the indexer's RAW key (and, with the V100 switch, its QUERY in the same kernel; was two launches) +bool idx_pair = false; #if defined(STRATA_EXPERIMENTAL_SM60) -// two BF16 projections of the same x in ONE kernel: the query is needed only at step 7 and nothing in between -// touches it, so computing it here changes no order that matters; `idx_raw` is still appended at step 5. -project_bf16_pair(x, b.x_bf16, (const uint16_t*) w_idxk->data, b.idx_raw, g.idx_key_dim, - (const uint16_t*) w_idxq->data, b.q_idx, g.idx_q_heads * g.idx_key_dim, g.n_embd, - false, stream); -#else -project_bf16(x, b.x_bf16, (const uint16_t*) w_idxk->data, b.idx_raw, g.n_embd, g.idx_key_dim, false, stream); +if (strata::kernels::fuse_decode()) { + // two BF16 projections of the same x in ONE kernel: the query is needed only at step 7 and nothing in between + // touches it, so computing it here changes no order that matters; `idx_raw` is still appended at step 5. + project_bf16_pair(x, b.x_bf16, (const uint16_t*) w_idxk->data, b.idx_raw, g.idx_key_dim, + (const uint16_t*) w_idxq->data, b.q_idx, g.idx_q_heads * g.idx_key_dim, g.n_embd, + false, stream); + idx_pair = true; +} #endif +if (!idx_pair) + project_bf16(x, b.x_bf16, (const uint16_t*) w_idxk->data, b.idx_raw, g.n_embd, g.idx_key_dim, false, stream); // ---- 4. K and V, in Q8_K, then norm and rotate K only SForm f_k, f_v, f_o, f_q; if (!sform_of(*w_attnk, f_k, v.name("attn_k.weight"), err)) return false; if (!sform_of(*w_attnv, f_v, v.name("attn_v.weight"), err)) return false; if (!sform_of(*w_attno, f_o, v.name("attn_output.weight"), err)) return false; if (!sform_of(*w_attnq, f_q, v.name("attn_q.weight"), err)) return false; Planes p_k, p_v, p_o, p_q; if (!plane_ptrs(*w_attnk, v.name("attn_k.weight"), p_k, err)) return false; if (!plane_ptrs(*w_attnv, v.name("attn_v.weight"), p_v, err)) return false; if (!plane_ptrs(*w_attno, v.name("attn_output.weight"), p_o, err)) return false; if (!plane_ptrs(*w_attnq, v.name("attn_q.weight"), p_q, err)) return false; // k and v, with the activation THIS layer's tensors ask for. Both are K-quants in every QSA layer of this @@ -1171,10 +1192,8 @@ if (!gemv_quantized(*w_attnq, p_q, f_q, b.x_q8_0, b.x_q8k, b.q_full, g.n_embd, g if (cudaMemcpy2DAsync(b.qcur, (size_t) g.head_dim * 4, b.q_full, (size_t) g.head_dim * 2 * 4, (size_t) g.head_dim * 4, (size_t) g.n_head, cudaMemcpyDeviceToDevice, (cudaStream_t) stream) != cudaSuccess) { err = "qsa_layer: the q/gate split failed"; return false; } if (!normalize_rotate(b.qcur, w_qn, (int) g.n_head, (int) g.head_dim)) return false; // ---- 7. the indexer's query: with the V100 switch it was projected at step 3 (paired with the raw key); // the trunk projects it here. Either way, norm and rotate it now. -#if !defined(STRATA_EXPERIMENTAL_SM60) -project_bf16(x, b.x_bf16, (const uint16_t*) w_idxq->data, b.q_idx, g.n_embd, g.idx_q_heads * g.idx_key_dim, +if (!idx_pair) project_bf16(x, b.x_bf16, (const uint16_t*) w_idxq->data, b.q_idx, g.n_embd, g.idx_q_heads * g.idx_key_dim, false, stream); -#endif if (!normalize_rotate(b.q_idx, w_iqn, (int) g.idx_q_heads, (int) g.idx_key_dim)) return false; // ---- 8. score, select, gather, attend. `max_blocks` and `cap` are CAPACITIES from the state, not this // token's counts: a grid or a shared-memory size that follows the sequence length is baked into a captured diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index 632de825..21927e14 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -4256,6 +4256,12 @@ bool w2_on() { bool gemm_iq_f16_grouped(int ty, const void* W, size_t expert_bytes, int n_out, int K, const void* X, int ldx, const int32_t* bounds, int n_experts, int max_rows, float* Y, int ldy, void* stream) { if (n_out % WG_BN != 0 || n_experts <= 0 || max_rows <= 0 || ldy % 4 != 0) return false; + { // the tiles are tensor-core kernels: a pre-Volta card has no body for them (the sm_60 pass compiles them empty) + int cur = 0, major = 0; + if (cudaGetDevice(&cur) != cudaSuccess || cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, cur) != cudaSuccess || + major < 7) + return false; + } // STRATA_PF_WMMA2=1 (opt-in): IQ2_S gate/up and IQ4_NL down through gemm_iq_f16_w2_kernel (above) if (w2_on() && n_out % W2_RB == 0 && ldx % 8 == 0 && ldy % 8 == 0 && (uintptr_t) X % 16 == 0 && (uintptr_t) Y % 32 == 0 && (uintptr_t) W % 4 == 0 && expert_bytes % 4 == 0 && ((ty == 22 && K % 512 == 0) || (ty == 20 && K % 128 == 0))) { diff --git a/src/kernels/cuda/s2_expert_grouped.cu b/src/kernels/cuda/s2_expert_grouped.cu index 9d5bc1e5..bff8b21e 100644 --- a/src/kernels/cuda/s2_expert_grouped.cu +++ b/src/kernels/cuda/s2_expert_grouped.cu @@ -19,6 +19,7 @@ #include "strata/kernels/f16_bits.hpp" #include "strata/kernels/quantize_act.hpp" +#include "strata/kernels/fuse_decode.hpp" #include "strata/kernels/verify_kernels.hpp" #include @@ -164,7 +165,6 @@ __global__ void gu_kernel(const uint8_t* __restrict__ blob_base, const int32_t* // `silu(gate) * up` lives in `strata/kernels/swiglu.cuh` (the fused kernels call it in their epilogues); // the standalone pass it replaced is gone. The scratch layout is unchanged: `[0, n_pairs)` ends up holding // the products, `[n_pairs, 2*n_pairs)` the raw up rows. -#if !defined(STRATA_EXPERIMENTAL_SM60) /// `silu(gate) * up`, in place, over a GATE-MAJOR buffer: `[0, n_pairs)` is every hit's gate and /// `[n_pairs, 2*n_pairs)` is every hit's up, so hit `h`'s row `r` meets itself at `h*FF + r`. /// @@ -177,7 +177,6 @@ __global__ void swiglu_kernel(float* __restrict__ gate_up, long long n_pairs) { const float u = gate_up[n_pairs + i]; gate_up[i] = (g / (1.0f + __expf(-g))) * u; } -#endif __global__ void swiglu_quantize_q8_0_scaled_kernel(float* __restrict__ gate_up, long long n_pairs, uint8_t* __restrict__ blocks, float* __restrict__ scales) { @@ -643,17 +642,20 @@ void moe_hit_grouped_s2(const uint8_t* blob_base, const int32_t* slot_index, con { const long long pairs = n_hits * (long long) FF; #if defined(STRATA_EXPERIMENTAL_SM60) + if (strata::kernels::fuse_decode()) { if (x_scales != nullptr) swilu_quantize_q8_0_scaled(gate_up, gate_up + pairs, gate_up, pairs, 1, h_q8_0, h_scales, stream); else swilu_quantize_q8_0(gate_up, gate_up + pairs, gate_up, pairs, 1, h_q8_0, stream); -#else + } else +#endif + { const unsigned blocks = (unsigned) ((pairs + THREADS - 1) / THREADS); swiglu_kernel<<>>(gate_up, pairs); check("moe_hit_grouped_s2/swiglu", stream); if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, n_hits * (int64_t) FF, stream); else quantize_q8_0(gate_up, h_q8_0, n_hits * (int64_t) FF, stream); -#endif + } } // 4. down. { @@ -747,16 +749,19 @@ void moe_hit_grouped_s2_dev(const uint8_t* blob_base, const int32_t* slot_index, { const long long pairs = cap * (long long) FF; #if defined(STRATA_EXPERIMENTAL_SM60) + if (strata::kernels::fuse_decode()) { if (x_scales != nullptr) swilu_quantize_q8_0_scaled(gate_up, gate_up + pairs, gate_up, pairs, 1, h_q8_0, h_scales, stream); else swilu_quantize_q8_0(gate_up, gate_up + pairs, gate_up, pairs, 1, h_q8_0, stream); -#else + } else +#endif + { swiglu_kernel<<<(unsigned) ((pairs + THREADS - 1) / THREADS), THREADS, 0, cs>>>(gate_up, pairs); check("moe_hit_grouped_s2_dev/swiglu", stream); if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap * (int64_t) FF, stream); else quantize_q8_0(gate_up, h_q8_0, cap * (int64_t) FF, stream); -#endif + } } { launch_hit_down(fast, blob_base, slot_index, dst_index, blob_bytes, h_q8_0, @@ -791,16 +796,19 @@ void moe_hit_grouped_s2_multi(const uint8_t* blob_base, const int32_t* slot_inde { const long long pairs = cap * (long long) FF; #if defined(STRATA_EXPERIMENTAL_SM60) + if (strata::kernels::fuse_decode()) { if (x_scales != nullptr) swilu_quantize_q8_0_scaled(gate_up, gate_up + pairs, gate_up, pairs, 1, h_q8_0, h_scales, stream); else swilu_quantize_q8_0(gate_up, gate_up + pairs, gate_up, pairs, 1, h_q8_0, stream); -#else + } else +#endif + { swiglu_kernel<<<(unsigned) ((pairs + THREADS - 1) / THREADS), THREADS, 0, cs>>>(gate_up, pairs); check("moe_hit_grouped_s2_multi/swiglu", stream); if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap * (int64_t) FF, stream); else quantize_q8_0(gate_up, h_q8_0, cap * (int64_t) FF, stream); -#endif + } } { launch_hit_down(fast, blob_base, slot_index, dst_index, blob_bytes, h_q8_0, @@ -1196,16 +1204,19 @@ void moe_grouped_s2(const unsigned long long* grp_ptr, const int32_t* grp_start, } else { const long long pairs = cap_entries * (long long) FF; #if defined(STRATA_EXPERIMENTAL_SM60) + if (strata::kernels::fuse_decode()) { if (x_scales != nullptr) swilu_quantize_q8_0_scaled(gate_up, gate_up + pairs, gate_up, pairs, 1, h_q8_0, h_scales, stream); else swilu_quantize_q8_0(gate_up, gate_up + pairs, gate_up, pairs, 1, h_q8_0, stream); -#else + } else +#endif + { swiglu_kernel<<<(unsigned) ((pairs + THREADS - 1) / THREADS), THREADS, 0, cs>>>(gate_up, pairs); check("moe_grouped_s2/swiglu", stream); if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap_entries * (int64_t) FF, stream); else quantize_q8_0(gate_up, h_q8_0, cap_entries * (int64_t) FF, stream); -#endif + } } { const dim3 grid((unsigned) (H / D_ROWS), (unsigned) cap_groups); diff --git a/src/kernels/cuda/shared_expert.cu b/src/kernels/cuda/shared_expert.cu index 98b634c4..bee0da97 100644 --- a/src/kernels/cuda/shared_expert.cu +++ b/src/kernels/cuda/shared_expert.cu @@ -19,6 +19,7 @@ // BF16 path affects only the scalar gate: it reads the original F32 input and uses pinned CUDA MMVF plus // an FP32 sigmoid. Native projection overrides independently select CUDA Q8_1 MMVQ and FP32 SwiGLU. #include "strata/kernels/shared_expert.hpp" +#include "strata/kernels/fuse_decode.hpp" #include "strata/kernels/bf16_gemv.hpp" #include "strata/kernels/bf16_bits.hpp" #include "strata/kernels/f16_bits.hpp" @@ -331,6 +332,7 @@ void shared_expert(const uint8_t* x_q8_0, const uint8_t* x_q8k, const uint16_t* const unsigned g_embd = (unsigned) ((n_embd + THREADS - 1) / THREADS); #if defined(STRATA_EXPERIMENTAL_SM60) + if (strata::kernels::fuse_decode()) { // V100 (experimental sm_70 build): gate and up projections, then silu(gate) * up - ONE kernel when both // projections are S-family (`s_gemv_pair_silu`: one read of x, SwiGLU in the epilogue, `up` never // materialised). The pair kernel is bit-exact vs the three-kernel sequence (shared row math, shared @@ -410,7 +412,9 @@ void shared_expert(const uint8_t* x_q8_0, const uint8_t* x_q8k, const uint16_t* } else { gemv(down_form, down_codes, down_scales, down_off, h_q8_0, h_q8k, out, n_ff, n_embd); } -#else + } else +#endif + { // gate and up projections, then silu(gate) * up in place in `gate` if (native_gate || native_up) native_quantize_q8_1(x_f32, native->q8_1, (int) n_embd, 1, stream); @@ -453,7 +457,7 @@ void shared_expert(const uint8_t* x_q8_0, const uint8_t* x_q8k, const uint16_t* gemv(down_form, down_codes, down_scales, down_off, h_q8_0, h_q8k, out, n_ff, n_embd); } } -#endif + } // the per-token scalar gate, then the multiply. Note the gate is computed from `x`, the ORIGINAL hidden // state, not from anything the expert produced. The historical branch uses BF16-rounded inputs; the diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 23616ae2..ccce1faa 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -1013,18 +1013,23 @@ struct MmqPlan { // Volta (sm_70): MMQ runs on dp4a there (no int8 tensor cores). pf_wmma(): the layers MMQ would take, and the IQ1_M // ones the FP16 path would, run as one launch per expert group on FP16 tensor-core tiles instead // (strata::kernels::gemm_iq_f16_grouped: each weight superblock dequantized once into shared memory by the FP16 path's -// own formulas, FP16 activations, FP32 sums). STRATA_PF_WMMA=0 / 1: off / on on any CUDA card. +// own formulas, FP16 activations, FP32 sums). OPT-IN: STRATA_PF_WMMA=1 (the activations are FP16 rather than MMQ's +// q8_1, so the answers differ from the default). Only when EVERY visible CUDA card is compute capability 7.0 or +// newer: the tiles need tensor cores, and a Volta + Pascal rig (one process, one decision) keeps MMQ. bool pf_wmma() { #if defined(__HIPCC__) return false; #else static const bool on = [] { - if (const char* e = std::getenv("STRATA_PF_WMMA")) return e[0] == '1'; - int dev = 0, major = 0, minor = 0; - if (cudaGetDevice(&dev) != cudaSuccess) return false; - cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev); - cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev); - return major == 7 && minor == 0; + const char* e = std::getenv("STRATA_PF_WMMA"); + if (e == nullptr || e[0] != '1') return false; + int n = 0; + if (cudaGetDeviceCount(&n) != cudaSuccess || n <= 0) return false; + for (int d = 0; d < n; ++d) { + int major = 0; + if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, d) != cudaSuccess || major < 7) return false; + } + return true; }(); return on; #endif @@ -3483,7 +3488,8 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri } // pf_wmma: this layer's groups on the FP16 tensor-core tiles (single GPU, native pack, Q2_0 / IQ4_NL down) const bool wmma_l = use_mmq && pf_wmma() && !fused_l && on_peer.empty() && lay.native && - (mmq_dt == 42 || mmq_dt == 20) && strata::kernels::iq_row_bytes(mmq_gt, N) > 0; + (mmq_dt == 42 || mmq_dt == 20) && !lay.fmt[(size_t) l].tail_off && + strata::kernels::iq_row_bytes(mmq_gt, N) > 0; if (use_mmq && mmq_plan().wmma_only[(size_t) l] && !wmma_l) { err = "prefill: an IQ1_M layer in the MMQ grouping needs the WMMA tiles, which this chunk cannot take"; return false; From 036d473a3c60d29206fe944f9ec3ba80bf157aed Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 15 Oct 2026 08:40:13 +0200 Subject: [PATCH 29/36] gdn: the Volta chain-split recurrence is opt-in (STRATA_GDN_REC_WARP=2), not the sm_70 default: it changes the summation order --- src/prefill/kernels.cu | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 435cac68..c4e0dd17 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -2129,10 +2129,11 @@ void gdn_recurrence_variant(int variant, float* state, const float* h, const flo // measured-fast path on Volta; the chunked recurrence is opt-in (STRATA_GDN_CHUNK=1/2) - correct and // measured, but slower than this on the V100 (bench/gdn_chunk_bench). STRATA_GDN_REC_WARP=0 restores // the old pipelined kernel bit-for-bit. - // STRATA_GDN_REC_WARP: unset -> the chain-split kernel on Volta (measured +6..9%, FP32-level), 0 -> the - // old pipelined kernel bit-for-bit, 1 -> the sync-free bit-exact control, 2 -> the chain split forced. + // STRATA_GDN_REC_WARP (Volta only, opt-in): unset or 0 -> the pipelined kernel (the default; the chain split changes the + // summation order, so it is not the default without a V100 check here), 2 -> the chain-split kernel (measured +6..9%, FP32-level), the + // old pipelined kernel bit-for-bit is 0, 1 -> the sync-free bit-exact control. const char* warp_v = std::getenv("STRATA_GDN_REC_WARP"); - const int warp_env = warp_v && *warp_v ? std::atoi(warp_v) : (volta ? 2 : 0); + const int warp_env = warp_v && *warp_v ? std::atoi(warp_v) : 0; const bool warp_rec = !serial && !chunked && T > 0 && volta && warp_env != 0; if (chunked && T >= 64) { // the chunked prefix + the recurrence over the tail (< 64 tokens), then the out norm over all of T From dea9b6de5d1aaa6bf891648aab5fbc3a99d04b69 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 15 Oct 2026 08:55:08 +0200 Subject: [PATCH 30/36] gdn chunk / Volta recurrence: name the sm_70-only kernels only in the host pass and the sm_70 device pass (a 60;70 or 70;86 build failed in the other device passes) --- src/prefill/gdn_chunk.cu | 2 +- src/prefill/kernels.cu | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/prefill/gdn_chunk.cu b/src/prefill/gdn_chunk.cu index cec287e8..1f18137c 100644 --- a/src/prefill/gdn_chunk.cu +++ b/src/prefill/gdn_chunk.cu @@ -532,7 +532,7 @@ void gdn_chunk_recurrence(float* state, const float* h, const float* gate, const (void) state; (void) h; (void) gate; (void) beta; (void) oc; (void) T; (void) stream; std::fprintf(stderr, "gdn_chunk_recurrence: not built for HIP\n"); std::exit(1); -#else +#elif !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 700 // the sm_60 device pass of a multi-arch build has no wmma kernel to name if (T <= 0) return; const int64_t T64 = T - T % CH; if (T64 <= 0) return; diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index c4e0dd17..598b94e8 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -2116,7 +2116,7 @@ void gdn_recurrence_variant(int variant, float* state, const float* h, const flo (void) variant; // the quad recurrence kernels are AMD-only #endif static const bool serial = std::getenv("STRATA_GDN_REC_HEADS") != nullptr; // the one-block-per-head kernel (A/B) -#if defined(STRATA_EXPERIMENTAL_SM60) +#if defined(STRATA_EXPERIMENTAL_SM60) && (!defined(__CUDA_ARCH__) || __CUDA_ARCH__ == 700) // the kernels exist in the host pass and the sm_70 device pass only // v100/gdn-chunk: the chunked recurrence (src/prefill/gdn_chunk.cu) on Volta, where the token chain is the // cost. STRATA_GDN_CHUNK=0 forces the recurrence, =1 forces the chunked path (the parity test's A/B switch); // unset: cc == 7.0 only, every other architecture keeps the recurrence bit-for-bit as before. Read per call From 4ef3855745c7f20cdc80507bb025cd0e3c6bcbf3 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 15 Oct 2026 09:48:05 +0200 Subject: [PATCH 31/36] gdn_chunk_parity: skip (77) on a card whose shared-memory opt-in cannot hold the kkt stage (Pascal), instead of failing --- CMakeLists.txt | 1 + src/kernels/gdn_chunk_parity.cpp | 11 +++++++++++ 2 files changed, 12 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 4545bcc5..1fae7183 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -935,6 +935,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_include_directories(gdn_chunk_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(gdn_chunk_parity PRIVATE strata_prefill ${_strata_gpu_runtime_target}) add_test(NAME gdn_chunk_parity COMMAND gdn_chunk_parity --selftest) + set_tests_properties(gdn_chunk_parity PROPERTIES SKIP_RETURN_CODE 77) # v100/gdn-chunk: the micro benchmark (CUDA events, real GDN shapes): chunked vs recurrent prompt path. add_executable(gdn_chunk_bench bench/gdn_chunk_bench.cpp) diff --git a/src/kernels/gdn_chunk_parity.cpp b/src/kernels/gdn_chunk_parity.cpp index e60fdc84..2a271694 100644 --- a/src/kernels/gdn_chunk_parity.cpp +++ b/src/kernels/gdn_chunk_parity.cpp @@ -258,6 +258,17 @@ int main(int argc, char** argv) { if (std::strcmp(argv[i], "--selftest") == 0) selftest = true; else { std::fprintf(stderr, "usage: gdn_chunk_parity [--selftest]\n"); return 2; } } + { + // the kkt stage needs 2*64*129 floats (66 KB) of dynamic shared memory: a card whose opt-in limit is lower + // (Pascal: 48 KB) cannot launch it, and the engine dispatch never selects the chunked path there + int dev = 0, smem = 0; + cudaGetDevice(&dev); + cudaDeviceGetAttribute(&smem, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev); + if (smem < 2 * 64 * 129 * 4) { + std::printf("gdn_chunk_parity: the card's shared-memory opt-in (%d B) is below the kkt stage's need, skipped\n", smem); + return 77; + } + } if (!strata::prefill::gdn_chunk_available()) std::printf("note: not a V100 (cc 7.0) - the parity still runs; the engine dispatch keeps the recurrence\n"); run_case(64, 1); From 456ec79c0a255aad793a41aad9cb0758f2d1774a Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 15 Oct 2026 09:49:14 +0200 Subject: [PATCH 32/36] docs/NVIDIA_V100.md: STRATA_GDN_REC_WARP (#1098) --- docs/NVIDIA_V100.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/NVIDIA_V100.md b/docs/NVIDIA_V100.md index b2ee3ca1..1536d0ea 100644 --- a/docs/NVIDIA_V100.md +++ b/docs/NVIDIA_V100.md @@ -102,3 +102,4 @@ None of these is on by default. Each was measured by its contributor on a V100, | `STRATA_ARGMAX_ROWS_SM70=1` | the multi-block greedy pick on sm_7x (#2357), bitwise the one-block pick | +0.7-0.8% decode | | `STRATA_GR_NORM_FAST=1` | the register-split hyper-connection norm on CUDA (#2358) | +0.5-0.6% decode | | `STRATA_Q8_GATHER_WIDE=0` | turns off the 8-wide int8 KV gather (#1095) that the experimental build uses below compute capability 7.5 | +11% on the gather kernel | +| `STRATA_GDN_REC_WARP=2` | the chain-split DeltaNet recurrence of the prompt on a V100 (#1098); changes the summation order (FP32 level), so the default stays the pipelined kernel; `1` is the bit-exact sync-free variant, `STRATA_GDN_CHUNK=1` the chunked path | +6-9% on the recurrence | From 5389eb9db873596072d48df3e8a98ae83f4538d4 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 15 Oct 2026 10:47:40 +0200 Subject: [PATCH 33/36] kv_hybrid_parity: the tensor-core prompt kernel is sm_70+ (base launch gate), so a refusal below sm_70 passes --- src/kernels/kv_hybrid_parity.cpp | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/kernels/kv_hybrid_parity.cpp b/src/kernels/kv_hybrid_parity.cpp index ca371782..58d50a60 100644 --- a/src/kernels/kv_hybrid_parity.cpp +++ b/src/kernels/kv_hybrid_parity.cpp @@ -333,8 +333,16 @@ int main() { // AMD: the tensor-core prompt path is CUDA-only, so it refuses every pool and the old kernel runs std::printf("[5/5] qsa_prompt_attn mode 3: PASS (refused on HIP - the old kernel runs)\n"); #else - std::printf("[5/5] qsa_prompt_attn mode 3: FAIL (refused the hybrid pools)\n"); - g_fail = 1; + // a card below compute capability 7.0 (Pascal) never had the tensor-core prompt kernels: the old kernel runs + int dev5 = 0, major5 = 0; + cudaGetDevice(&dev5); + cudaDeviceGetAttribute(&major5, cudaDevAttrComputeCapabilityMajor, dev5); + if (major5 > 0 && major5 < 7) { + std::printf("[5/5] qsa_prompt_attn mode 3: PASS (refused below sm_70 - the old kernel runs)\n"); + } else { + std::printf("[5/5] qsa_prompt_attn mode 3: FAIL (refused the hybrid pools)\n"); + g_fail = 1; + } #endif } else { k::fwht256_inplace_cuda(d_at4, QH, nullptr); From e1ee39169d8f6e6b79680a0ec93c56d8f9ae2d10 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 15 Oct 2026 14:33:21 +0200 Subject: [PATCH 34/36] sm_60: IQ3 table staging is opt-in (STRATA_IQ_STAGE_TABLES=1), not the default on cc 6.0: no end-to-end gain on a Tesla P100 (#1424) --- docs/OLDER_GPUS.md | 20 ++++++++++---------- src/kernels/cuda/iq_kernels.cu | 25 +++++++------------------ 2 files changed, 17 insertions(+), 28 deletions(-) diff --git a/docs/OLDER_GPUS.md b/docs/OLDER_GPUS.md index c4cd2a73..87415ba5 100644 --- a/docs/OLDER_GPUS.md +++ b/docs/OLDER_GPUS.md @@ -114,16 +114,16 @@ and i-quant blocks (Q6_K, IQ4_XS, Q4_K, IQ3_S, ...) one int at a time. Two chang (+3.5 GiB; the experts keep their offsets, so the native pack is reused). Point `--native` and `--ple-gguf` at the new folder. Requantizing costs at most 0.4% of a tensor's |w|max (Q8_0 is finer than the sources). -- IQ3_XXS's and IQ3_S's codebooks and sign-mask tables are staged in shared memory by the grouped expert kernels on - compute capability 6.0 (IQ3_XXS's ported from shinbunbun/llama-cpp-p100-patches 29 and 30, IQ3_S's the same for its - sign bytes; bitwise the same output; `STRATA_IQ_STAGE_TABLES=0|1` forces it off or on, on any card). IQ3_S was the - one gate/up format whose codebook those kernels still read from global memory: a verify window's layer of IQ3_S - experts (20 experts, 24 entries) takes 24% less on a GP100 die (517 -> 393 us with a Q2_0 down projection, 492 -> - 369 us with IQ4_NL), and Swift 1.5 IQ3_XXS (13 of its 48 layers are IQ3_S) decodes 3.2% faster with the settings - below at 1M context (39.3 -> 40.5 tok/s, mean of the four prompts; the same drafts accepted). IQ3_XXS's tables - alone were within noise (+0-4%). It is a trade that only pays where the decode is the limit: on an RTX 3090 Ti - (sm_86), forced on, the same IQ3_S layers took 3-13% longer (those kernels already read at 490-665 GB/s there), so - the default is 6.0 only. +- **Opt-in `STRATA_IQ_STAGE_TABLES=1`**: IQ3_XXS's and IQ3_S's codebooks and sign-mask tables are staged in shared memory by + the grouped expert kernels (IQ3_XXS's ported from shinbunbun/llama-cpp-p100-patches 29 and 30, IQ3_S's the same for its + sign bytes; bitwise the same output). IQ3_S was the one gate/up format whose codebook those kernels still read from + global memory: the contributor measured a verify window's layer of IQ3_S experts (20 experts, 24 entries) 24% faster on a + GP100 die (517 -> 393 us with a Q2_0 down projection, 492 -> 369 us with IQ4_NL), and Swift 1.5 IQ3_XXS (13 of its 48 + layers are IQ3_S) 3.2% faster at 1M context (39.3 -> 40.5 tok/s); IQ3_XXS's tables alone were within noise (+0-4%). The + maintainers' interleaved A/Bs on a Tesla P100 (PCIe, IQ3_XXS pack and IQ3_S pack, 5-6 pairs each) showed no end-to-end + change (decode 0.97-1.03x, inside the noise of that box), so it is off by default (the contributor's version had it on + for compute capability 6.0). On an RTX 3090 Ti, forced on, the same IQ3_S layers took 3-13% longer (those kernels already + read at 490-665 GB/s there). - Neither change is measured on compute capability 6.1 (P40, P4, GTX 10 series), which has `__dp4a`. Both build for sm_61, and on a card with `__dp4a` the Q8_0 kernel's dot is the hardware instruction (`tools/q8_sm60_check.cu` passes on an RTX 3090 Ti); numbers from a 6.1 card with `STRATA_Q8_SM60=1` or `STRATA_IQ_STAGE_TABLES=1` would diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index 21927e14..a42cc4e5 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -2202,28 +2202,17 @@ bool g_stage_grid_mmvq = g_stage_grid && [] { return v != nullptr && v[0] == '1'; }(); // IQ3_XXS's and IQ3_S's codebooks and sign-mask tables staged in shared memory by the grouped expert kernels (the -// single-matrix mmvq does not): bitwise the same either way. The default on compute capability 6.0 (GP100: no -// __dp4a, these kernels decode-bound at 70-140 GB/s) and off elsewhere: on an RTX 3090 Ti, where they run at -// 490-665 GB/s, the staging made the IQ3_S layers 3-13% slower, and 6.1 cards (which have __dp4a) are unmeasured. -// STRATA_IQ_STAGE_TABLES=1 / 0 forces it on / off on any card. +// single-matrix mmvq does not): bitwise the same either way. OPT-IN: STRATA_IQ_STAGE_TABLES=1. The PR (#1424) made it +// the default on compute capability 6.0 (GP100: no __dp4a, these kernels decode-bound at 70-140 GB/s); on a Tesla P100 +// (IQ3_XXS and IQ3_S packs, 5-6 interleaved pairs each) the decode was 0.97-1.03x of the unstaged kernels, noise, so +// it is not on by default. On an RTX 3090 Ti, forced on, the IQ3_S layers took 3-13% longer. bool stage_tables_on() { if (!g_stage_grid) return false; - static const int forced = [] { + static const bool on = [] { const char* v = std::getenv("STRATA_IQ_STAGE_TABLES"); - return (v && v[0]) ? (v[0] != '0' ? 1 : 0) : -1; + return v && v[0] && v[0] != '0'; }(); - if (forced >= 0) return forced == 1; - static int by_device[64]; // 0 unknown, 1 on, 2 off - int dev = 0; - if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return false; - if (by_device[dev] == 0) { - int major = 0, minor = 0; - const bool gp100 = cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess && - cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) == cudaSuccess && - major == 6 && minor == 0; - by_device[dev] = gp100 ? 1 : 2; - } - return by_device[dev] == 1; + return on; } template> From 4c968e61999d237caed3139e6a714d0de52afe82 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 15 Oct 2026 14:47:57 +0200 Subject: [PATCH 35/36] gdn chunk / Volta recurrence: name the kernels in every device pass (wmma body guarded inside the kernel), not behind __CUDA_ARCH__ at the call sites: the dea9b6de5 guard left the host stubs undefined in a 60;70;86 build (link error) --- src/prefill/gdn_chunk.cu | 10 ++++++---- src/prefill/kernels.cu | 6 +++--- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/src/prefill/gdn_chunk.cu b/src/prefill/gdn_chunk.cu index 1f18137c..0db55020 100644 --- a/src/prefill/gdn_chunk.cu +++ b/src/prefill/gdn_chunk.cu @@ -223,13 +223,14 @@ __global__ void __launch_bounds__(128) gdn_chunk_fwd_kernel(float* __restrict__ // // Precision: the FP16 staging is the reference's "f32 -> f16 暂存" (10-bit mantissa on the operands); // accumulations, the solve and the state are f32. FP32-level, not bit-exact - see gdn_chunk_parity. -#if !defined(__HIPCC__) && (!defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 700) -namespace wmma = ::nvcuda::wmma; +#if !defined(__HIPCC__) __global__ void __launch_bounds__(128) gdn_chunk_wmma_kernel(float* __restrict__ state, float* __restrict__ oc, const float* __restrict__ h, const float* __restrict__ beta, const float* __restrict__ gcum, int nchunks) { +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 700 // named in every device pass of a multi-arch build; only sm_70+ has wmma + namespace wmma = ::nvcuda::wmma; // smem (84.5 KB, opt-in): Ks/Qs the chunk's k and q rows f16; W16 the state slice f16 (U's operand); // Ug[128][32] f32 aliasing the 64x64 Gram scratch and then U = [K;Q] W; As/Ps f16; dlt f32 + f16. extern __shared__ __align__(1024) unsigned char smem[]; @@ -439,8 +440,9 @@ __global__ void __launch_bounds__(128) gdn_chunk_wmma_kernel(float* __restrict__ const int r = i / NS, j = i % NS; state[(size_t) r * HV * S + (size_t) hh * S + j0 + j] = Ug[i]; } +#endif } -#endif // !HIPCC && __CUDA_ARCH__ >= 700 +#endif // !HIPCC // The grow-only workspace, one per (thread, device): a layer split runs the chunked recurrence on more than // one card, and each card's pointers are only valid on that card - a single per-thread buffer would hand a @@ -532,7 +534,7 @@ void gdn_chunk_recurrence(float* state, const float* h, const float* gate, const (void) state; (void) h; (void) gate; (void) beta; (void) oc; (void) T; (void) stream; std::fprintf(stderr, "gdn_chunk_recurrence: not built for HIP\n"); std::exit(1); -#elif !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 700 // the sm_60 device pass of a multi-arch build has no wmma kernel to name +#else if (T <= 0) return; const int64_t T64 = T - T % CH; if (T64 <= 0) return; diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 598b94e8..d6c6b99a 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -395,7 +395,7 @@ constexpr int RG = 4, RPG = S / RG; constexpr int CB = 32, NCB = S / CB; // value columns per block kernel / blocks per head // v100/gdn-chunk: Volta-only (sm_70), inside the experimental build. Main's recurrence kernels above are // untouched for every other architecture; the chain-split is dispatched only when the device is cc 7.0. -#if defined(STRATA_EXPERIMENTAL_SM60) && (!defined(__CUDA_ARCH__) || __CUDA_ARCH__ == 700) +#if defined(STRATA_EXPERIMENTAL_SM60) // v100/gdn-chunk: the same recurrence with WARP-LOCAL reductions - no __syncthreads at all. gdn_rec_cols_*' // per-token shape is two cross-warp reductions (k^T W and q^T W) behind two barriers each (six barriers per // token in the pipelined kernel); here a warp owns 8 columns and the 4 row-groups are lanes within the warp, @@ -613,7 +613,7 @@ __global__ void __launch_bounds__(CB * RG) gdn_rec_cols_pipe_kernel(float* __res // cycles before the barriers); the split keeps the load pattern, the barriers and the (S, h_v, S) state // layout untouched. FP32-level, NOT bit-exact - the four partial sums group the 32 products differently - // so it is opt-in by measured benefit (STRATA_GDN_REC_WARP=2; gdn_chunk_parity bounds the error). -#if defined(STRATA_EXPERIMENTAL_SM60) && (!defined(__CUDA_ARCH__) || __CUDA_ARCH__ == 700) +#if defined(STRATA_EXPERIMENTAL_SM60) __global__ void __launch_bounds__(CB * RG) gdn_rec_cols_pipe_fast_kernel(float* __restrict__ state, const float* __restrict__ h, const float* __restrict__ gate, @@ -2116,7 +2116,7 @@ void gdn_recurrence_variant(int variant, float* state, const float* h, const flo (void) variant; // the quad recurrence kernels are AMD-only #endif static const bool serial = std::getenv("STRATA_GDN_REC_HEADS") != nullptr; // the one-block-per-head kernel (A/B) -#if defined(STRATA_EXPERIMENTAL_SM60) && (!defined(__CUDA_ARCH__) || __CUDA_ARCH__ == 700) // the kernels exist in the host pass and the sm_70 device pass only +#if defined(STRATA_EXPERIMENTAL_SM60) // v100/gdn-chunk: the chunked recurrence (src/prefill/gdn_chunk.cu) on Volta, where the token chain is the // cost. STRATA_GDN_CHUNK=0 forces the recurrence, =1 forces the chunked path (the parity test's A/B switch); // unset: cc == 7.0 only, every other architecture keeps the recurrence bit-for-bit as before. Read per call From c61364fc8981304c272292268a1e1575a290c497 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 17 Oct 2026 13:49:20 +0200 Subject: [PATCH 36/36] qsa prompt attention: STRATA_QSA_WARP=1 only forces the Turing kernels on cards that have the Turing MMA (sm_75+) The switch made every card answer as sm_75, so a Tesla P100 (sm_60) launched the m16n8k8 prompt-attention kernels, whose sm_60 code is a __trap(): the engine died on the first long prompt with "prefill copy_i32: unspecified launch failure". A card below sm_75 now ignores the switch and runs the kernel it runs without it (the same tokens). --- src/kernels/cuda/qsa_prompt_attn.cu | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/kernels/cuda/qsa_prompt_attn.cu b/src/kernels/cuda/qsa_prompt_attn.cu index b2b5480c..489a6d5f 100644 --- a/src/kernels/cuda/qsa_prompt_attn.cu +++ b/src/kernels/cuda/qsa_prompt_attn.cu @@ -2272,10 +2272,13 @@ bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int3 cudaGetLastError(); return false; } - // STRATA_QSA_WARP=1|attn (an A/B arm): the pre-sm_80 kernels on any card, as RTX 20 runs them + // STRATA_QSA_WARP=1|attn (an A/B arm): the pre-sm_80 kernels on any card that has the Turing MMA (sm_75 + // and newer), as RTX 20 runs them. A card below sm_75 has no m16n8k8: its builds hold a __trap() in those + // kernels, so forcing them there killed the engine ("prefill copy_i32: unspecified launch failure" on a + // Tesla P100); such a card ignores the switch and keeps the kernel it runs without it. const char* w = std::getenv("STRATA_QSA_WARP"); - cc[dev] = w && (!std::strcmp(w, "1") || !std::strcmp(w, "attn")) ? 75 - : 10 * strata::cc_major_of(major) + strata::cc_minor_of(minor); + const int real_cc = 10 * strata::cc_major_of(major) + strata::cc_minor_of(minor); + cc[dev] = w && (!std::strcmp(w, "1") || !std::strcmp(w, "attn")) && real_cc >= 75 ? 75 : real_cc; } if (cc[dev] < 70) return false; volta = cc[dev] < 75; // sm_70: the m8n8k4 kernel (STRATA_PA_VOLTA); STRATA_QSA_WARP=1 still forces the old one