#1825 qsa_select: prompt-path block scores with a thread per query head (Turing)

On cards without the TF32 scorer (sm_75) the prompt path scored every
(query, key block) with a whole warp: 20 shuffles and five 512-byte loads per
score. block_scores_thread_kernel gives each lane one (query, head), keeps the
128-float query head in registers, reads each key once from shared memory as
a broadcast, and adds the 32 four-value partials in the tree lane 0 of the
xor-shuffle sum computes. Float addition is commutative, so the same pairs in
the same tree give the same bits; the heads are summed 0..3 from 0.0f as
before; the tail block keeps block_scores_tail_kernel. STRATA_SCORES_THREAD=0
selects the old kernel.

Measured on 2x CMP 50HX (TU102, sm_75, unlocked to RTX 2080 clocks):
- qsa_scores_parity (new): 141 M scores bitwise identical on both cards
  (normal values, wide magnitudes with zeros, small integers with ties);
  per call 4.6-5.2x faster, e.g. 1,024 queries at 200K: 52.4 -> 10.8 ms,
  at 140K: 35.9 -> 7.8 ms. 199 registers, no spills.
- nsys, one +4.4K-token turn at 140K: block_scores_kernel was the top prompt
  kernel at 1,045 ms per card (17 %).
- agentbench, IQ3_XXS, layer split, 262144 context, 34K -> 190K (with the
  tokenizer cache): engine read per turn at 190K 9.25 -> 6.96 s (476 -> 632
  tok/s, +33 %), time to first token 10.49 -> 7.13 s (-32 %); median
  incremental read 576 -> 682 tok/s; decode unchanged (73.3 tok/s).
  AGENT GATE: all 36 turns word-for-word identical to the base run.
This commit is contained in:
xrip authored and Niko1221 committed 2026-10-15 08:53:32 +02:00
1 parent 1d5319ae88
commit 33237ff367
3 files changed
+219

No files matched your search

+6
View File
@@ -408,6 +408,12 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
target_link_libraries(qsa_topk_active_parity PRIVATE strata_kernels CUDA::cudart)
add_test(NAME qsa_topk_active_parity COMMAND qsa_topk_active_parity)
set_tests_properties(qsa_topk_active_parity PROPERTIES SKIP_RETURN_CODE 77)
# the prompt path's block scores on the thread-per-head kernel (Turing) against the warp kernel, bitwise
add_executable(qsa_scores_parity src/kernels/qsa_scores_parity.cpp)
target_include_directories(qsa_scores_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES})
target_link_libraries(qsa_scores_parity PRIVATE strata_kernels CUDA::cudart)
add_test(NAME qsa_scores_parity COMMAND qsa_scores_parity)
set_tests_properties(qsa_scores_parity PROPERTIES SKIP_RETURN_CODE 77)
endif()
# the QSA selection (block scores on the warp kernel and the tensor-core one, top-k): a GPU bench with a
# scorer-vs-scorer comparison and an FP64 accuracy gate (synthetic, no model); the ctest runs a 32K context under a
+93
View File
@@ -968,6 +968,85 @@ __global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_multi_kernel(co
}
}
#if !defined(__HIPCC__)
// ---- prompt calls on cards without the tensor-core scorer (Turing): block_scores_kernel's scores, BITWISE, with a
// thread per (query, head) instead of a warp per (query, block). There a warp spends 20 shuffles and five 512-byte
// loads per score; here a lane holds its query head (128 floats) in registers, every lane of the warp reads the same
// key from shared memory (a broadcast), and the 4-value partials are added in the tree lane 0 of the xor-shuffle sum
// computes: partial g covers values 4g..4g+3, level o adds g and g + o. Float addition is commutative, so the same
// pairs in the same tree give the same bits. The heads are then summed 0..3 from 0.0f as there. Blocks < n_bid only:
// the tail block n_bid (the `dead` key, +1e9) is block_scores_tail_kernel's.
constexpr int TS_Q = 64; // queries per CTA (8 per warp, a lane per query head)
constexpr int TS_KB = 32; // key blocks per shared-memory tile
constexpr int TS_BR = 512; // key blocks per CTA
__device__ __forceinline__ float ts_part(const float4 k4, const float4 q4) {
return k4.x * q4.x + k4.y * q4.y + k4.z * q4.z + k4.w * q4.w; // block_scores_kernel's per-lane expression
}
__global__ void __launch_bounds__(256, 1) block_scores_thread_kernel(const float* __restrict__ pooled,
const float* __restrict__ q_idx,
const int32_t* __restrict__ steps, int64_t nq,
int64_t max_blocks, int64_t reach,
float* __restrict__ out) {
__shared__ __align__(16) float4 ks[TS_KB][IDX_DIM / 4];
__shared__ float so[TS_Q][TS_KB + 1];
__shared__ int64_t s_nbid[TS_Q];
const int t = threadIdx.x, lane = t & 31;
const int ql = (t >> 5) * 8 + (lane >> 2), h = lane & 3; // this lane's query (in the CTA) and head
const int64_t q0 = (int64_t) blockIdx.y * TS_Q, qi = q0 + ql;
if (t < TS_Q) s_nbid[t] = q0 + t < nq ? steps[(q0 + t) * kStepCount + kStepNBid] : -1;
float4 qv[IDX_DIM / 4];
{
const float4* src = reinterpret_cast<const float4*>(q_idx + (qi < nq ? qi : 0) * IDX_HEADS * IDX_DIM + h * IDX_DIM);
#pragma unroll
for (int g = 0; g < IDX_DIM / 4; ++g) qv[g] = src[g];
}
__syncthreads();
int64_t top = -1; // the largest n_bid of the CTA's queries: blocks at or past it are never written here
for (int i = 0; i < TS_Q; ++i) top = s_nbid[i] > top ? s_nbid[i] : top;
const int64_t b_lo = (int64_t) blockIdx.x * TS_BR;
int64_t b_hi = b_lo + TS_BR;
if (b_hi > reach) b_hi = reach;
if (b_hi > top) b_hi = top;
if (b_hi > max_blocks) b_hi = max_blocks;
for (int64_t b0 = b_lo; b0 < b_hi; b0 += TS_KB) {
const int nb = (int) (b_hi - b0 < TS_KB ? b_hi - b0 : TS_KB);
__syncthreads(); // the previous tile's reads of ks and so are done
for (int i = t; i < nb * (IDX_DIM / 4); i += blockDim.x)
ks[i / (IDX_DIM / 4)][i % (IDX_DIM / 4)] = reinterpret_cast<const float4*>(pooled + (b0 + i / (IDX_DIM / 4)) * IDX_DIM)[i % (IDX_DIM / 4)];
__syncthreads();
for (int j = 0; j < nb; ++j) {
const float4* k = ks[j];
float c[4];
#pragma unroll
for (int g = 0; g < 4; ++g)
c[g] = ((ts_part(k[g], qv[g]) + ts_part(k[g + 16], qv[g + 16])) +
(ts_part(k[g + 8], qv[g + 8]) + ts_part(k[g + 24], qv[g + 24]))) +
((ts_part(k[g + 4], qv[g + 4]) + ts_part(k[g + 20], qv[g + 20])) +
(ts_part(k[g + 12], qv[g + 12]) + ts_part(k[g + 28], qv[g + 28])));
const float d = (c[0] + c[2]) + (c[1] + c[3]);
const float r = d > 0.0f ? d : 0.0f;
const float r1 = __shfl_down_sync(0xffffffffu, r, 1), r2 = __shfl_down_sync(0xffffffffu, r, 2),
r3 = __shfl_down_sync(0xffffffffu, r, 3);
if (h == 0) {
float score = 0.0f;
score += r;
score += r1;
score += r2;
score += r3;
so[ql][j] = score;
}
}
__syncthreads();
for (int i = t; i < TS_Q * nb; i += blockDim.x) {
const int q = i / nb, j = i % nb;
if (b0 + j < s_nbid[q]) out[(q0 + q) * max_blocks + b0 + j] = so[q][j];
}
}
}
#endif
#if !defined(__HIPCC__)
// ---- the decode top-k on a thread-block cluster (sm_90+; S19). One CTA per query (block_topk_reg_kernel, or
// block_topk_kernel above 33,792 blocks: a --max-context over ~135K) makes four radix passes and two scans over up to
@@ -1342,6 +1421,20 @@ void qsa_block_scores(const float* pooled, const float* dead, const float* q_idx
return;
}
const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks;
#if !defined(__HIPCC__)
// prompt calls (an active-block count): the thread-per-head kernel, the same bits. STRATA_SCORES_THREAD=0: the warp
// kernel below
static const bool thread = [] { const char* v = std::getenv("STRATA_SCORES_THREAD"); return v == nullptr || std::atoi(v) != 0; }();
if (thread && active_blocks > 0) {
const dim3 tgrid((unsigned) ((reach + TS_BR - 1) / TS_BR), (unsigned) ((nq + TS_Q - 1) / TS_Q));
block_scores_thread_kernel<<<tgrid, 256, 0, (cudaStream_t) stream>>>(pooled, q_idx, steps, nq, max_blocks, reach,
scores);
block_scores_tail_kernel<<<(unsigned) nq, 32, 0, (cudaStream_t) stream>>>(dead, q_idx, steps, max_blocks, scores);
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores thread: %s\n", cudaGetErrorString(e)); std::exit(1); }
return;
}
#endif
const dim3 grid((unsigned) ((reach + SCORE_WARPS - 1) / SCORE_WARPS), (unsigned) nq);
block_scores_kernel<<<grid, SCORE_WARPS * 32, 0, (cudaStream_t) stream>>>(pooled, dead, q_idx, steps, max_blocks,
scores);
+120
View File
@@ -0,0 +1,120 @@
// The prompt path's block scores on the thread-per-head kernel (an active-block count) against block_scores_kernel
// (no count, more than 8 queries), every score of blocks 0..n_bid bitwise; then the time of each. GPU, synthetic.
#include "strata/kernels/qsa.hpp"
#include "strata/kernels/qsa_select.hpp"
#include <cuda_runtime.h>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <vector>
namespace k = strata::kernels;
namespace {
void ck(cudaError_t e) {
if (e != cudaSuccess) {
std::fprintf(stderr, "CUDA: %s\n", cudaGetErrorString(e));
std::exit(2);
}
}
// ctx: the last query's position + 1; queries: a prompt chunk ending there; mode 0 normal values, 1 wide magnitudes
// and exact zeros, 2 small integers (many ties and cancellations)
struct Case { int64_t ctx, queries; int mode; bool time; };
bool check(Case c) {
const auto s = k::qsa_real_shapes();
const int64_t D = s.idx_dim, H = s.idx_n_head, max_blocks = c.ctx / s.idx_block + 2;
std::mt19937 rng(91731 + (unsigned) c.ctx + 7 * (unsigned) c.queries + 101 * (unsigned) c.mode);
std::normal_distribution<float> nd(0.f, 1.f);
std::uniform_int_distribution<int> small(-3, 3), expo(-20, 20), coin(0, 9);
auto value = [&] {
if (c.mode == 1) return coin(rng) == 0 ? 0.f : std::ldexp(nd(rng), expo(rng));
if (c.mode == 2) return (float) small(rng);
return nd(rng);
};
std::vector<float> pooled((size_t) (max_blocks * D)), dead((size_t) D), q((size_t) (c.queries * H * D));
for (auto& v : pooled) v = value();
for (auto& v : dead) v = value();
for (auto& v : q) v = value();
std::vector<int32_t> steps((size_t) (c.queries * k::kStepCount));
for (int64_t i = 0; i < c.queries; ++i) {
int32_t* st = steps.data() + i * k::kStepCount;
const int64_t pos = c.ctx - c.queries + 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);
}
const int64_t active = steps[(size_t) ((c.queries - 1) * k::kStepCount + k::kStepNBid)] + 1;
float *dp = nullptr, *dd = nullptr, *dq = nullptr, *da = nullptr, *db = nullptr;
int32_t* dt = nullptr;
const size_t n_out = (size_t) (c.queries * max_blocks);
ck(cudaMalloc(&dp, pooled.size() * 4)); ck(cudaMalloc(&dd, dead.size() * 4)); ck(cudaMalloc(&dq, q.size() * 4));
ck(cudaMalloc(&dt, steps.size() * 4)); ck(cudaMalloc(&da, n_out * 4)); ck(cudaMalloc(&db, n_out * 4));
ck(cudaMemcpy(dp, pooled.data(), pooled.size() * 4, cudaMemcpyHostToDevice));
ck(cudaMemcpy(dd, dead.data(), dead.size() * 4, cudaMemcpyHostToDevice));
ck(cudaMemcpy(dq, q.data(), q.size() * 4, cudaMemcpyHostToDevice));
ck(cudaMemcpy(dt, steps.data(), steps.size() * 4, cudaMemcpyHostToDevice));
ck(cudaMemset(da, 0x7f, n_out * 4)); // different fill in each: an unwritten score cannot match by chance
ck(cudaMemset(db, 0x3e, n_out * 4));
k::qsa_block_scores(dp, dd, dq, dt, c.queries, max_blocks, s, da, nullptr); // block_scores_kernel
k::qsa_block_scores(dp, dd, dq, dt, c.queries, max_blocks, s, db, nullptr, active); // the thread kernel
ck(cudaDeviceSynchronize());
std::vector<uint32_t> a(n_out), b(n_out);
ck(cudaMemcpy(a.data(), da, n_out * 4, cudaMemcpyDeviceToHost));
ck(cudaMemcpy(b.data(), db, n_out * 4, cudaMemcpyDeviceToHost));
bool ok = true;
int64_t checked = 0;
for (int64_t i = 0; i < c.queries && ok; ++i) {
const int64_t n_bid = steps[(size_t) (i * k::kStepCount + k::kStepNBid)];
for (int64_t j = 0; j <= n_bid; ++j, ++checked) {
const size_t at = (size_t) (i * max_blocks + j);
if (a[at] != b[at]) {
float fa, fb;
std::memcpy(&fa, &a[at], 4); std::memcpy(&fb, &b[at], 4);
std::fprintf(stderr, "FAIL ctx=%lld queries=%lld mode=%d query=%lld block=%lld: %.9g vs %.9g\n",
(long long) c.ctx, (long long) c.queries, c.mode, (long long) i, (long long) j, fa, fb);
ok = false;
break;
}
}
}
if (ok) std::printf("ok ctx=%7lld queries=%5lld mode=%d: %lld scores identical\n", (long long) c.ctx,
(long long) c.queries, c.mode, (long long) checked);
if (ok && c.time) {
cudaEvent_t e0, e1, e2;
ck(cudaEventCreate(&e0)); ck(cudaEventCreate(&e1)); ck(cudaEventCreate(&e2));
constexpr int N = 5;
ck(cudaEventRecord(e0));
for (int r = 0; r < N; ++r) k::qsa_block_scores(dp, dd, dq, dt, c.queries, max_blocks, s, da, nullptr);
ck(cudaEventRecord(e1));
for (int r = 0; r < N; ++r) k::qsa_block_scores(dp, dd, dq, dt, c.queries, max_blocks, s, db, nullptr, active);
ck(cudaEventRecord(e2));
ck(cudaEventSynchronize(e2));
float t_old = 0.f, t_new = 0.f;
ck(cudaEventElapsedTime(&t_old, e0, e1)); ck(cudaEventElapsedTime(&t_new, e1, e2));
std::printf(" time per call: warp kernel %.2f ms, thread kernel %.2f ms (%.2fx)\n", t_old / N, t_new / N,
t_old / t_new);
cudaEventDestroy(e0); cudaEventDestroy(e1); cudaEventDestroy(e2);
}
ck(cudaFree(dp)); ck(cudaFree(dd)); ck(cudaFree(dq)); ck(cudaFree(dt)); ck(cudaFree(da)); ck(cudaFree(db));
return ok;
}
} // namespace
int main() {
int devices = 0;
if (cudaGetDeviceCount(&devices) != cudaSuccess || devices == 0) {
std::puts("SKIP: no CUDA device");
return 77;
}
const Case cases[] = {
{1111, 9, 0, false}, {1111, 64, 1, false}, {8192, 65, 0, false}, {8195, 200, 2, false},
{32768, 256, 0, false}, {32771, 1000, 1, false}, {131072, 64, 2, false}, {131075, 333, 0, false},
{262144, 129, 1, false}, {40000, 2048, 0, true}, {140000, 1024, 0, true}, {200000, 1024, 0, true},
};
for (const auto c : cases) if (!check(c)) return 1;
std::puts("PASS: block scores of the thread kernel bitwise identical to block_scores_kernel");
return 0;
}