"""Custom CUDA top-k kernel using CUB merge-sort primitives. Two-stage design: 1. Each CUDA block sorts a chunk of an input row and writes its top-k (value, global-index) pairs to a temporary buffer. 2. A second kernel merges the per-block top-k arrays into the final top-k. A specialized argmax kernel is used for k == 1. """ import os import torch import torch.nn as nn from torch.utils.cpp_extension import load_inline # --------------------------------------------------------------------------- # CUDA source: kernels + host launcher functions. Compiled by nvcc. # --------------------------------------------------------------------------- _CUDA_SOURCE = r""" #include #include #include #include #include #include #include #define NEG_INF_F (-std::numeric_limits::infinity()) struct DescendingFloat { __device__ __forceinline__ bool operator()(const float &a, const float &b) const { return a > b; } }; extern "C" __global__ void argmax_256( const float *__restrict__ in, float *__restrict__ out_vals, int64_t *__restrict__ out_idxs, int n) { constexpr int BLOCK_THREADS = 256; using KVT = cub::KeyValuePair; using BlockReduceT = cub::BlockReduce; __shared__ typename BlockReduceT::TempStorage temp_storage; int row = blockIdx.x; KVT thread_kv; thread_kv.key = NEG_INF_F; thread_kv.value = -1; const float *row_in = in + static_cast(row) * n; for (int pos = threadIdx.x; pos < n; pos += BLOCK_THREADS) { float v = row_in[pos]; if (v > thread_kv.key) { thread_kv.key = v; thread_kv.value = static_cast(pos); } } KVT block_kv = BlockReduceT(temp_storage).Reduce(thread_kv, cub::ArgMax()); if (threadIdx.x == 0) { out_vals[row] = block_kv.key; out_idxs[row] = block_kv.value; } } #define TOPK_CORE(K, BLOCK_THREADS, READ_INDICES) \ do { \ constexpr int WARP_THREADS = 32; \ constexpr int WARPS = BLOCK_THREADS / WARP_THREADS; \ constexpr int K_IPT = (K + WARP_THREADS - 1) / WARP_THREADS; \ constexpr int MERGE_IPT = (WARPS * K + BLOCK_THREADS - 1) / BLOCK_THREADS; \ \ using WarpMergeT = cub::WarpMergeSort; \ using BlockMergeT = cub::BlockMergeSort; \ \ __shared__ typename WarpMergeT::TempStorage warp_temp[WARPS]; \ __shared__ typename BlockMergeT::TempStorage block_temp; \ __shared__ float smem_vals[WARPS * K]; \ __shared__ int64_t smem_idxs[WARPS * K]; \ \ int lane = threadIdx.x % WARP_THREADS; \ int warp_id = threadIdx.x / WARP_THREADS; \ \ const float *row_in_vals = in_vals + in_offset; \ const int64_t *row_in_idxs = READ_INDICES ? (in_idxs + in_offset) : nullptr; \ \ float local_vals[K_IPT]; \ int64_t local_idxs[K_IPT]; \ _Pragma("unroll") \ for (int i = 0; i < K_IPT; ++i) { \ local_vals[i] = NEG_INF_F; \ local_idxs[i] = -1; \ } \ \ for (int pos = threadIdx.x; pos < m; pos += BLOCK_THREADS) { \ float v = row_in_vals[pos]; \ int64_t idx; \ if (READ_INDICES) { \ idx = row_in_idxs[pos]; \ } else { \ idx = static_cast(index_base + pos); \ } \ if (v > local_vals[K_IPT - 1]) { \ int j = K_IPT - 1; \ while (j > 0 && v > local_vals[j - 1]) { \ local_vals[j] = local_vals[j - 1]; \ local_idxs[j] = local_idxs[j - 1]; \ --j; \ } \ local_vals[j] = v; \ local_idxs[j] = idx; \ } \ } \ \ DescendingFloat desc; \ WarpMergeT(warp_temp[warp_id]).Sort(local_vals, local_idxs, desc); \ \ _Pragma("unroll") \ for (int i = 0; i < K_IPT; ++i) { \ int pos = lane * K_IPT + i; \ if (pos < K) { \ smem_vals[warp_id * K + pos] = local_vals[i]; \ smem_idxs[warp_id * K + pos] = local_idxs[i]; \ } \ } \ __syncthreads(); \ \ float merge_vals[MERGE_IPT]; \ int64_t merge_idxs[MERGE_IPT]; \ _Pragma("unroll") \ for (int i = 0; i < MERGE_IPT; ++i) { \ int pos = threadIdx.x * MERGE_IPT + i; \ if (pos < WARPS * K) { \ merge_vals[i] = smem_vals[pos]; \ merge_idxs[i] = smem_idxs[pos]; \ } else { \ merge_vals[i] = NEG_INF_F; \ merge_idxs[i] = -1; \ } \ } \ \ int valid_merge = WARPS * K; \ if (valid_merge == BLOCK_THREADS * MERGE_IPT) { \ BlockMergeT(block_temp).Sort(merge_vals, merge_idxs, desc); \ } else { \ BlockMergeT(block_temp).Sort(merge_vals, merge_idxs, desc, valid_merge, NEG_INF_F); \ } \ \ float *row_out_vals = out_vals + out_offset; \ int64_t *row_out_idxs = out_idxs + out_offset; \ _Pragma("unroll") \ for (int i = 0; i < K_IPT; ++i) { \ int pos = threadIdx.x * K_IPT + i; \ if (pos < k) { \ row_out_vals[pos] = merge_vals[i]; \ row_out_idxs[pos] = merge_idxs[i]; \ } \ } \ } while (0) #define DEFINE_STAGE1(K) \ extern "C" __global__ void topk_stage1_k##K( \ const float *__restrict__ in_vals, \ const int64_t *__restrict__ in_idxs, \ float *__restrict__ out_vals, \ int64_t *__restrict__ out_idxs, \ int n, int blocks_per_row, int chunk_size, int k) \ { \ int block_global = blockIdx.x; \ int row = block_global / blocks_per_row; \ int block_in_row = block_global % blocks_per_row; \ int start = block_in_row * chunk_size; \ int m = (start + chunk_size <= n) ? chunk_size : (n - start); \ int64_t in_offset = static_cast(row) * n + start; \ int64_t out_offset = static_cast(block_global) * k; \ int index_base = start; \ TOPK_CORE(K, 128, false); \ } DEFINE_STAGE1(8) DEFINE_STAGE1(16) DEFINE_STAGE1(32) DEFINE_STAGE1(64) #define DEFINE_STAGE2(K) \ extern "C" __global__ void topk_stage2_k##K( \ const float *__restrict__ in_vals, \ const int64_t *__restrict__ in_idxs, \ float *__restrict__ out_vals, \ int64_t *__restrict__ out_idxs, \ int blocks_per_row, int k) \ { \ int row = blockIdx.x; \ int m = blocks_per_row * k; \ int64_t in_offset = static_cast(row) * m; \ int64_t out_offset = static_cast(row) * k; \ int index_base = 0; \ TOPK_CORE(K, 128, true); \ } DEFINE_STAGE2(8) DEFINE_STAGE2(16) DEFINE_STAGE2(32) DEFINE_STAGE2(64) // --------------------------------------------------------------------------- // Host launcher functions (compiled by nvcc, declared to g++ via cpp_sources). // --------------------------------------------------------------------------- void launch_argmax_256(torch::Tensor in, torch::Tensor out_vals, torch::Tensor out_idxs, int n, int grid, int block) { argmax_256<<>>( in.data_ptr(), out_vals.data_ptr(), out_idxs.data_ptr(), n); } static int64_t *idx_ptr(torch::Tensor t) { return (t.defined() && t.numel() > 0) ? t.data_ptr() : nullptr; } void launch_stage1_k8(torch::Tensor in_vals, torch::Tensor in_idxs, torch::Tensor out_vals, torch::Tensor out_idxs, int n, int blocks_per_row, int chunk_size, int k, int grid, int block) { topk_stage1_k8<<>>( in_vals.data_ptr(), idx_ptr(in_idxs), out_vals.data_ptr(), out_idxs.data_ptr(), n, blocks_per_row, chunk_size, k); } void launch_stage1_k16(torch::Tensor in_vals, torch::Tensor in_idxs, torch::Tensor out_vals, torch::Tensor out_idxs, int n, int blocks_per_row, int chunk_size, int k, int grid, int block) { topk_stage1_k16<<>>( in_vals.data_ptr(), idx_ptr(in_idxs), out_vals.data_ptr(), out_idxs.data_ptr(), n, blocks_per_row, chunk_size, k); } void launch_stage1_k32(torch::Tensor in_vals, torch::Tensor in_idxs, torch::Tensor out_vals, torch::Tensor out_idxs, int n, int blocks_per_row, int chunk_size, int k, int grid, int block) { topk_stage1_k32<<>>( in_vals.data_ptr(), idx_ptr(in_idxs), out_vals.data_ptr(), out_idxs.data_ptr(), n, blocks_per_row, chunk_size, k); } void launch_stage1_k64(torch::Tensor in_vals, torch::Tensor in_idxs, torch::Tensor out_vals, torch::Tensor out_idxs, int n, int blocks_per_row, int chunk_size, int k, int grid, int block) { topk_stage1_k64<<>>( in_vals.data_ptr(), idx_ptr(in_idxs), out_vals.data_ptr(), out_idxs.data_ptr(), n, blocks_per_row, chunk_size, k); } void launch_stage2_k8(torch::Tensor in_vals, torch::Tensor in_idxs, torch::Tensor out_vals, torch::Tensor out_idxs, int blocks_per_row, int k, int grid, int block) { topk_stage2_k8<<>>( in_vals.data_ptr(), in_idxs.data_ptr(), out_vals.data_ptr(), out_idxs.data_ptr(), blocks_per_row, k); } void launch_stage2_k16(torch::Tensor in_vals, torch::Tensor in_idxs, torch::Tensor out_vals, torch::Tensor out_idxs, int blocks_per_row, int k, int grid, int block) { topk_stage2_k16<<>>( in_vals.data_ptr(), in_idxs.data_ptr(), out_vals.data_ptr(), out_idxs.data_ptr(), blocks_per_row, k); } void launch_stage2_k32(torch::Tensor in_vals, torch::Tensor in_idxs, torch::Tensor out_vals, torch::Tensor out_idxs, int blocks_per_row, int k, int grid, int block) { topk_stage2_k32<<>>( in_vals.data_ptr(), in_idxs.data_ptr(), out_vals.data_ptr(), out_idxs.data_ptr(), blocks_per_row, k); } void launch_stage2_k64(torch::Tensor in_vals, torch::Tensor in_idxs, torch::Tensor out_vals, torch::Tensor out_idxs, int blocks_per_row, int k, int grid, int block) { topk_stage2_k64<<>>( in_vals.data_ptr(), in_idxs.data_ptr(), out_vals.data_ptr(), out_idxs.data_ptr(), blocks_per_row, k); } """ # --------------------------------------------------------------------------- # C++ declarations: only launcher signatures, no kernel launch syntax here. # Compiled by g++ and used by load_inline's generated pybind11 wrapper. # --------------------------------------------------------------------------- _CPP_DECLS = r""" #include void launch_argmax_256(torch::Tensor in, torch::Tensor out_vals, torch::Tensor out_idxs, int n, int grid, int block); void launch_stage1_k8(torch::Tensor in_vals, torch::Tensor in_idxs, torch::Tensor out_vals, torch::Tensor out_idxs, int n, int blocks_per_row, int chunk_size, int k, int grid, int block); void launch_stage1_k16(torch::Tensor in_vals, torch::Tensor in_idxs, torch::Tensor out_vals, torch::Tensor out_idxs, int n, int blocks_per_row, int chunk_size, int k, int grid, int block); void launch_stage1_k32(torch::Tensor in_vals, torch::Tensor in_idxs, torch::Tensor out_vals, torch::Tensor out_idxs, int n, int blocks_per_row, int chunk_size, int k, int grid, int block); void launch_stage1_k64(torch::Tensor in_vals, torch::Tensor in_idxs, torch::Tensor out_vals, torch::Tensor out_idxs, int n, int blocks_per_row, int chunk_size, int k, int grid, int block); void launch_stage2_k8(torch::Tensor in_vals, torch::Tensor in_idxs, torch::Tensor out_vals, torch::Tensor out_idxs, int blocks_per_row, int k, int grid, int block); void launch_stage2_k16(torch::Tensor in_vals, torch::Tensor in_idxs, torch::Tensor out_vals, torch::Tensor out_idxs, int blocks_per_row, int k, int grid, int block); void launch_stage2_k32(torch::Tensor in_vals, torch::Tensor in_idxs, torch::Tensor out_vals, torch::Tensor out_idxs, int blocks_per_row, int k, int grid, int block); void launch_stage2_k64(torch::Tensor in_vals, torch::Tensor in_idxs, torch::Tensor out_vals, torch::Tensor out_idxs, int blocks_per_row, int k, int grid, int block); """ def _compile(): extra_cuda_cflags = ["-O3", "--use_fast_math", "-gencode=arch=compute_90,code=sm_90"] if os.environ.get("DEBUG_CUDA"): extra_cuda_cflags += ["-g", "-lineinfo"] return load_inline( name="topk_bitonic_cuda", cpp_sources=_CPP_DECLS, cuda_sources=_CUDA_SOURCE, functions=[ "launch_argmax_256", "launch_stage1_k8", "launch_stage1_k16", "launch_stage1_k32", "launch_stage1_k64", "launch_stage2_k8", "launch_stage2_k16", "launch_stage2_k32", "launch_stage2_k64", ], extra_cuda_cflags=extra_cuda_cflags, verbose=os.environ.get("VERBOSE_CUDA", "0") == "1", ) _CUDA_MODULE = _compile() _ST1 = {8: _CUDA_MODULE.launch_stage1_k8, 16: _CUDA_MODULE.launch_stage1_k16, 32: _CUDA_MODULE.launch_stage1_k32, 64: _CUDA_MODULE.launch_stage1_k64} _ST2 = {8: _CUDA_MODULE.launch_stage2_k8, 16: _CUDA_MODULE.launch_stage2_k16, 32: _CUDA_MODULE.launch_stage2_k32, 64: _CUDA_MODULE.launch_stage2_k64} def _get_chunk_size(n: int, k: int) -> int: return 2048 class Model(nn.Module): def __init__(self, batch: int, n: int, k: int): super().__init__() self.batch = batch self.n = n self.k = k self.register_buffer("_dummy", torch.zeros(1)) def forward(self, x: torch.Tensor): batch, n = x.shape k = self.k device = x.device if k == 1: out_vals = torch.empty(batch, 1, dtype=torch.float32, device=device) out_idxs = torch.empty(batch, 1, dtype=torch.int64, device=device) _CUDA_MODULE.launch_argmax_256(x, out_vals, out_idxs, n, batch, 256) return out_vals, out_idxs chunk_size = _get_chunk_size(n, k) blocks_per_row = (n + chunk_size - 1) // chunk_size stage1_blocks = batch * blocks_per_row tmp_vals = torch.empty(batch, blocks_per_row, k, dtype=torch.float32, device=device) tmp_idxs = torch.empty(batch, blocks_per_row, k, dtype=torch.int64, device=device) # Stage 1: all (row, chunk) blocks in one launch. _ST1[k](x, torch.empty(0, dtype=torch.int64, device=device), tmp_vals, tmp_idxs, n, blocks_per_row, chunk_size, k, stage1_blocks, 128) # Stage 2: merge per-block results, one block per row. out_vals = torch.empty(batch, k, dtype=torch.float32, device=device) out_idxs = torch.empty(batch, k, dtype=torch.int64, device=device) _ST2[k](tmp_vals, tmp_idxs, out_vals, out_idxs, blocks_per_row, k, batch, 128) return out_vals, out_idxs # Module-level shims rebuilt by check.py / benchmark.py per shape. batch = 64 n = 8192 k = 8 def get_inputs(): x = torch.randn(batch, n, dtype=torch.float32) return [x] def get_init_inputs(): return [batch, n, k]