"""CUDA top-k with multi-block row scan + merge for large n.""" from __future__ import annotations import torch import torch.nn as nn from torch.utils.cpp_extension import load_inline CUDA_SRC = r""" #include #include #include #include #include #include constexpr int WARP_SIZE = 32; constexpr int ROW_CHUNK = 4096; __device__ __forceinline__ float warp_reduce_max(float val, int* idx, int lane) { for (int offset = WARP_SIZE / 2; offset > 0; offset >>= 1) { float other = __shfl_down_sync(0xffffffff, val, offset); int other_idx = __shfl_down_sync(0xffffffff, *idx, offset); if (other > val) { val = other; *idx = other_idx; } } return val; } __device__ __forceinline__ void insert_desc(float val, int idx, float* vals, int* idxs, int cap) { if (val <= vals[cap - 1]) return; int pos = cap - 1; while (pos >= 0 && val > vals[pos]) { if (pos + 1 < cap) { vals[pos + 1] = vals[pos]; idxs[pos + 1] = idxs[pos]; } pos--; } vals[pos + 1] = val; idxs[pos + 1] = idx; } __device__ void bitonic_sort_desc(float* vals, int* idxs, int n) { for (int k = 2; k <= n; k <<= 1) { for (int j = k >> 1; j > 0; j >>= 1) { for (int i = threadIdx.x; i < n; i += blockDim.x) { int ixj = i ^ j; if (ixj > i) { bool up = ((i & k) == 0); float va = vals[i], vb = vals[ixj]; int ia = idxs[i], ib = idxs[ixj]; bool swap = up ? (va < vb) : (va > vb); if (swap) { vals[i] = vb; vals[ixj] = va; idxs[i] = ib; idxs[ixj] = ia; } } } __syncthreads(); } } } template __device__ void process_chunk( const float* row_in, int chunk_start, int chunk_len, float* out_vals, int* out_idxs, int k ) { constexpr int CAND = BLOCK * LOCAL_K; __shared__ float smem_vals[CAND]; __shared__ int smem_idxs[CAND]; float local_vals[LOCAL_K]; int local_idxs[LOCAL_K]; #pragma unroll for (int i = 0; i < LOCAL_K; ++i) { local_vals[i] = -INFINITY; local_idxs[i] = 0; } const int tid = threadIdx.x; const int end = chunk_start + chunk_len; const int vec_start = chunk_start & ~3; const int vec_end = end & ~3; for (int idx = vec_start + tid * 4; idx < vec_end; idx += BLOCK * 4) { if (idx < chunk_start) continue; float4 v4 = reinterpret_cast(row_in)[idx >> 2]; if (idx + 0 >= chunk_start && idx + 0 < end) insert_desc(v4.x, idx + 0, local_vals, local_idxs, LOCAL_K); if (idx + 1 >= chunk_start && idx + 1 < end) insert_desc(v4.y, idx + 1, local_vals, local_idxs, LOCAL_K); if (idx + 2 >= chunk_start && idx + 2 < end) insert_desc(v4.z, idx + 2, local_vals, local_idxs, LOCAL_K); if (idx + 3 >= chunk_start && idx + 3 < end) insert_desc(v4.w, idx + 3, local_vals, local_idxs, LOCAL_K); } for (int idx = vec_end + tid; idx < end; idx += BLOCK) { insert_desc(row_in[idx], idx, local_vals, local_idxs, LOCAL_K); } const int base = tid * LOCAL_K; #pragma unroll for (int i = 0; i < LOCAL_K; ++i) { smem_vals[base + i] = local_vals[i]; smem_idxs[base + i] = local_idxs[i]; } __syncthreads(); bitonic_sort_desc(smem_vals, smem_idxs, CAND); if (tid < k) { out_vals[tid] = smem_vals[tid]; out_idxs[tid] = smem_idxs[tid]; } } template __global__ void topk_streaming_kernel( const float* __restrict__ input, float* __restrict__ out_values, int64_t* __restrict__ out_indices, int batch, int n, int k ) { const int row = blockIdx.x; if (row >= batch) return; const float* row_in = input + (int64_t)row * n; __shared__ float out_vals[LOCAL_K]; __shared__ int out_idxs[LOCAL_K]; process_chunk(row_in, 0, n, out_vals, out_idxs, k); __syncthreads(); const int tid = threadIdx.x; if (tid < k) { out_values[(int64_t)row * k + tid] = out_vals[tid]; out_indices[(int64_t)row * k + tid] = (int64_t)out_idxs[tid]; } } template __global__ void topk_chunk_kernel( const float* __restrict__ input, float* __restrict__ partial_values, int* __restrict__ partial_indices, int batch, int n, int k, int blocks_per_row ) { const int row = blockIdx.y; const int chunk_id = blockIdx.x; if (row >= batch || chunk_id >= blocks_per_row) return; const int chunk_start = chunk_id * ROW_CHUNK; if (chunk_start >= n) return; const int chunk_len = min(ROW_CHUNK, n - chunk_start); const float* row_in = input + (int64_t)row * n; __shared__ float out_vals[LOCAL_K]; __shared__ int out_idxs[LOCAL_K]; process_chunk(row_in, chunk_start, chunk_len, out_vals, out_idxs, k); __syncthreads(); const int tid = threadIdx.x; const int64_t base = ((int64_t)row * blocks_per_row + chunk_id) * k; if (tid < k) { partial_values[base + tid] = out_vals[tid]; partial_indices[base + tid] = out_idxs[tid]; } } template __global__ void topk_merge_kernel( const float* __restrict__ partial_values, const int* __restrict__ partial_indices, float* __restrict__ out_values, int64_t* __restrict__ out_indices, int batch, int k, int blocks_per_row ) { const int row = blockIdx.x; if (row >= batch) return; const int total = blocks_per_row * k; __shared__ float smem_vals[MAX_MERGE]; __shared__ int smem_idxs[MAX_MERGE]; const int tid = threadIdx.x; const int64_t base = (int64_t)row * blocks_per_row * k; for (int i = tid; i < total; i += BLOCK) { smem_vals[i] = partial_values[base + i]; smem_idxs[i] = partial_indices[base + i]; } int sort_n = 1; while (sort_n < total) sort_n <<= 1; for (int i = total + tid; i < sort_n; i += BLOCK) { smem_vals[i] = -INFINITY; smem_idxs[i] = 0; } __syncthreads(); bitonic_sort_desc(smem_vals, smem_idxs, sort_n); if (tid < k) { out_values[(int64_t)row * k + tid] = smem_vals[tid]; out_indices[(int64_t)row * k + tid] = (int64_t)smem_idxs[tid]; } } __global__ void topk_k1_kernel( const float* __restrict__ input, float* __restrict__ out_values, int64_t* __restrict__ out_indices, int batch, int n ) { const int row = blockIdx.x; if (row >= batch) return; const float* row_in = input + (int64_t)row * n; const int tid = threadIdx.x; const int lane = tid & (WARP_SIZE - 1); const int warp_id = tid >> 5; const int num_warps = blockDim.x >> 5; float best = -INFINITY; int best_idx = 0; const int vec_n = n & ~3; for (int idx = tid * 4; idx < vec_n; idx += blockDim.x * 4) { float4 v4 = reinterpret_cast(row_in)[idx >> 2]; if (v4.x > best) { best = v4.x; best_idx = idx + 0; } if (v4.y > best) { best = v4.y; best_idx = idx + 1; } if (v4.z > best) { best = v4.z; best_idx = idx + 2; } if (v4.w > best) { best = v4.w; best_idx = idx + 3; } } for (int idx = vec_n + tid; idx < n; idx += blockDim.x) { float v = row_in[idx]; if (v > best) { best = v; best_idx = idx; } } __shared__ float warp_max_val[32]; __shared__ int warp_max_idx[32]; best = warp_reduce_max(best, &best_idx, lane); if (lane == 0) { warp_max_val[warp_id] = best; warp_max_idx[warp_id] = best_idx; } __syncthreads(); if (warp_id == 0) { float val = (lane < num_warps) ? warp_max_val[lane] : -INFINITY; int idx = (lane < num_warps) ? warp_max_idx[lane] : 0; val = warp_reduce_max(val, &idx, lane); if (lane == 0) { out_values[row] = val; out_indices[row] = (int64_t)idx; } } } template void launch_streaming( const float* input, float* out_values, int64_t* out_indices, int batch, int n, int k, cudaStream_t stream ) { topk_streaming_kernel<<>>( input, out_values, out_indices, batch, n, k); } template void launch_multiblock( const float* input, float* out_values, int64_t* out_indices, float* partial_values, int* partial_indices, int batch, int n, int k, cudaStream_t stream ) { const int blocks_per_row = (n + ROW_CHUNK - 1) / ROW_CHUNK; dim3 grid(blocks_per_row, batch); topk_chunk_kernel<<>>( input, partial_values, partial_indices, batch, n, k, blocks_per_row); topk_merge_kernel<<>>( partial_values, partial_indices, out_values, out_indices, batch, k, blocks_per_row); } struct TopkWorkspace { torch::Tensor partial_values; torch::Tensor partial_indices; int blocks_per_row = 0; int batch = 0; int k = 0; }; static TopkWorkspace g_ws; void ensure_workspace(int batch, int n, int k, torch::Device device) { const int blocks_per_row = (n + ROW_CHUNK - 1) / ROW_CHUNK; if (g_ws.blocks_per_row >= blocks_per_row && g_ws.batch >= batch && g_ws.k >= k && g_ws.partial_values.defined() && g_ws.partial_values.device() == device) { return; } g_ws.blocks_per_row = blocks_per_row; g_ws.batch = batch; g_ws.k = k; g_ws.partial_values = torch::empty( {batch * blocks_per_row * k}, torch::TensorOptions().dtype(torch::kFloat32).device(device)); g_ws.partial_indices = torch::empty( {batch * blocks_per_row * k}, torch::TensorOptions().dtype(torch::kInt32).device(device)); } template void dispatch_topk( const float* input, float* out_values, int64_t* out_indices, int batch, int n, int k, cudaStream_t stream, torch::Device device ) { const int blocks_per_row = (n + ROW_CHUNK - 1) / ROW_CHUNK; if (blocks_per_row <= 1) { launch_streaming(input, out_values, out_indices, batch, n, k, stream); } else { ensure_workspace(batch, n, k, device); launch_multiblock( input, out_values, out_indices, g_ws.partial_values.data_ptr(), g_ws.partial_indices.data_ptr(), batch, n, k, stream); } } void launch_topk( const float* input, float* out_values, int64_t* out_indices, int batch, int n, int k, cudaStream_t stream, torch::Device device ) { if (k == 1) { topk_k1_kernel<<>>(input, out_values, out_indices, batch, n); return; } if (k <= 4) { dispatch_topk<256, 4, 1024>(input, out_values, out_indices, batch, n, k, stream, device); } else if (k <= 8) { dispatch_topk<256, 8, 1024>(input, out_values, out_indices, batch, n, k, stream, device); } else if (k <= 16) { dispatch_topk<256, 16, 2048>(input, out_values, out_indices, batch, n, k, stream, device); } else if (k <= 32) { dispatch_topk<128, 32, 4096>(input, out_values, out_indices, batch, n, k, stream, device); } else { dispatch_topk<64, 64, 4096>(input, out_values, out_indices, batch, n, k, stream, device); } } std::vector topk_forward(torch::Tensor input, int64_t k) { TORCH_CHECK(input.is_cuda(), "input must be CUDA"); TORCH_CHECK(input.scalar_type() == torch::kFloat32, "input must be fp32"); TORCH_CHECK(input.dim() == 2, "input must be 2D"); const int batch = (int)input.size(0); const int n = (int)input.size(1); const int ki = (int)k; TORCH_CHECK(ki > 0 && ki <= n, "invalid k"); auto values = torch::empty({batch, ki}, input.options()); auto indices = torch::empty({batch, ki}, input.options().dtype(torch::kInt64)); launch_topk( input.data_ptr(), values.data_ptr(), indices.data_ptr(), batch, n, ki, c10::cuda::getCurrentCUDAStream(), input.device() ); return {values, indices}; } """ CPP_SRC = r""" #include #include std::vector topk_forward(torch::Tensor input, int64_t k); """ _ext = load_inline( name="topk_cuda_ext_v7", cpp_sources=CPP_SRC, cuda_sources=CUDA_SRC, functions=["topk_forward"], extra_cuda_cflags=["-O3", "--use_fast_math"], verbose=False, ) class Model(nn.Module): def __init__(self, batch: int, n: int, k: int): super().__init__() self.batch, self.n, self.k = batch, n, k self.register_buffer("_dummy", torch.zeros(1)) def forward(self, x: torch.Tensor): return _ext.topk_forward(x.contiguous(), self.k) 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]