prefill: the QSA top-k digit by a cooperative scan (same ids)

block_topk_reg_kernel picked each radix digit with thread 0 walking up to 255 bins while the other threads waited.
Threads 0-255 now prefix-sum the bins in descending order, and the one where the count above reaches `width` takes the
digit (bin 0 when none of 255..1 does). The digit and the count above are the same, so the selected ids are the same.

Measured on a Ryzen AI Max+ 395 (gfx1151, ROCm 7.14.1), qsa_topk_parity with 2,048 queries (CTX 2048 10 <ctx> 1),
ms per call:
  32K  2.19 -> 1.11 (-49%)
  64K  2.54 -> 1.63 (-36%)
  128K 4.83 -> 3.79 (-22%)
qsa_topk_parity --selftest: 19 PASS. UD-Q4_K_XL end to end, 3 interleaved rounds: the same text in every round; the
128K prompt moved +0.2%, inside the noise, so the gain is the kernel's and not yet visible end to end.

CUDA (RTX 3060, Windows, CUDA 13.0, sm_86), same call, ms: 4K 2.12 -> 0.975, 8K 2.04 -> 1.03, 16K ~1.9 -> ~1.1, 32K ~2.0 -> 1.27, 64K 2.53 -> 2.15, 128K 7.29 -> 7.29 (no change); qsa_topk_parity --selftest passes, ids identical in every case. Not built: SYCL.
This commit is contained in:
libratechw authored and Niko1221 committed 2026-10-14 07:08:23 +02:00
1 parent ccba2d5fd3
commit 6ef23b8966
1 file changed
+22 -7
+22 -7
View File
@@ -642,14 +642,29 @@ __global__ void __launch_bounds__(TK_T) block_topk_reg_kernel(const float* __res
hist[0][t] = s;
}
__syncthreads();
if (t == 0) {
int cum = above, d = 255;
for (; d > 0; --d) {
if (cum + hist[0][d] >= width) break;
cum += hist[0][d];
// the digit: the first bin from the top where the count above reaches `width` (bin 0 when none of 255..1
// does). Threads 0-255 (warps 0-7) prefix-sum the 256 bins in descending order instead of one thread
// walking them: the same digit and count above.
int v = 0, x = 0;
if (t < 256) {
v = hist[0][255 - t];
x = v;
#pragma unroll
for (int o = 1; o < 32; o <<= 1) {
const int y = __shfl_up_sync(0xffffffffu, x, o);
if (lane >= o) x += y;
}
if (lane == 31) s_warp[warp] = x;
}
__syncthreads();
if (t < 256) {
int inc = x;
for (int w2 = 0; w2 < warp; ++w2) inc += s_warp[w2];
const int before = above + inc - v;
if (before < width && (above + inc >= width || t == 255)) {
s_digit = 255 - t;
s_above = before;
}
s_digit = d;
s_above = cum;
}
__syncthreads();
prefix |= (uint32_t) s_digit << shift;