diff --git a/CMakeLists.txt b/CMakeLists.txt index 347d2ec7..c614cbdd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -670,6 +670,13 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(qsa_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME qsa_parity COMMAND qsa_parity --selftest) + # the QSA top-k the engine dispatches against the original kernel: identical ids on both sides of the register + # kernel's reach, with tied and with equal scores (synthetic, no model) + add_executable(qsa_topk_parity src/kernels/qsa_topk_parity.cpp) + target_include_directories(qsa_topk_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(qsa_topk_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME qsa_topk_parity COMMAND qsa_topk_parity --selftest) + # ---- P2.S4: the PLE n-gram hash, the IQ4_NL table read, and the PLE block ---- # `ngram.cpp` is host-only but lives in `strata_kernels` because `ple.cu` shares its geometry constants, and # splitting them across two libraries would only add a layer. diff --git a/include/strata/kernels/qsa_select.hpp b/include/strata/kernels/qsa_select.hpp index b70a4ce5..31508165 100644 --- a/include/strata/kernels/qsa_select.hpp +++ b/include/strata/kernels/qsa_select.hpp @@ -49,7 +49,8 @@ void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64 /// build below sm_90, or a capacity whose keys do not fit one cluster's shared memory. Capturable. bool qsa_block_topk_cluster(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap, const QsaShapes& s, int32_t* ids, void* stream); -/// The original kernel (keys read from memory on every radix pass), for tests: the same ids. +/// The original kernel (256 threads, one shared histogram, keys read from memory on every radix pass), for tests and +/// STRATA_TOPK_OLD=1: the same ids. void qsa_block_topk_ref(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap, const QsaShapes& s, int32_t* ids, void* stream); diff --git a/src/kernels/cuda/qsa_select.cu b/src/kernels/cuda/qsa_select.cu index ad705b1d..56222c51 100644 --- a/src/kernels/cuda/qsa_select.cu +++ b/src/kernels/cuda/qsa_select.cu @@ -596,6 +596,125 @@ __global__ void __launch_bounds__(TK_T) block_topk_reg_kernel(const float* __res } } +#if !defined(__HIPCC__) +// ---- a query with more blocks than the register kernel holds (contexts past 4 * 1024 * TK_PER cells): the register +// kernel's threads, per-warp histograms and warp scans, with each key read from memory again on every pass. A +// histogram has no order, so on the four radix passes thread t reads blocks t, t + 1024, ...: a warp reads 32 +// neighbours at a time. The cells are emitted ascending in the order (warp, row, lane): warp w holds the `per` rows +// of 32 consecutive blocks from block w * 32 * per. block_topk_kernel's selection rule (radix threshold, ties to the +// lowest index): identical ids. +__global__ void __launch_bounds__(TK_T) block_topk_wide_kernel(const float* __restrict__ scores, + const int32_t* __restrict__ steps, int64_t max_blocks, + int64_t cap, int32_t* __restrict__ ids) { + __shared__ int hist[TK_T / 32][256]; + __shared__ int s_gt[TK_T / 32], s_eq[TK_T / 32]; + __shared__ int s_digit, s_above; + const int64_t qi = blockIdx.x; + const int32_t* st = steps + qi * kStepCount; + const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid], width = st[kStepWidth]; + int32_t* out = ids + qi * cap; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + if (n_kv <= width) { + for (int64_t j = t; j < n_kv; j += TK_T) out[j] = (int32_t) j; + return; + } + const float* sc = scores + qi * max_blocks; + const int64_t nb = n_bid + 1; + const int64_t per = (nb + TK_T - 1) / TK_T; // rows of 32 blocks per warp + auto weight = [&](int64_t b) -> int { return b < n_bid ? R : (int) (n_kv - n_bid * R); }; + uint32_t prefix = 0; + int above = 0; + for (int shift = 24; shift >= 0; shift -= 8) { + for (int i = lane; i < 256; i += 32) hist[warp][i] = 0; + __syncwarp(); + const uint32_t hi_mask = shift == 24 ? 0u : (0xffffffffu << (shift + 8)); + for (int64_t b = t; b < nb; b += TK_T) { + const int w = weight(b); + if (w == 0) continue; + const uint32_t k = order_key(sc[b]); + if ((k & hi_mask) == (prefix & hi_mask)) atomicAdd(&hist[warp][(k >> shift) & 255], w); + } + __syncthreads(); + if (t < 256) { // fold the warps' histograms into warp 0's + int sum = 0; + for (int w2 = 0; w2 < TK_T / 32; ++w2) sum += hist[w2][t]; + hist[0][t] = sum; + } + __syncthreads(); + if (t == 0) { + int cum = above, d = 255; + for (; d > 0; --d) { + if (cum + hist[0][d] >= width) break; + cum += hist[0][d]; + } + s_digit = d; + s_above = cum; + } + __syncthreads(); + prefix |= (uint32_t) s_digit << shift; + above = s_above; + __syncthreads(); + } + const uint32_t thr = prefix; + const int eq_budget = (int) (width - above); // cells equal to thr that fit, lowest index first + const int64_t w0 = (int64_t) warp * 32 * per; + int gt = 0, eq = 0; + for (int64_t b = w0 + lane; b < nb && b < w0 + 32 * per; b += 32) { + const int w = weight(b); + if (w == 0) continue; + const uint32_t k = order_key(sc[b]); + if (k > thr) gt += w; + else if (k == thr) eq += w; + } +#pragma unroll + for (int o = 16; o > 0; o >>= 1) { + gt += __shfl_xor_sync(0xffffffffu, gt, o); + eq += __shfl_xor_sync(0xffffffffu, eq, o); + } + if (lane == 0) { s_gt[warp] = gt; s_eq[warp] = eq; } + __syncthreads(); + if (t == 0) { // per warp: the selected cells and the tied cells before it + int eb = 0, sb = 0; + for (int w2 = 0; w2 < TK_T / 32; ++w2) { + const int g2 = s_gt[w2], e2 = s_eq[w2]; + const int take = eq_budget - eb < 0 ? 0 : (eq_budget - eb > e2 ? e2 : eq_budget - eb); + s_gt[w2] = sb; + s_eq[w2] = eb; + sb += g2 + take; + eb += e2; + } + } + __syncthreads(); + int run_sel = s_gt[warp], run_eq = s_eq[warp]; + for (int64_t r0 = w0; r0 < nb && r0 < w0 + 32 * per; r0 += 32) { + const int64_t b = r0 + lane; + const int w = b < nb ? weight(b) : 0; + const uint32_t k = w ? order_key(sc[b]) : 0u; + const int my_gt = (w && k > thr) ? w : 0, my_eq = (w && k == thr) ? w : 0; + if (__ballot_sync(0xffffffffu, (my_gt | my_eq) != 0) == 0u) continue; // a row without a selected block + int pe = my_eq; // tied cells up to and with this lane +#pragma unroll + for (int o = 1; o < 32; o <<= 1) { + const int y = __shfl_up_sync(0xffffffffu, pe, o); + if (lane >= o) pe += y; + } + const int left = eq_budget - (run_eq + pe - my_eq); + const int take = left < 0 ? 0 : (left > my_eq ? my_eq : left); + const int my_sel = my_gt + take; + int ps = my_sel; +#pragma unroll + for (int o = 1; o < 32; o <<= 1) { + const int y = __shfl_up_sync(0xffffffffu, ps, o); + if (lane >= o) ps += y; + } + int32_t* dst = out + run_sel + ps - my_sel; + for (int c = 0; c < my_sel; ++c) dst[c] = (int32_t) (b * R + c); + run_eq += __shfl_sync(0xffffffffu, pe, 31); + run_sel += __shfl_sync(0xffffffffu, ps, 31); + } +} +#endif + // Block scores with every key block read ONCE for all of a call's queries (block_scores_kernel's grid is // (max_blocks / 8) x nq: ~24,600 mostly-idle blocks per layer at a decode window, each key re-read per query). A fixed @@ -1054,8 +1173,8 @@ bool qsa_block_topk_cluster(const float* scores, const int32_t* steps, int64_t n void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap, const QsaShapes& s, int32_t* ids, void* stream, int64_t active_blocks) { - // keys in registers when every query's blocks fit (contexts up to ~135K cells); the same ids. STRATA_TOPK_OLD=1: - // the kernel that reads them from memory on every pass + // keys in registers when every query's blocks fit (contexts up to ~135K cells), else (CUDA) the same threads + // reading them from memory; the same ids. STRATA_TOPK_OLD=1: the original kernel static const bool old = std::getenv("STRATA_TOPK_OLD") != nullptr; if (nq <= 0) return; #if !defined(__HIPCC__) @@ -1089,10 +1208,12 @@ void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64 #if defined(__HIPCC__) constexpr int64_t kRegMinBlocks = 7168; // gfx1201: below ~28K cells the 1,024-thread kernel's fixed cost loses to the ref const bool too_small = counted && reach < kRegMinBlocks; -#else - const bool too_small = false; -#endif if (old || too_small || reach > fit) { +#else + constexpr int64_t kWideMinBlocks = 4608; // RTX 3060: a prompt batch below ~18K cells is faster on the ref + const bool too_small = reach > fit && active_blocks > 0 && active_blocks < kWideMinBlocks; + if (old || too_small) { +#endif qsa_block_topk_ref(scores, steps, nq, max_blocks, cap, s, ids, stream); return; } @@ -1100,6 +1221,11 @@ void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64 std::fprintf(stderr, "qsa_block_topk: unsupported geometry or cap\n"); std::exit(1); } +#if !defined(__HIPCC__) + if (reach > fit) // past the register kernel's reach + block_topk_wide_kernel<<<(unsigned) nq, TK_T, 0, (cudaStream_t) stream>>>(scores, steps, max_blocks, cap, ids); + else +#endif if (reach <= (int64_t) TK_T * TK_PER) block_topk_reg_kernel<<<(unsigned) nq, TK_T, 0, (cudaStream_t) stream>>>(scores, steps, max_blocks, cap, ids); else diff --git a/src/kernels/qsa_topk_parity.cpp b/src/kernels/qsa_topk_parity.cpp new file mode 100644 index 00000000..d14af3e1 --- /dev/null +++ b/src/kernels/qsa_topk_parity.cpp @@ -0,0 +1,139 @@ +// src/kernels/qsa_topk_parity.cpp - the QSA top-k the engine dispatches (qsa_block_topk) against the original kernel +// (qsa_block_topk_ref): the selected cells must be identical (GPU, synthetic, no model). +// +// A case is a context under a capacity (the engine's --max-context; max_blocks = capacity / 4 + 2, and without an +// active-block count the dispatch follows it), with consecutive queries at the context's end so that the tail block +// holds 0 to 3 cells. Three score sets per case: continuous, 64 levels (many ties at the threshold) and all equal +// (the rule's ties go to the lowest index). The dispatch is called as a decode window calls it (no block count) and as +// the prompt path does (with the call's largest block count). The reference and the dispatched kernel are also timed. +// +// Usage: qsa_topk_parity --selftest +// qsa_topk_parity CONTEXT [QUERIES=256] [REPS=10] [CAPACITY=CONTEXT] [COUNT=1] (COUNT=0: no block count) +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/qsa_select.hpp" + +#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); } +} + +bool run_case(int64_t ctx, int64_t nq, int reps, int64_t capacity, bool counted) { + const k::QsaShapes s = k::qsa_real_shapes(); + const int64_t max_blocks = capacity / s.idx_block + 2, cap = k::qsa_selection_width(k::kTopkMaxCells, s); + std::vector steps((size_t) (nq * k::kStepCount)); + for (int64_t i = 0; i < nq; ++i) { + int32_t* st = steps.data() + i * k::kStepCount; + const int64_t pos = ctx - nq + i; + st[k::kStepPos] = (int32_t) pos; + st[k::kStepNKv] = (int32_t) (pos + 1); + st[k::kStepNBid] = (int32_t) ((pos + 1) / s.idx_block); + st[k::kStepWidth] = (int32_t) k::qsa_selection_width(pos + 1, s); + } + std::mt19937 rng((uint32_t) (ctx * 31 + capacity)); + std::normal_distribution nd(0.f, 1.f); + std::vector scores((size_t) (nq * max_blocks)), tied(scores.size()), equal(scores.size(), 0.25f); + for (int64_t i = 0; i < nq; ++i) { + const int32_t* st = steps.data() + i * k::kStepCount; + float* row = scores.data() + i * max_blocks; + for (int64_t b = 0; b < max_blocks; ++b) row[b] = nd(rng); + // the tail block as the scorers leave it: far above the others when it holds cells + if (st[k::kStepNKv] % s.idx_block != 0) row[st[k::kStepNBid]] += 1e9f; + for (int64_t b = 0; b < max_blocks; ++b) + tied[(size_t) (i * max_blocks + b)] = row[b] > 1e8f ? row[b] : std::floor(row[b] * 8.0f) / 8.0f; // ~64 levels + } + int32_t *d_steps = nullptr, *ids_ref = nullptr, *ids_new = nullptr; + float* d_scores = nullptr; + ck(cudaMalloc(&d_steps, steps.size() * 4), "malloc"); + ck(cudaMalloc(&d_scores, scores.size() * 4), "malloc"); + ck(cudaMalloc(&ids_ref, (size_t) (nq * cap) * 4), "malloc"); + ck(cudaMalloc(&ids_new, (size_t) (nq * cap) * 4), "malloc"); + ck(cudaMemcpy(d_steps, steps.data(), steps.size() * 4, cudaMemcpyHostToDevice), "upload"); + const int64_t active = counted ? steps[(size_t) ((nq - 1) * k::kStepCount + k::kStepNBid)] + 1 : -1; + std::vector a((size_t) (nq * cap)), b(a.size()); + auto same = [&](const std::vector& sc) -> int64_t { + ck(cudaMemcpy(d_scores, sc.data(), sc.size() * 4, cudaMemcpyHostToDevice), "upload"); + ck(cudaMemset(ids_ref, 0xff, a.size() * 4), "memset"); + ck(cudaMemset(ids_new, 0xff, a.size() * 4), "memset"); + k::qsa_block_topk_ref(d_scores, d_steps, nq, max_blocks, cap, s, ids_ref, nullptr); + k::qsa_block_topk(d_scores, d_steps, nq, max_blocks, cap, s, ids_new, nullptr, active); + ck(cudaDeviceSynchronize(), "sync"); + ck(cudaMemcpy(a.data(), ids_ref, a.size() * 4, cudaMemcpyDeviceToHost), "down"); + ck(cudaMemcpy(b.data(), ids_new, b.size() * 4, cudaMemcpyDeviceToHost), "down"); + int64_t n = 0; + for (int64_t i = 0; i < nq; ++i) { + const int64_t w = steps[(size_t) (i * k::kStepCount + k::kStepWidth)]; + n += std::equal(a.begin() + i * cap, a.begin() + i * cap + w, b.begin() + i * cap); + } + return n; + }; + const int64_t same_tied = same(tied), same_equal = same(equal), same_cont = same(scores); // d_scores: continuous + cudaEvent_t e0, e1; + ck(cudaEventCreate(&e0), "event"); + ck(cudaEventCreate(&e1), "event"); + auto timed = [&](auto f) { + ck(cudaEventRecord(e0), "record"); + for (int r = 0; r < reps; ++r) f(); + ck(cudaEventRecord(e1), "record"); + ck(cudaEventSynchronize(e1), "time"); + float ms = 0; + ck(cudaEventElapsedTime(&ms, e0, e1), "elapsed"); + return ms / (float) reps; + }; + const float t_ref = timed([&] { k::qsa_block_topk_ref(d_scores, d_steps, nq, max_blocks, cap, s, ids_ref, nullptr); }); + const float t_new = timed([&] { k::qsa_block_topk(d_scores, d_steps, nq, max_blocks, cap, s, ids_new, nullptr, active); }); + cudaEventDestroy(e0); cudaEventDestroy(e1); + cudaFree(d_steps); cudaFree(d_scores); cudaFree(ids_ref); cudaFree(ids_new); + const bool ok = same_cont == nq && same_tied == nq && same_equal == nq; + std::printf("%s context %lld under a capacity of %lld (%lld blocks), %lld queries %s: reference %.3f ms, " + "dispatched %.3f ms (%.1fx); identical ids: continuous %lld/%lld, 64 levels %lld/%lld, equal scores " + "%lld/%lld\n", ok ? "PASS" : "FAIL", (long long) ctx, (long long) capacity, (long long) max_blocks, + (long long) nq, counted ? "with their block count" : "without a block count", t_ref, t_new, t_ref / t_new, + (long long) same_cont, (long long) nq, (long long) same_tied, + (long long) nq, (long long) same_equal, (long long) nq); + return ok; +} +} // namespace + +int main(int argc, char** argv) { + if (argc > 1 && std::strcmp(argv[1], "--selftest") == 0) { + // {context, capacity}: both sides of the register kernel's reach (33,792 blocks = 135,168 cells), short + // contexts under a long capacity (fewer blocks than the kernel's threads; a prompt batch below the dispatch's + // 4,608 blocks), and the long contexts themselves + const int64_t cases[][2] = {{9000, 9000}, {135160, 135160}, {135176, 135176}, {2100, 262144}, + {9000, 262144}, {32768, 262144}, {262144, 262144}, {300001, 524288}, + {524288, 524288}}; + bool ok = true; + for (const auto& c : cases) { + ok = run_case(c[0], 8, 3, c[1], false) && ok; // a decode window's call + ok = run_case(c[0], 64, 3, c[1], true) && ok; // the prompt path's + } + std::printf("%s\n", ok ? "qsa_topk_parity: PASS" : "qsa_topk_parity: FAIL"); + return ok ? 0 : 1; + } + if (argc < 2) { + std::fprintf(stderr, "usage: qsa_topk_parity --selftest | CONTEXT [QUERIES=256] [REPS=10] [CAPACITY=CONTEXT] " + "[COUNT=1]\n"); + return 2; + } + const int64_t ctx = std::atoll(argv[1]); + const int64_t nq = argc > 2 ? std::atoll(argv[2]) : 256; + const int reps = argc > 3 ? std::atoi(argv[3]) : 10; + const int64_t capacity = argc > 4 ? std::atoll(argv[4]) : ctx; + if (ctx < nq || nq <= 0 || reps <= 0 || capacity < ctx) { + std::fprintf(stderr, "qsa_topk_parity: CONTEXT >= QUERIES > 0, REPS > 0, CAPACITY >= CONTEXT\n"); + return 2; + } + return run_case(ctx, nq, reps, capacity, argc <= 5 || std::atoi(argv[5]) != 0) ? 0 : 1; +}