From c3cd1c998f3bd8f744c2fd0e978b2e35468f3d45 Mon Sep 17 00:00:00 2001 From: rafasmour <54501936+rafasmour@users.noreply.github.com> Date: Fri, 4 Dec 2026 12:27:28 +0000 Subject: [PATCH] qwen4 QSA: fuse the pooled-key gather into the lightning indexer, one-block top-k, shared constant fills - lightning indexer: the 4-head vec and tile kernels take an optional row-index pointer; a new matcher (GET_ROWS, RESHAPE, LIGHTNING_INDEXER) scores the pooled keys straight from the f16/q8_0 cache rows instead of materializing all n_pool keys as f32. Bit identical. GGML_CUDA_NO_LI_GATHER_FUSION=1 disables. - top-k: one 1024-thread block per row (HIP, nrows <= 8, ne0 > 1024, k > 32), 4 radix passes in one launch with the same selection as the radix path (greater keys, then the lowest columns of the ties). GGML_CUDA_TOP_K_NO_ONEBLOCK=1 disables, GGML_CUDA_TOP_K_ONEBLOCK_MAX_ROWS= (default 8). - qwen4exp graph: the head-weight, k-mask and pooled-zero fills are built once per graph. - tests: LIGHTNING_INDEXER_GATHER, TOP_K k=512 eval and perf cases. Assisted-by: Claude Sonnet 5.5 --- ggml/src/ggml-cuda/fusion.cu | 36 ++++ ggml/src/ggml-cuda/lightning-indexer.cu | 87 +++++++-- ggml/src/ggml-cuda/lightning-indexer.cuh | 5 + ggml/src/ggml-cuda/top-k.cu | 233 +++++++++++++++++++++++ src/models/models.h | 5 + src/models/qwen4exp.cpp | 20 +- tests/test-backend-ops.cpp | 116 +++++++++++ 7 files changed, 488 insertions(+), 14 deletions(-) diff --git a/ggml/src/ggml-cuda/fusion.cu b/ggml/src/ggml-cuda/fusion.cu index d5eff36cb844..bad93f391a31 100644 --- a/ggml/src/ggml-cuda/fusion.cu +++ b/ggml/src/ggml-cuda/fusion.cu @@ -7,6 +7,7 @@ #include "fwht.cuh" #include "gated_delta_net.cuh" #include "inkling2.cuh" +#include "lightning-indexer.cuh" #include "mmsm.cuh" #include "mmsk.cuh" #include "mmq.cuh" @@ -2446,6 +2447,35 @@ static int ggml_cuda_try_fuse_rms_norm_set_rows(ggml_backend_cuda_context * cuda return last - i; } +// Qwen4 QSA: GET_ROWS of the pooled keys in the key cache, RESHAPE, LIGHTNING_INDEXER -> the indexer reads the keys from the +// cache rows, the f32 copy of all pooled keys is not made. GGML_CUDA_NO_LI_GATHER_FUSION=1 turns it off. +static int ggml_cuda_try_fuse_li_gather(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i) { + static const bool disabled = [] { + const char * env = getenv("GGML_CUDA_NO_LI_GATHER_FUSION"); + return env != nullptr && strcmp(env, "0") != 0; + }(); + if (disabled || cuda_ctx->curr_stream_no != 0 || i + 2 >= cgraph->n_nodes) { + return 0; + } + ggml_tensor ** n = cgraph->nodes + i; + if (n[0]->op != GGML_OP_GET_ROWS || n[1]->op != GGML_OP_RESHAPE || n[1]->src[0] != n[0] || + n[2]->op != GGML_OP_LIGHTNING_INDEXER || n[2]->src[1] != n[1] || n[2]->src[0] == n[1] || n[2]->src[2] == n[1] || n[2]->src[3] == n[1]) { + return 0; + } + // the GET_ROWS result and its reshape have no other consumer and are no graph outputs + const ggml_op ops[] = { GGML_OP_GET_ROWS, GGML_OP_RESHAPE, GGML_OP_LIGHTNING_INDEXER }; + const int outputs[] = { i + 2 }; + if (!ggml_can_fuse_subgraph(cgraph, i, 3, ops, outputs, 1)) { + return 0; + } + if (!ggml_cuda_check_fusion_memory_ranges(cgraph, i, 3, outputs, 1) || + !ggml_cuda_lightning_indexer_rows_supported(cuda_ctx->device, n[2], n[0])) { + return 0; + } + ggml_cuda_op_lightning_indexer_rows(*cuda_ctx, n[2], n[0]); + return 2; +} + // try and fuse nodes and return the number of nodes to skip int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i) { if (int n = ggml_cuda_try_fuse_inkling2(cuda_ctx, cgraph, i)) { @@ -2454,6 +2484,12 @@ int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgrap ggml_tensor * node = cgraph->nodes[i]; + if (node->op == GGML_OP_GET_ROWS) { + if (int n = ggml_cuda_try_fuse_li_gather(cuda_ctx, cgraph, i)) { + return n; + } + } + if (node->op == GGML_OP_MUL_MAT) { if (int n = ggml_cuda_try_fuse_fwht_set_rows(cuda_ctx, cgraph, i)) { return n; diff --git a/ggml/src/ggml-cuda/lightning-indexer.cu b/ggml/src/ggml-cuda/lightning-indexer.cu index b5a5b14911d1..2b18b11a618f 100644 --- a/ggml/src/ggml-cuda/lightning-indexer.cu +++ b/ggml/src/ggml-cuda/lightning-indexer.cu @@ -25,8 +25,10 @@ static __global__ void lightning_indexer_kernel_mma( size_t nbk1, size_t nbk2, size_t nbk3, size_t nbw1, size_t nbw2, size_t nbw3, size_t nbm1, size_t nbm2, size_t nbm3, - int64_t nem3 + int64_t nem3, const int32_t * K_rows ) { + GGML_UNUSED(K_rows); // the gathered keys are scored by the vec and tile kernels only + constexpr int MMA_DIM = 16; constexpr int WAVE_SIZE = ggml_cuda_get_physical_warp_size(); constexpr int THREADS_PER_BLOCK = WARPS_PER_BLOCK * WAVE_SIZE; @@ -195,7 +197,7 @@ static __global__ void lightning_indexer_kernel_vec( size_t nbk1, size_t nbk2, size_t nbk3, size_t nbw1, size_t nbw2, size_t nbw3, size_t nbm1, size_t nbm2, size_t nbm3, - int64_t nem3 + int64_t nem3, const int32_t * K_rows ) { constexpr int K_VECS_PER_WARP = K_VECS_PER_BLOCK / WARPS_PER_BLOCK; @@ -224,7 +226,8 @@ static __global__ void lightning_indexer_kernel_vec( for (int k = 0; k < K_VECS_PER_WARP; ++k) { int i_kv = start_kv + k; if (i_kv < n_kv) { - const float4 * k_base = (const float4 *) ((const char *) K + i_kv*nbk2 + i_stream*nbk3); + const int64_t i_row = K_rows ? K_rows[i_kv] : i_kv; + const float4 * k_base = (const float4 *) ((const char *) K + i_row*nbk2 + i_stream*nbk3); k_reg_f[k] = k_base[i_lane]; } else { k_reg_f[k] = make_float4(0, 0, 0, 0); @@ -237,7 +240,8 @@ static __global__ void lightning_indexer_kernel_vec( for (int k = 0; k < K_VECS_PER_WARP; ++k) { int i_kv = start_kv + k; if (i_kv < n_kv) { - const void * k_base = (const void *) ((const char *) K + i_kv*nbk2 + i_stream*nbk3); + const int64_t i_row = K_rows ? K_rows[i_kv] : i_kv; + const void * k_base = (const void *) ((const char *) K + i_row*nbk2 + i_stream*nbk3); dequantize_k(k_base, &k_reg_f[k], i_lane * 4); } else { k_reg_f[k] = make_float4(0, 0, 0, 0); @@ -341,7 +345,7 @@ static __global__ void lightning_indexer_kernel_tile( size_t nbk1, size_t nbk2, size_t nbk3, size_t nbw1, size_t nbw2, size_t nbw3, size_t nbm1, size_t nbm2, size_t nbm3, - int64_t nem3 + int64_t nem3, const int32_t * K_rows ) { constexpr int THREADS_PER_BLOCK = WARPS_PER_BLOCK * WARP_SIZE; @@ -375,7 +379,8 @@ static __global__ void lightning_indexer_kernel_tile( half2 lo = make_half2(0.0f, 0.0f); half2 hi = lo; if (start_kv + r < n_kv) { - const char * k_row = K + (start_kv + r)*nbk2 + i_stream*nbk3; + const int64_t i_row = K_rows ? K_rows[start_kv + r] : start_kv + r; + const char * k_row = K + i_row*nbk2 + i_stream*nbk3; if constexpr (TYPE_K == GGML_TYPE_F16) { lo = ((const half2 *) k_row)[2*c4 + 0]; hi = ((const half2 *) k_row)[2*c4 + 1]; @@ -494,16 +499,18 @@ static __global__ void lightning_indexer_kernel_tile( n_stream, n_batch, n_kv, \ nb1, nb2, nb3, \ nbq1, nbq2, nbq3, \ - nbk1, nbk2, nbk3, \ + nbk1, k_nb2, k_nb3, \ nbw1, nbw2, nbw3, \ nbm1, nbm2, nbm3, \ - nem3 \ + nem3, rows_d \ ); \ } else -void ggml_cuda_lightning_indexer(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { +// k is the tensor the keys are read from: dst->src[1], or with rows the 2-D source of the GET_ROWS that +// made it, and then rows[i] is the row of key i and n_kv_rows their number +static void lightning_indexer_launch( + ggml_backend_cuda_context & ctx, ggml_tensor * dst, const ggml_tensor * k, const int32_t * rows_d, int64_t n_kv_rows) { const ggml_tensor * q = dst->src[0]; - const ggml_tensor * k = dst->src[1]; const ggml_tensor * w = dst->src[2]; // weights const ggml_tensor * m = dst->src[3]; // mask @@ -539,7 +546,12 @@ void ggml_cuda_lightning_indexer(ggml_backend_cuda_context & ctx, ggml_tensor * const int n_head = q->ne[1]; const int n_batch = q->ne[2]; const int n_stream = q->ne[3]; - const int n_kv = k->ne[2]; + const int n_kv = rows_d ? n_kv_rows : k->ne[2]; + + // key row strides: a gathered key is a row of the 2-D source, one stream + const size_t k_nb2 = rows_d ? nbk1 : nbk2; + const size_t k_nb3 = rows_d ? 0 : nbk3; + GGML_ASSERT(!rows_d || (n_stream == 1 && n_embd == 128 && n_head == 4)); const float * q_d = (const float *) q->data; const char * k_d = (const char *) k->data; @@ -701,6 +713,59 @@ void ggml_cuda_lightning_indexer(ggml_backend_cuda_context & ctx, ggml_tensor * } } +void ggml_cuda_lightning_indexer(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { + lightning_indexer_launch(ctx, dst, dst->src[1], nullptr, 0); +} + +// GET_ROWS of a key cache + RESHAPE + LIGHTNING_INDEXER: the indexer reads the keys straight from the cache rows, +// the gathered f32 copy is never made. The keys are widened exactly as GET_ROWS widens them (f16 is exact, q8_0 is +// d*q in f32 with the same single multiply), so the scores are bit identical. +void ggml_cuda_op_lightning_indexer_rows(ggml_backend_cuda_context & ctx, ggml_tensor * dst, const ggml_tensor * get_rows) { + const ggml_tensor * src0 = get_rows->src[0]; + const ggml_tensor * rows = get_rows->src[1]; + + lightning_indexer_launch(ctx, dst, src0, (const int32_t *) rows->data, get_rows->ne[1]); +} + +bool ggml_cuda_lightning_indexer_rows_supported(int device, const ggml_tensor * dst, const ggml_tensor * get_rows) { + const ggml_tensor * src0 = get_rows->src[0]; + const ggml_tensor * rows = get_rows->src[1]; + const ggml_tensor * q = dst->src[0]; + const ggml_tensor * k = dst->src[1]; + + if (!ggml_cuda_lightning_indexer_supported(device, dst)) { + return false; + } + + // the 4 head vec and tile kernels only, one stream + if (q->ne[0] != 128 || q->ne[1] != 4 || q->ne[3] != 1 || k->ne[3] != 1) { + return false; + } + + // the keys the indexer would have read: the rows of a 2-D cache view + if (get_rows->type != GGML_TYPE_F32 || k->type != GGML_TYPE_F32 || k->ne[0] != 128 || k->ne[1] != 1 || + k->ne[2] != get_rows->ne[1] || get_rows->ne[0] != 128 || get_rows->ne[2] != 1 || get_rows->ne[3] != 1) { + return false; + } + if (src0->ne[0] != 128 || src0->ne[2] != 1 || src0->ne[3] != 1 || src0->nb[0] != ggml_type_size(src0->type)) { + return false; + } + if (rows->type != GGML_TYPE_I32 || rows->ne[0] != get_rows->ne[1] || rows->ne[1] != 1 || rows->ne[2] != 1 || + rows->ne[3] != 1 || rows->nb[0] != sizeof(int32_t)) { + return false; + } + + // the key loads of the kernels: f16 in 8 byte pieces, q8_0 in 2 byte aligned quants + switch (src0->type) { + case GGML_TYPE_F16: + return src0->nb[1] % 8 == 0 && (uintptr_t) src0->data % 8 == 0; + case GGML_TYPE_Q8_0: + return src0->nb[1] % 2 == 0 && (uintptr_t) src0->data % 2 == 0; + default: + return false; + } +} + bool ggml_cuda_lightning_indexer_supported(int device, const ggml_tensor * dst) { GGML_UNUSED(device); diff --git a/ggml/src/ggml-cuda/lightning-indexer.cuh b/ggml/src/ggml-cuda/lightning-indexer.cuh index f2fc95181339..a6e9d021e915 100644 --- a/ggml/src/ggml-cuda/lightning-indexer.cuh +++ b/ggml/src/ggml-cuda/lightning-indexer.cuh @@ -2,3 +2,8 @@ void ggml_cuda_lightning_indexer(ggml_backend_cuda_context & ctx, ggml_tensor * dst); bool ggml_cuda_lightning_indexer_supported(int device, const ggml_tensor * dst); + +// the keys gathered by get_rows (src[0] a 2-D f16 or q8_0 cache view, src[1] the I32 rows) read in place: the indexer must score +// the reshape of get_rows and use the 4 head kernels +bool ggml_cuda_lightning_indexer_rows_supported(int device, const ggml_tensor * dst, const ggml_tensor * get_rows); +void ggml_cuda_op_lightning_indexer_rows(ggml_backend_cuda_context & ctx, ggml_tensor * dst, const ggml_tensor * get_rows); diff --git a/ggml/src/ggml-cuda/top-k.cu b/ggml/src/ggml-cuda/top-k.cu index 1035d1a27217..7cf903014866 100644 --- a/ggml/src/ggml-cuda/top-k.cu +++ b/ggml/src/ggml-cuda/top-k.cu @@ -1,5 +1,6 @@ #include "argsort.cuh" #include "top-k.cuh" +#include // Adjusted implementation thresholds from #28547, can be overridden at build time #ifndef GGML_CUDA_TOP_K_NCOLS_THRESHOLD_BITONIC @@ -47,6 +48,20 @@ using namespace cub; # endif #endif // GGML_CUDA_TOP_K_SELECT_MAX_K +// one block per row for few long rows, instead of the ten launches of the radix path: 1 enables it, not measured outside HIP +#ifndef GGML_CUDA_TOP_K_ONEBLOCK +# if defined(GGML_USE_HIP) +# define GGML_CUDA_TOP_K_ONEBLOCK 1 +# else +# define GGML_CUDA_TOP_K_ONEBLOCK 0 +# endif +#endif // GGML_CUDA_TOP_K_ONEBLOCK + +// at most this many rows take the one block path, GGML_CUDA_TOP_K_ONEBLOCK_MAX_ROWS overrides, GGML_CUDA_TOP_K_NO_ONEBLOCK=1 disables +#ifndef GGML_CUDA_TOP_K_ONEBLOCK_MAX_ROWS +# define GGML_CUDA_TOP_K_ONEBLOCK_MAX_ROWS 8 +#endif // GGML_CUDA_TOP_K_ONEBLOCK_MAX_ROWS + // max rows for the per-row DeviceTopK / CUB argsort path before switching to radix / bitonic #ifndef GGML_CUDA_TOP_K_NROWS_THRESHOLD # ifdef CUB_TOP_K_AVAILABLE @@ -425,6 +440,219 @@ static void top_k_select_cuda( } } +// One block per row: the radix select of top_k_radix_cuda in a single launch, with the same selection: the elements above +// the k-th largest key, and of those equal to it the lowest columns, so the index sets are identical. The greater +// elements are written in column order, the ties after them, again in column order. +// The row is read in tiles of 1024 columns, thread t owns column i*1024 + t of tile i. With C_MAX > 0 the keys of the +// row stay in registers for all passes (rows of up to C_MAX tiles), C_MAX == 0 reads them again in every pass. +// The 8 bit histogram of a pass has one copy per lane (padded, so equal digits of a warp are in different banks), the +// bin of the k-th largest key is found by a suffix scan of the digit counts. +#define TOP_K_ONEBLOCK_THREADS 1024 + +template +static __global__ void __launch_bounds__(TOP_K_ONEBLOCK_THREADS) top_k_oneblock( + const float * __restrict__ src, + int * __restrict__ dst, + const int ncols, + const int k) { + constexpr int BLOCK_SIZE = TOP_K_ONEBLOCK_THREADS; + constexpr int NBINS = 256; + constexpr int warp_size = ggml_cuda_get_physical_warp_size(); + constexpr int nwarps = BLOCK_SIZE / warp_size; + constexpr int NCOPIES = warp_size < 32 ? warp_size : 32; + constexpr int COPY_STRIDE = NBINS + 1; + constexpr int SCAN_WARPS = NBINS / warp_size; + static_assert(nwarps % 4 == 0, "the per warp counts are read four at a time"); + + __shared__ int histogram[NCOPIES*COPY_STRIDE]; + __shared__ int warp_sums[SCAN_WARPS]; + __shared__ __align__(16) int warp_counts[2][nwarps]; + __shared__ int selected[2]; + + const int tid = threadIdx.x; + const int lane = tid % warp_size; + const int warp = tid / warp_size; + const int nt = (ncols + BLOCK_SIZE - 1) / BLOCK_SIZE; // tiles of the row + + const float * row_src = src + (size_t) blockIdx.x * ncols; + int * row_dst = dst + (size_t) blockIdx.x * k; + + uint32_t keys[C_MAX > 0 ? C_MAX : 1]; + if constexpr (C_MAX > 0) { +#pragma unroll + for (int i = 0; i < C_MAX; ++i) { + const int col = i*BLOCK_SIZE + tid; + keys[i] = (i < nt && col < ncols) ? top_k_float_to_ordered(row_src[col]) : 0u; + } + } + + uint32_t prefix = 0; + uint32_t prefix_mask = 0; + int rank = k; // the rank of the k-th largest key among the keys of the prefix + +#pragma unroll 1 + for (int shift = 32 - 8; shift >= 0; shift -= 8) { + for (int i = tid; i < NCOPIES*COPY_STRIDE; i += BLOCK_SIZE) { + histogram[i] = 0; + } + __syncthreads(); + + int * hist = histogram + (lane % NCOPIES)*COPY_STRIDE; + if constexpr (C_MAX > 0) { +#pragma unroll + for (int i = 0; i < C_MAX; ++i) { + if (i < nt && i*BLOCK_SIZE + tid < ncols && (keys[i] & prefix_mask) == prefix) { + atomicAdd(&hist[(keys[i] >> shift) & (NBINS - 1)], 1); + } + } + } else { + for (int col = tid; col < ncols; col += BLOCK_SIZE) { + const uint32_t key = top_k_float_to_ordered(row_src[col]); + if ((key & prefix_mask) == prefix) { + atomicAdd(&hist[(key >> shift) & (NBINS - 1)], 1); + } + } + } + __syncthreads(); + + // thread t scans the bin 255 - t, so the inclusive prefix of the threads is the count of the keys of this bin and above + int count = 0; + int incl = 0; + if (tid < NBINS) { +#pragma unroll + for (int c = 0; c < NCOPIES; ++c) { + count += histogram[c*COPY_STRIDE + (NBINS - 1 - tid)]; + } + incl = count; +#pragma unroll + for (int offset = 1; offset < warp_size; offset <<= 1) { + const int y = ggml_cuda_shfl_up(incl, offset, warp_size); + incl += lane >= offset ? y : 0; + } + if (lane == warp_size - 1) { + warp_sums[warp] = incl; + } + } + __syncthreads(); + if (tid < NBINS) { + for (int w = 0; w < warp; ++w) { + incl += warp_sums[w]; + } + const int excl = incl - count; + // the bin that holds the rank-th largest key: the keys above it are fewer than the rank, with it they are not + if (excl < rank && rank <= incl) { + selected[0] = NBINS - 1 - tid; + selected[1] = rank - excl; + } + } + __syncthreads(); + + prefix |= (uint32_t) selected[0] << shift; + prefix_mask |= (uint32_t) (NBINS - 1) << shift; + rank = selected[1]; + } + + // prefix is the k-th largest key, rank of the elements equal to it are taken, the others above it are all taken + const int n_greater = k - rank; + int pos_greater = 0; + int pos_tie = 0; + + const ggml_cuda_thread_mask_t lane_mask = ((ggml_cuda_thread_mask_t) 1 << lane) - 1; + + // writes the greater elements and the ties of tile t, returns whether the selection is complete, the same in all threads + auto write_tile = [&](const int t, const uint32_t key) -> bool { + const int col = t*BLOCK_SIZE + tid; + const bool valid = col < ncols; + const bool greater = valid && key > prefix; + const bool tie = valid && key == prefix; + + const ggml_cuda_thread_mask_t m_greater = ggml_cuda_ballot(greater); + const ggml_cuda_thread_mask_t m_tie = ggml_cuda_ballot(tie); + const int lane_greater = ggml_cuda_popc(m_greater & lane_mask); + const int lane_tie = ggml_cuda_popc(m_tie & lane_mask); + + // the counts of the tile are exchanged through a buffer per parity of the tile: a warp that has passed the barrier + // of the next tile has not written this buffer again before every warp has read it + int * counts = warp_counts[t & 1]; + if (lane == 0) { + counts[warp] = ggml_cuda_popc(m_greater) | (ggml_cuda_popc(m_tie) << 16); + } + __syncthreads(); + + int before = 0; // the counts of the warps in front of this one + int total = 0; // the counts of the tile +#pragma unroll + for (int w4 = 0; w4 < nwarps/4; ++w4) { + const int4 c = ((const int4 *) counts)[w4]; + before += (4*w4 + 0 < warp ? c.x : 0) + (4*w4 + 1 < warp ? c.y : 0) + (4*w4 + 2 < warp ? c.z : 0) + (4*w4 + 3 < warp ? c.w : 0); + total += c.x + c.y + c.z + c.w; + } + + if (greater) { + row_dst[pos_greater + (before & 0xFFFF) + lane_greater] = col; + } + if (tie) { + const int pos = pos_tie + (before >> 16) + lane_tie; + if (pos < rank) { + row_dst[n_greater + pos] = col; + } + } + pos_greater += total & 0xFFFF; + pos_tie += total >> 16; + + return pos_greater >= n_greater && pos_tie >= rank; + }; + + if constexpr (C_MAX > 0) { + // no early exit out of the unrolled loop: the keys must stay in registers + bool done = false; +#pragma unroll + for (int i = 0; i < C_MAX; ++i) { + if (!done && i < nt) { + done = write_tile(i, keys[i]); + } + } + } else { + for (int t = 0; t < nt; ++t) { + const int col = t*BLOCK_SIZE + tid; + if (write_tile(t, col < ncols ? top_k_float_to_ordered(row_src[col]) : 0u)) { + return; + } + } + } +} + +static void top_k_oneblock_cuda( + const float * src, int * dst, int ncols, int64_t nrows, int k, cudaStream_t stream) { + const int ntiles = (ncols + TOP_K_ONEBLOCK_THREADS - 1) / TOP_K_ONEBLOCK_THREADS; + const dim3 grid((unsigned int) nrows); + + if (ntiles <= 4) { + top_k_oneblock<4><<>>(src, dst, ncols, k); + } else if (ntiles <= 16) { + top_k_oneblock<16><<>>(src, dst, ncols, k); + } else if (ntiles <= 48) { + top_k_oneblock<48><<>>(src, dst, ncols, k); + } else { + top_k_oneblock<0><<>>(src, dst, ncols, k); + } +} + +static bool top_k_oneblock_enabled(int64_t ncols, int64_t nrows, int64_t k) { + static const bool disabled = [] { + const char * env = getenv("GGML_CUDA_TOP_K_NO_ONEBLOCK"); + return env != nullptr && strcmp(env, "0") != 0; + }(); + static const int64_t max_rows = [] { + const char * env = getenv("GGML_CUDA_TOP_K_ONEBLOCK_MAX_ROWS"); + return env != nullptr ? (int64_t) atoi(env) : (int64_t) GGML_CUDA_TOP_K_ONEBLOCK_MAX_ROWS; + }(); + + // short rows are sorted, small k is selected by rounds of a block maximum + return GGML_CUDA_TOP_K_ONEBLOCK && !disabled && nrows <= max_rows && + ncols > GGML_CUDA_TOP_K_NCOLS_THRESHOLD_BITONIC && k > GGML_CUDA_TOP_K_SELECT_MAX_K && k <= ncols; +} + // long rows without a sort: by selection for small k, else by radix passes static void top_k_long_rows_cuda( ggml_cuda_pool & pool, @@ -501,6 +729,11 @@ void ggml_cuda_op_top_k(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { } } + if (top_k_oneblock_enabled(ncols, nrows, k)) { + top_k_oneblock_cuda(src0_d, dst_d, ncols, nrows, k, stream); + return; + } + if (nrows > GGML_CUDA_TOP_K_NROWS_THRESHOLD) { top_k_long_rows_cuda(pool, src0_d, dst_d, ncols, nrows, k, stream); return; diff --git a/src/models/models.h b/src/models/models.h index d73231b6ac12..40e0727dd462 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -3184,6 +3184,11 @@ struct llama_model_qwen4exp : public llama_model_base { ggml_tensor * inp_pos, int il); + // constants every QSA layer reads, they depend on n_tokens and n_kv only: built once per graph, on the first use + ggml_tensor * qsa_pzero = nullptr; // [indexer_head_size, n_tokens] zeros, the pooled half of the fresh cache rows + ggml_tensor * qsa_weights = nullptr; // [indexer_n_head, n_tokens] the head weights of the indexer + ggml_tensor * qsa_keep = nullptr; // [n_kv] zeros, the input of the fused top-k mask + ggml_tensor * build_layer_attn_linear( llm_graph_input_rs * inp, ggml_tensor * cur, diff --git a/src/models/qwen4exp.cpp b/src/models/qwen4exp.cpp index a6bc485a9149..54468fc5d151 100644 --- a/src/models/qwen4exp.cpp +++ b/src/models/qwen4exp.cpp @@ -830,7 +830,13 @@ ggml_tensor * llama_model_qwen4exp::graph::build_qsa_sel( ggml_tensor * k_raw = build_lora_mm(model.layers[il].index_k_proj, cur); cb(k_raw, "indexer_k_raw", il); - ggml_tensor * pzero = ggml_fill(ctx0, ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, idx_dim, n_tokens), 0.0f); + // the fills below are the same in every QSA layer: one node each per graph, expanded where they are first made so they + // sit in front of the nodes of this layer + if (!qsa_pzero) { + qsa_pzero = ggml_fill(ctx0, ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, idx_dim, n_tokens), 0.0f); + ggml_build_forward_expand(gf, qsa_pzero); + } + ggml_tensor * pzero = qsa_pzero; ggml_tensor * packed = ggml_reshape_3d(ctx0, ggml_concat(ctx0, k_raw, pzero, 0), 2*idx_dim, 1, n_tokens); ggml_build_forward_expand(gf, mctx_idx->cpy_k(ctx0, packed, inp_kpool->k_idxs, il)); @@ -870,7 +876,11 @@ ggml_tensor * llama_model_qwen4exp::graph::build_qsa_sel( // the reference sums the rectified head scores unweighted, scaled by 1/sqrt(head_dim), // which is the lightning indexer with every head weight set to that scale - ggml_tensor * weights = ggml_fill(ctx0, ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_idx_h, n_tokens), 1.0f/sqrtf((float) idx_dim)); + if (!qsa_weights) { + qsa_weights = ggml_fill(ctx0, ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_idx_h, n_tokens), 1.0f/sqrtf((float) idx_dim)); + ggml_build_forward_expand(gf, qsa_weights); + } + ggml_tensor * weights = qsa_weights; ggml_tensor * score = ggml_lightning_indexer(ctx0, q, pooled, weights, inp_kpool->pool_mask); // [n_pool, n_tokens] cb(score, "indexer_score", il); @@ -886,7 +896,11 @@ ggml_tensor * llama_model_qwen4exp::graph::build_qsa_sel( if (cparams.fused_top_k_mask) { GGML_ASSERT(kpool*n_top_pool + inp_kpool->tail_idxs->ne[0] == inp_kpool->n_sel); - ggml_tensor * keep = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, type_mask, inp_kpool->n_kv), 0.0f); + if (!qsa_keep) { + qsa_keep = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, type_mask, inp_kpool->n_kv), 0.0f); + ggml_build_forward_expand(gf, qsa_keep); + } + ggml_tensor * keep = qsa_keep; ggml_tensor * sel = ggml_top_k_mask(ctx0, keep, top_k, score, inp_kpool->pool_idxs, inp_kpool->tail_idxs); // [n_kv, n_tokens] res->add_fused_node({LLM_FUSED_OP_TOP_K_MASK, sel, il}); cb(sel, "indexer_sel", il); diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index c3aa490e347b..58ef40f9e3b2 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -35,6 +35,7 @@ #include #include #include +#include #include #include #include @@ -12339,6 +12340,87 @@ struct test_lightning_indexer : public test_case { } }; +// w2 qwen4-qsa-indexer: the Qwen4 QSA pooled keys. GET_ROWS of the pooled half of the rows of a key cache +// (a 2-D view at the upper 128 columns, f16 or q8_0), RESHAPE, LIGHTNING_INDEXER with 4 heads: a backend may read the keys +// from the cache rows without making the f32 copy. The whole graph runs, so the fusion is exercised. +struct test_lightning_indexer_gather : public test_case { + const ggml_type type_K; // type of the key cache + const int64_t n_pool; // pooled keys gathered + const int64_t nb; // batch size + + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "LIGHTNING_INDEXER_GATHER"; + } + + std::string vars() override { + return VARS_TO_STR3(type_K, n_pool, nb); + } + + double max_nmse_err() override { + return 1e-6; + } + + bool run_whole_graph() override { return true; } + + uint64_t op_flops(ggml_tensor * t) override { + GGML_UNUSED(t); + return ((2 * 128 + 2) * 4 + 1) * n_pool * nb; + } + + test_lightning_indexer_gather(ggml_type type_K = GGML_TYPE_Q8_0, int64_t n_pool = 1000, int64_t nb = 1) + : type_K(type_K), n_pool(n_pool), nb(nb) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + const int64_t n_cells = n_pool + n_pool/4 + 1; + + // rows: raw key | pooled key, the pooled key is the upper half + ggml_tensor * cache = ggml_new_tensor_2d(ctx, type_K, 256, n_cells); + ggml_set_name(cache, "cache"); + ggml_tensor * pooled = ggml_view_2d(ctx, cache, 128, n_cells, cache->nb[1], ggml_row_size(type_K, 128)); + ggml_set_name(pooled, "pooled_view"); + + ggml_tensor * rows = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_pool); + ggml_set_name(rows, "rows"); + + ggml_tensor * k = ggml_reshape_3d(ctx, ggml_get_rows(ctx, pooled, rows), 128, 1, n_pool); + + ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 128, 4, nb, 1); + ggml_set_name(q, "q"); + + ggml_tensor * w = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 4, nb, 1, 1); + ggml_set_name(w, "w"); + + ggml_tensor * m = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, n_pool, nb, 1, 1); + ggml_set_name(m, "m"); + + ggml_tensor * out = ggml_lightning_indexer(ctx, q, k, w, m); + ggml_set_name(out, "out"); + + return out; + } + + void initialize_tensors(ggml_context * ctx) override { + std::default_random_engine rng(1234); + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) { + if (ggml_is_view_op(t->op) || t->op != GGML_OP_NONE) { + continue; + } + if (t->type == GGML_TYPE_I32) { + // a random subset of the cells, in random order + std::vector cells(t->ne[0] + t->ne[0]/4 + 1); + std::iota(cells.begin(), cells.end(), 0); + std::shuffle(cells.begin(), cells.end(), rng); + ggml_backend_tensor_set(t, cells.data(), 0, ggml_nbytes(t)); + } else if (strcmp(t->name, "m") == 0) { + init_tensor_kq_mask(t); + } else { + init_tensor_uniform(t); + } + } + } +}; + // GGML_OP_TOP_K_MASK struct test_top_k_mask : public test_case { const ggml_type type; @@ -17147,6 +17229,25 @@ static std::vector> make_test_cases_eval() { } } + // w2 qwen4-qsa-indexer: pooled keys gathered from the key cache, one block top-k of few long rows + for (ggml_type type_K : {GGML_TYPE_Q8_0, GGML_TYPE_F16}) { + for (int64_t n_pool : {1000, 24576}) { + for (int64_t nb : {1, 3, 512}) { + test_cases.emplace_back(new test_lightning_indexer_gather(type_K, n_pool, nb)); + } + } + } + for (int ne0 : {2048, 24576, 49152}) { + for (int nrows : {1, 3, 512}) { + test_cases.emplace_back(new test_top_k(GGML_TYPE_F32, {ne0, nrows, 1, 1}, 512)); + test_cases.emplace_back(new test_top_k(GGML_TYPE_F32, {ne0, nrows, 1, 1}, 512, true)); + test_cases.emplace_back(new test_top_k_inf({ne0, nrows, 1, 1}, 512)); + } + } + // rows of 1025 columns and k = ne0: every column is picked + test_cases.emplace_back(new test_top_k(GGML_TYPE_F32, {1025, 1, 1, 1}, 1025)); + test_cases.emplace_back(new test_top_k(GGML_TYPE_F32, {1025, 3, 1, 1}, 512, true)); + return test_cases; } #ifdef _MSC_VER @@ -17198,6 +17299,21 @@ static std::vector> make_test_cases_perf() { test_cases.emplace_back(new test_dsv4_hc_post(2560, n_tokens, true)); // synthetic, Qwen4-Exp kernel without the gate chain } + // w2 qwen4-qsa-indexer: decode (1 row), MTP verify (3 rows) and a prompt batch of the QSA selection at 32k to 192k of context + for (ggml_type type_K : {GGML_TYPE_Q8_0, GGML_TYPE_F16}) { + for (int64_t n_pool : {8192, 24576, 49152}) { + for (int64_t nb : {1, 3, 512}) { + test_cases.emplace_back(new test_lightning_indexer_gather(type_K, n_pool, nb)); + } + } + } + for (int ne0 : {8192, 24576, 49152}) { + for (int nrows : {1, 3, 8, 512}) { + test_cases.emplace_back(new test_top_k(GGML_TYPE_F32, {ne0, nrows, 1, 1}, 512)); + test_cases.emplace_back(new test_top_k(GGML_TYPE_F32, {ne0, nrows, 1, 1}, 512, true)); + } + } + // Qwen3.8-Flash-Next pooled indexer prefill. test_cases.emplace_back(new test_lightning_indexer(128, 4, 1088, 1024, 1, 1, GGML_TYPE_F32)); test_cases.emplace_back(new test_lightning_indexer(128, 4, 1088, 1024, 1, 1, GGML_TYPE_Q4_0));