import torch import torch.nn as nn from torch.utils.cpp_extension import load_inline # Define the complete CUDA C++ source code cuda_src = """ #include #include #include #include template __global__ void topk_pass1_kernel( const float* __restrict__ input, float* __restrict__ temp_val, int* __restrict__ temp_idx, float* __restrict__ out_val, int64_t* __restrict__ out_idx, int N, int chunk_size) { int row_idx = blockIdx.y; int block_start = blockIdx.x * chunk_size; int block_end = min(N, (blockIdx.x + 1) * chunk_size); float val[K]; int idx[K]; #pragma unroll for (int i = 0; i < K; ++i) { val[i] = -INFINITY; idx[i] = -1; } if (block_start < N) { const float* row_ptr = input + row_idx * N; int i = block_start + threadIdx.x * 4; int stride = blockDim.x * 4; for (; i < block_end; i += stride) { float4 items = *reinterpret_cast(&row_ptr[i]); // Item 1 float x1 = items.x; if (x1 > val[K - 1]) { #pragma unroll for (int p = 0; p < K; ++p) { if (x1 > val[p]) { #pragma unroll for (int j = K - 1; j > p; --j) { val[j] = val[j - 1]; idx[j] = idx[j - 1]; } val[p] = x1; idx[p] = i; break; } } } // Item 2 float x2 = items.y; if (x2 > val[K - 1]) { #pragma unroll for (int p = 0; p < K; ++p) { if (x2 > val[p]) { #pragma unroll for (int j = K - 1; j > p; --j) { val[j] = val[j - 1]; idx[j] = idx[j - 1]; } val[p] = x2; idx[p] = i + 1; break; } } } // Item 3 float x3 = items.z; if (x3 > val[K - 1]) { #pragma unroll for (int p = 0; p < K; ++p) { if (x3 > val[p]) { #pragma unroll for (int j = K - 1; j > p; --j) { val[j] = val[j - 1]; idx[j] = idx[j - 1]; } val[p] = x3; idx[p] = i + 2; break; } } } // Item 4 float x4 = items.w; if (x4 > val[K - 1]) { #pragma unroll for (int p = 0; p < K; ++p) { if (x4 > val[p]) { #pragma unroll for (int j = K - 1; j > p; --j) { val[j] = val[j - 1]; idx[j] = idx[j - 1]; } val[p] = x4; idx[p] = i + 3; break; } } } } } // Shared memory layout uses K + 1 stride to eliminate bank conflicts extern __shared__ char smem[]; float* sh_val = reinterpret_cast(smem); int* sh_idx = reinterpret_cast(smem + (blockDim.x / 2) * (K + 1) * sizeof(float)); for (int limit = blockDim.x / 2; limit > 0; limit /= 2) { if (threadIdx.x >= limit && threadIdx.x < 2 * limit) { int write_idx = threadIdx.x - limit; #pragma unroll for (int p = 0; p < K; ++p) { sh_val[write_idx * (K + 1) + p] = val[p]; sh_idx[write_idx * (K + 1) + p] = idx[p]; } } __syncthreads(); if (threadIdx.x < limit) { int read_idx = threadIdx.x; float temp_val_arr[K]; int temp_idx_arr[K]; int p_self = 0; int p_other = 0; #pragma unroll for (int step = 0; step < K; ++step) { bool take_self = false; if (p_self < K && p_other < K) { take_self = (val[p_self] >= sh_val[read_idx * (K + 1) + p_other]); } else if (p_self < K) { take_self = true; } else { take_self = false; } if (take_self) { temp_val_arr[step] = val[p_self]; temp_idx_arr[step] = idx[p_self]; p_self++; } else { temp_val_arr[step] = sh_val[read_idx * (K + 1) + p_other]; temp_idx_arr[step] = sh_idx[read_idx * (K + 1) + p_other]; p_other++; } } #pragma unroll for (int s = 0; s < K; ++s) { val[s] = temp_val_arr[s]; idx[s] = temp_idx_arr[s]; } } __syncthreads(); } if (threadIdx.x == 0) { if (temp_val == nullptr) { #pragma unroll for (int p = 0; p < K; ++p) { out_val[row_idx * K + p] = val[p]; out_idx[row_idx * K + p] = static_cast(idx[p]); } } else { int out_offset = (row_idx * gridDim.x + blockIdx.x) * K; #pragma unroll for (int p = 0; p < K; ++p) { temp_val[out_offset + p] = val[p]; temp_idx[out_offset + p] = idx[p]; } } } } template __global__ void topk_pass2_kernel( const float* __restrict__ temp_val, const int* __restrict__ temp_idx, float* __restrict__ out_val, int64_t* __restrict__ out_idx, int num_blocks_per_row) { int row_idx = blockIdx.x; float val[K]; int idx[K]; #pragma unroll for (int p = 0; p < K; ++p) { val[p] = -INFINITY; idx[p] = -1; } if (threadIdx.x < num_blocks_per_row) { int in_offset = (row_idx * num_blocks_per_row + threadIdx.x) * K; #pragma unroll for (int p = 0; p < K; ++p) { val[p] = temp_val[in_offset + p]; idx[p] = temp_idx[in_offset + p]; } } extern __shared__ char smem[]; float* sh_val = reinterpret_cast(smem); int* sh_idx = reinterpret_cast(smem + (blockDim.x / 2) * (K + 1) * sizeof(float)); for (int limit = blockDim.x / 2; limit > 0; limit /= 2) { if (threadIdx.x >= limit && threadIdx.x < 2 * limit) { int write_idx = threadIdx.x - limit; #pragma unroll for (int p = 0; p < K; ++p) { sh_val[write_idx * (K + 1) + p] = val[p]; sh_idx[write_idx * (K + 1) + p] = idx[p]; } } __syncthreads(); if (threadIdx.x < limit) { int read_idx = threadIdx.x; float temp_val_arr[K]; int temp_idx_arr[K]; int p_self = 0; int p_other = 0; #pragma unroll for (int step = 0; step < K; ++step) { bool take_self = false; if (p_self < K && p_other < K) { take_self = (val[p_self] >= sh_val[read_idx * (K + 1) + p_other]); } else if (p_self < K) { take_self = true; } else { take_self = false; } if (take_self) { temp_val_arr[step] = val[p_self]; temp_idx_arr[step] = idx[p_self]; p_self++; } else { temp_val_arr[step] = sh_val[read_idx * (K + 1) + p_other]; temp_idx_arr[step] = sh_idx[read_idx * (K + 1) + p_other]; p_other++; } } #pragma unroll for (int s = 0; s < K; ++s) { val[s] = temp_val_arr[s]; idx[s] = temp_idx_arr[s]; } } __syncthreads(); } if (threadIdx.x == 0) { #pragma unroll for (int p = 0; p < K; ++p) { out_val[row_idx * K + p] = val[p]; out_idx[row_idx * K + p] = static_cast(idx[p]); } } } template void launch_topk( const float* input, float* out_val, int64_t* out_idx, int batch, int N, int num_blocks_per_row, float* temp_val, int* temp_idx) { int block_size = (K == 64) ? 128 : 256; int chunk_size = (N + num_blocks_per_row - 1) / num_blocks_per_row; chunk_size = ((chunk_size + 3) / 4) * 4; if (num_blocks_per_row == 1) { dim3 grid(1, batch); dim3 block(block_size); int shared_mem_bytes = (block_size / 2) * (K + 1) * (sizeof(float) + sizeof(int)); topk_pass1_kernel<<>>( input, nullptr, nullptr, out_val, out_idx, N, chunk_size ); } else { dim3 grid1(num_blocks_per_row, batch); dim3 block1(block_size); int shared_mem_bytes1 = (block_size / 2) * (K + 1) * (sizeof(float) + sizeof(int)); topk_pass1_kernel<<>>( input, temp_val, temp_idx, nullptr, nullptr, N, chunk_size ); dim3 grid2(batch); int block_size2 = num_blocks_per_row; if (block_size2 < 32) block_size2 = 32; dim3 block2(block_size2); int shared_mem_bytes2 = (block_size2 / 2) * (K + 1) * (sizeof(float) + sizeof(int)); topk_pass2_kernel<<>>( temp_val, temp_idx, out_val, out_idx, num_blocks_per_row ); } } std::vector topk_cuda_dispatch( at::Tensor input, int K, int num_blocks_per_row, at::Tensor temp_val, at::Tensor temp_idx) { int batch = input.size(0); int N = input.size(1); auto options_val = torch::TensorOptions().dtype(torch::kFloat32).device(input.device()); auto options_idx = torch::TensorOptions().dtype(torch::kInt64).device(input.device()); auto out_val = torch::empty({batch, K}, options_val); auto out_idx = torch::empty({batch, K}, options_idx); const float* input_ptr = input.data_ptr(); float* out_val_ptr = out_val.data_ptr(); int64_t* out_idx_ptr = out_idx.data_ptr(); float* temp_val_ptr = num_blocks_per_row > 1 ? temp_val.data_ptr() : nullptr; int* temp_idx_ptr = num_blocks_per_row > 1 ? temp_idx.data_ptr() : nullptr; if (K == 1) { launch_topk<1>(input_ptr, out_val_ptr, out_idx_ptr, batch, N, num_blocks_per_row, temp_val_ptr, temp_idx_ptr); } else if (K <= 2) { launch_topk<2>(input_ptr, out_val_ptr, out_idx_ptr, batch, N, num_blocks_per_row, temp_val_ptr, temp_idx_ptr); } else if (K <= 4) { launch_topk<4>(input_ptr, out_val_ptr, out_idx_ptr, batch, N, num_blocks_per_row, temp_val_ptr, temp_idx_ptr); } else if (K <= 8) { launch_topk<8>(input_ptr, out_val_ptr, out_idx_ptr, batch, N, num_blocks_per_row, temp_val_ptr, temp_idx_ptr); } else if (K <= 16) { launch_topk<16>(input_ptr, out_val_ptr, out_idx_ptr, batch, N, num_blocks_per_row, temp_val_ptr, temp_idx_ptr); } else if (K <= 32) { launch_topk<32>(input_ptr, out_val_ptr, out_idx_ptr, batch, N, num_blocks_per_row, temp_val_ptr, temp_idx_ptr); } else if (K <= 64) { launch_topk<64>(input_ptr, out_val_ptr, out_idx_ptr, batch, N, num_blocks_per_row, temp_val_ptr, temp_idx_ptr); } else { TORCH_CHECK(false, "K > 64 is not supported"); } return {out_val, out_idx}; } """ cpp_src = """ std::vector topk_cuda_dispatch( at::Tensor input, int K, int num_blocks_per_row, at::Tensor temp_val, at::Tensor temp_idx); """ # Compile the CUDA C++ extension in-line _module = load_inline( name="topk_cuda_extension", cpp_sources=cpp_src, cuda_sources=cuda_src, functions=["topk_cuda_dispatch"], verbose=True, ) def get_padded_k(k: int) -> int: if k <= 1: return 1 if k <= 2: return 2 if k <= 4: return 4 if k <= 8: return 8 if k <= 16: return 16 if k <= 32: return 32 if k <= 64: return 64 raise ValueError(f"Unsupported k: {k}") 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.padded_k = get_padded_k(k) self.register_buffer("_dummy", torch.zeros(1)) # Calculate num_blocks_per_row at initialization time block_size = 128 if self.padded_k == 64 else 256 target_total_blocks = 128 int_blocks = target_total_blocks // batch if int_blocks < 1: int_blocks = 1 min_chunk_size = block_size * 4 if n // min_chunk_size < int_blocks: int_blocks = n // min_chunk_size if int_blocks < 1: int_blocks = 1 p_blocks = 1 while p_blocks * 2 <= int_blocks: p_blocks *= 2 self.num_blocks_per_row = p_blocks # Pre-allocate intermediate buffers to avoid runtime allocation overhead if self.num_blocks_per_row > 1: self.temp_val = torch.empty((batch, self.num_blocks_per_row, self.padded_k), dtype=torch.float32, device="cuda") self.temp_idx = torch.empty((batch, self.num_blocks_per_row, self.padded_k), dtype=torch.int32, device="cuda") else: self.temp_val = torch.empty((0,), dtype=torch.float32, device="cuda") self.temp_idx = torch.empty((0,), dtype=torch.int32, device="cuda") def forward(self, x: torch.Tensor): vals, idxs = _module.topk_cuda_dispatch(x, self.padded_k, self.num_blocks_per_row, self.temp_val, self.temp_idx) if self.padded_k != self.k: return vals[:, :self.k], idxs[:, :self.k] return vals, idxs def get_inputs(): x = torch.randn(64, 8192, dtype=torch.float32) return [x] def get_init_inputs(): return [64, 8192, 8]