import torch import torch.nn as nn _CUDA_SRC = r""" #include #include #define NEG_INF __int_as_float(0xff800000) __device__ __forceinline__ uint32_t f2s(float f) { uint32_t b = __float_as_uint(f); return (b & 0x80000000u) ? ~b : (b | 0x80000000u); } __device__ __forceinline__ float s2f(uint32_t s) { uint32_t b = (s & 0x80000000u) ? (s & 0x7fffffffu) : ~s; return __uint_as_float(b); } __device__ __forceinline__ uint64_t pack(float f, int ix) { return ((uint64_t)f2s(f) << 32) | (uint32_t)ix; } __device__ __forceinline__ float uval(uint64_t p) { return s2f((uint32_t)(p >> 32)); } __device__ __forceinline__ int uidx(uint64_t p) { return (int)(p & 0xffffffffu); } template __device__ __forceinline__ void insert_topk(uint64_t (&v)[K], uint64_t val) { if (val <= v[K-1]) return; #pragma unroll for (int j = 0; j < K; ++j) { if (val > v[j]) { uint64_t t = v[j]; v[j] = val; val = t; } } } template __device__ __forceinline__ void warp_tournament(int lane, const uint64_t* __restrict__ base, uint64_t* __restrict__ out) { // base layout: [slot][lane] = base[slot*32 + lane]; each lane contributes up // to K sorted candidates. Consecutive lanes hit consecutive addresses (no // bank conflict). const uint64_t SENT = pack(NEG_INF, -1); int ptr = 0; for (int p = 0; p < K; ++p) { uint64_t m = (ptr < K) ? base[ptr * 32 + lane] : SENT; uint32_t rh = (uint32_t)(m >> 32); uint32_t rl = (uint32_t)(m & 0xffffffffu); #pragma unroll for (int off = 16; off > 0; off >>= 1) { uint32_t oh = __shfl_down_sync(0xffffffffu, rh, off); uint32_t ol = __shfl_down_sync(0xffffffffu, rl, off); if (oh > rh || (oh == rh && ol > rl)) { rh = oh; rl = ol; } } int winner = (int)__shfl_sync(0xffffffffu, rl, 0); if (winner < 0) break; if ((int)(m & 0xffffffffu) == winner) { out[p] = m; ptr++; } } } // Warp-only bitonic sort of s[0..N) into descending packed order using the 32 // lanes of a single warp. __syncwarp() (nearly free) replaces __syncthreads() // so small candidate sets sort in a fraction of the block-wide barrier cost. template __device__ __forceinline__ void warp_bitonic_sort(uint64_t* s) { int lane = threadIdx.x & 31; #pragma unroll for (int size = 2; size <= N; size <<= 1) { #pragma unroll for (int stride = size >> 1; stride > 0; stride >>= 1) { __syncwarp(); #pragma unroll for (int i = lane; i < N / 2; i += 32) { int pos = 2 * i - (i & (stride - 1)); uint64_t a = s[pos], b = s[pos + stride]; bool desc = ((pos & size) == 0); if (desc ? (a < b) : (a > b)) { s[pos] = b; s[pos + stride] = a; } } } } __syncwarp(); } // Pad s[cnt..size) with SENT and bitonic-sort the smallest power-of-two >= cnt // (warp 0). Sorting 64/128 instead of a fixed 256 is ~7x/2x cheaper, and the // radix gather almost always yields only slightly more than K candidates. __device__ __forceinline__ void pad_and_sort(uint64_t* s, int cnt) { int lane = threadIdx.x & 31; const uint64_t SENT = pack(NEG_INF, -1); if (cnt <= 64) { for (int j = lane; j < 64; j += 32) if (j >= cnt) s[j] = SENT; __syncwarp(); warp_bitonic_sort<64>(s); } else if (cnt <= 128) { for (int j = lane; j < 128; j += 32) if (j >= cnt) s[j] = SENT; __syncwarp(); warp_bitonic_sort<128>(s); } else { for (int j = lane; j < 256; j += 32) if (j >= cnt) s[j] = SENT; __syncwarp(); warp_bitonic_sort<256>(s); } } // In-place bitonic sort of s[0..N) into descending packed order. N and T are // compile-time so every stage unrolls into a static compare-exchange network. template __device__ __forceinline__ void bitonic_sort_desc(uint64_t* s) { #pragma unroll for (int size = 2; size <= N; size <<= 1) { #pragma unroll for (int stride = size >> 1; stride > 0; stride >>= 1) { __syncthreads(); #pragma unroll for (int i = threadIdx.x; i < N / 2; i += T) { int pos = 2 * i - (i & (stride - 1)); uint64_t a = s[pos], b = s[pos + stride]; bool desc = ((pos & size) == 0); if (desc ? (a < b) : (a > b)) { s[pos] = b; s[pos + stride] = a; } } } } __syncthreads(); } // ---- per-thread path (k == 1: batched argmax) ------------------------------ template __global__ void tile_topk(const float* __restrict__ x, int n, int tile_elems, float* __restrict__ out_val, IdxT* __restrict__ out_idx, int out_stride) { extern __shared__ char smem[]; uint64_t* wl = (uint64_t*)smem; uint64_t* wr = (uint64_t*)(smem + (size_t)BLOCK * K * 8); int row = blockIdx.y, tile = blockIdx.x; int base = tile * tile_elems; int cnt = min(tile_elems, n - base); const float* xr = x + (int64_t)row * n + base; int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; const int NW = BLOCK / 32; uint64_t v[K]; const uint64_t SENT = pack(NEG_INF, -1); #pragma unroll for (int j = 0; j < K; ++j) v[j] = SENT; const int B = 8; int e = tid; for (; e + (B-1)*BLOCK < cnt; e += B*BLOCK) { float r[B]; #pragma unroll for (int b = 0; b < B; ++b) r[b] = xr[e + b*BLOCK]; for (int b = 0; b < B; ++b) insert_topk(v, pack(r[b], base + e + b*BLOCK)); } for (; e < cnt; e += BLOCK) insert_topk(v, pack(xr[e], base + e)); #pragma unroll for (int j = 0; j < K; ++j) wl[(warp * K + j) * 32 + lane] = v[j]; __syncthreads(); warp_tournament(lane, &wl[warp * 32 * K], &wr[warp * K]); __syncthreads(); if (tid < 32) { #pragma unroll for (int j = 0; j < K; ++j) v[j] = SENT; int total = NW * K; for (int i = lane; i < total; i += 32) insert_topk(v, wr[i]); #pragma unroll for (int j = 0; j < K; ++j) wl[j * 32 + lane] = v[j]; __syncwarp(); warp_tournament(lane, wl, wr); float* ov = out_val + (int64_t)row * out_stride + tile * K; IdxT* oi = out_idx + (int64_t)row * out_stride + tile * K; for (int j = lane; j < K; j += 32) { ov[j] = uval(wr[j]); oi[j] = (IdxT)uidx(wr[j]); } } } // ---- fused single-kernel top-k (k > 8) ------------------------------------ // Each block histogram-selects the block-local top-K (8-bit buckets). The // gather re-reads the slice from global (it is already L1/L2-resident after the // histogram pass), so no large per-element staging buffer is needed and the // shared footprint stays tiny regardless of slice length -- which lets us run // one block per row for k <= 32. The last block of each row (tracked by a // per-row atomic counter) merges the nchunks*K candidates into the sorted // global top-K via a two-pass radix select (top 8 bits, then the next 8 bits of // the boundary bucket), removing the second kernel launch entirely. // // Pathological inputs (boundary set larger than the 256-entry sort buffer) fall // back to an exact K-pass max selection with a per-index used-bitmask, so the // result is always exact. #define NB 256 #define NBH 4096 // 12-bit buckets for the block-local select // Generalized boundary-bucket search over a histogram of NB32*32 buckets (each // lane sums NB32 consecutive buckets). Returns bstar (0..NB32*32-1) such that // sum_{b>=bstar} hist[b] >= Kneed > sum_{b>bstar} hist[b], and above = the // count strictly above bstar. Call with all 32 lanes of every warp. __device__ __forceinline__ void warp_threshold_n(const uint32_t* sh, int Kneed, int NB32, int* bstar_out, int* above_out) { int lane = threadIdx.x & 31; int local = 0; #pragma unroll 8 for (int j = 0; j < NB32; ++j) local += (int)sh[NB32 * lane + j]; int suff = local; #pragma unroll for (int off = 1; off < 32; off <<= 1) { int t = __shfl_down_sync(0xffffffffu, suff, off); if (lane + off < 32) suff += t; } int inter_above = suff - local; int bstar_local = NB32 - 1, acc = inter_above; #pragma unroll 8 for (int j = NB32 - 1; j >= 0; --j) { int h = (int)sh[NB32 * lane + j]; if (acc + h >= Kneed) { bstar_local = j; break; } acc += h; } int above = acc; int bstar = NB32 * lane + bstar_local; int is_cross = (inter_above < Kneed && inter_above + local >= Kneed) ? 1 : 0; int cross = __ffs(__ballot_sync(0xffffffffu, is_cross)) - 1; *bstar_out = __shfl_sync(0xffffffffu, bstar, cross); *above_out = __shfl_sync(0xffffffffu, above, cross); } // Warp 0 computes the boundary bucket bstar (0..255) of a 256-entry histogram // such that sum_{b>=bstar} hist[b] >= Kneed > sum_{b>bstar} hist[b], and // returns above = sum_{b>bstar} hist[b]. Call with all 32 lanes of warp 0. __device__ __forceinline__ void warp_threshold(const uint32_t* sh, int Kneed, int* bstar_out, int* above_out) { int lane = threadIdx.x & 31; int local = 0; #pragma unroll for (int j = 0; j < 8; ++j) local += (int)sh[8 * lane + j]; int suff = local; #pragma unroll for (int off = 1; off < 32; off <<= 1) { int t = __shfl_down_sync(0xffffffffu, suff, off); if (lane + off < 32) suff += t; } int inter_above = suff - local; int bstar_local = 0, acc = inter_above; #pragma unroll for (int j = 7; j >= 0; --j) { int h = (int)sh[8 * lane + j]; if (acc + h >= Kneed) { bstar_local = j; break; } acc += h; } int above = acc; int bstar = 8 * lane + bstar_local; int is_cross = (inter_above < Kneed && inter_above + local >= Kneed) ? 1 : 0; int cross = __ffs(__ballot_sync(0xffffffffu, is_cross)) - 1; *bstar_out = __shfl_sync(0xffffffffu, bstar, cross); *above_out = __shfl_sync(0xffffffffu, above, cross); } template __global__ void fused_topk(const float* __restrict__ x, int n, int nchunks, uint64_t* __restrict__ cand, float* __restrict__ oval, int64_t* __restrict__ oidx, int* __restrict__ counter) { extern __shared__ char smem[]; const int NW = BLOCK / 32; int row = blockIdx.y, chunk = blockIdx.x, tid = threadIdx.x; int per = (n + nchunks - 1) / nchunks; int lo = chunk * per; int cntl = min(per, n - lo); const float* xr = x + (int64_t)row * n; const uint64_t SENT = pack(NEG_INF, -1); int nused = ((per >> 5) + 2) & ~1; // bitmask words, even for 8B align uint32_t* sh = (uint32_t*)smem; // [0..NB) hi-byte hist, [NB..2NB) lo-byte hist uint32_t* sh2 = sh + NB; uint32_t* used = sh + 2 * NB; // bitmask for the fallback uint64_t* sc = (uint64_t*)(smem + 2 * NB * 4 + nused * 4); // 256-entry sort buf __shared__ int s_cnt; __shared__ bool is_last; __shared__ uint64_t sv[NW]; __shared__ int si[NW]; // ---- Phase 1: block-local top-K (16-bit radix: never overflows 256) ------ for (int b = tid; b < 2 * NB; b += BLOCK) sh[b] = 0; if (tid == 0) s_cnt = 0; __syncthreads(); for (int i = tid; i < cntl; i += BLOCK) { atomicAdd(&sh[f2s(xr[lo + i]) >> 24], 1u); } __syncthreads(); int bstar_hi = 0, above_hi = 0; warp_threshold(sh, K, &bstar_hi, &above_hi); // all warps, redundantly for (int i = tid; i < cntl; i += BLOCK) { uint32_t key = f2s(xr[lo + i]); if ((key >> 24) == (uint32_t)bstar_hi) atomicAdd(&sh2[(key >> 16) & 0xffu], 1u); } __syncthreads(); int bstar_lo = 0, above_lo = 0; warp_threshold(sh2, K - above_hi, &bstar_lo, &above_lo); // all warps for (int i = tid; i < cntl; i += BLOCK) { uint32_t key = f2s(xr[lo + i]); bool sel = (key >> 24) > (uint32_t)bstar_hi || ((key >> 24) == (uint32_t)bstar_hi && ((key >> 16) & 0xffu) >= (uint32_t)bstar_lo); if (sel) { int slot = atomicAdd(&s_cnt, 1); if (slot < 256) sc[slot] = ((uint64_t)key << 32) | (uint32_t)(lo + i); } } __syncthreads(); int cnt2 = s_cnt; uint64_t* c = cand + ((int64_t)row * nchunks + chunk) * K; if (cnt2 <= 256) { if (tid < 32) { int lane = tid; pad_and_sort(sc, cnt2); if (nchunks == 1) { for (int j = lane; j < K; j += 32) { oval[(int64_t)row * K + j] = uval(sc[j]); oidx[(int64_t)row * K + j] = (int64_t)uidx(sc[j]); } } else { for (int j = lane; j < K; j += 32) c[j] = sc[j]; } } } else { int lane = tid & 31, warp = tid >> 5; for (int w = tid; w < nused; w += BLOCK) used[w] = 0; __syncthreads(); for (int p = 0; p < K; ++p) { uint64_t best = SENT; int bix = -1; for (int i = tid; i < cntl; i += BLOCK) { if (!(used[i >> 5] & (1u << (i & 31)))) { uint64_t v = pack(xr[lo + i], lo + i); if (v > best) { best = v; bix = i; } } } #pragma unroll for (int off = 16; off > 0; off >>= 1) { uint64_t o = __shfl_down_sync(0xffffffffu, best, off); int oi = __shfl_down_sync(0xffffffffu, bix, off); if (o > best) { best = o; bix = oi; } } if (lane == 0) { sv[warp] = best; si[warp] = bix; } __syncthreads(); if (tid == 0) { best = sv[0]; bix = si[0]; #pragma unroll for (int w = 1; w < NW; ++w) if (sv[w] > best) { best = sv[w]; bix = si[w]; } used[bix >> 5] |= (1u << (bix & 31)); if (nchunks == 1) { oval[(int64_t)row * K + p] = uval(best); oidx[(int64_t)row * K + p] = (int64_t)uidx(best); } else { c[p] = best; } } __syncthreads(); } } if (nchunks == 1) return; // ---- signal completion; last block of the row runs the merge ------------- __threadfence(); if (tid == 0) { int prev = atomicAdd(&counter[row], 1); is_last = (prev == nchunks - 1); } __syncthreads(); if (!is_last) return; // ---- Phase 2: two-pass radix select over the row's candidates ------------- int C = nchunks * K; uint64_t* crow = cand + (int64_t)row * C; for (int b = tid; b < 2 * NB; b += BLOCK) sh[b] = 0; if (tid == 0) s_cnt = 0; __syncthreads(); for (int i = tid; i < C; i += BLOCK) { atomicAdd(&sh[(uint32_t)(crow[i] >> 32) >> 24], 1u); } __syncthreads(); warp_threshold(sh, K, &bstar_hi, &above_hi); // all warps, redundantly for (int i = tid; i < C; i += BLOCK) { uint32_t key = (uint32_t)(crow[i] >> 32); if ((key >> 24) == (uint32_t)bstar_hi) atomicAdd(&sh2[(key >> 16) & 0xffu], 1u); } __syncthreads(); warp_threshold(sh2, K - above_hi, &bstar_lo, &above_lo); // all warps __syncthreads(); for (int i = tid; i < C; i += BLOCK) { uint32_t key = (uint32_t)(crow[i] >> 32); bool sel = (key >> 24) > (uint32_t)bstar_hi || ((key >> 24) == (uint32_t)bstar_hi && ((key >> 16) & 0xffu) >= (uint32_t)bstar_lo); if (sel) { int slot = atomicAdd(&s_cnt, 1); if (slot < 256) sc[slot] = crow[i]; } } __syncthreads(); cnt2 = s_cnt; if (cnt2 <= 256) { if (tid < 32) { int lane = tid; pad_and_sort(sc, cnt2); for (int j = lane; j < K; j += 32) { oval[(int64_t)row * K + j] = uval(sc[j]); oidx[(int64_t)row * K + j] = (int64_t)uidx(sc[j]); } } } else { int lane = tid & 31, warp = tid >> 5; for (int p = 0; p < K; ++p) { uint64_t best = SENT; int bix = -1; for (int i = tid; i < C; i += BLOCK) { uint64_t v = crow[i]; if (v > best) { best = v; bix = i; } } #pragma unroll for (int off = 16; off > 0; off >>= 1) { uint64_t o = __shfl_down_sync(0xffffffffu, best, off); int oi = __shfl_down_sync(0xffffffffu, bix, off); if (o > best) { best = o; bix = oi; } } if (lane == 0) { sv[warp] = best; si[warp] = bix; } __syncthreads(); if (tid == 0) { best = sv[0]; bix = si[0]; #pragma unroll for (int w = 1; w < NW; ++w) if (sv[w] > best) { best = sv[w]; bix = si[w]; } crow[bix] = SENT; oval[(int64_t)row * K + p] = uval(best); oidx[(int64_t)row * K + p] = (int64_t)uidx(best); } __syncthreads(); } } if (tid == 0) counter[row] = 0; } void topk_dispatch(const float* x, float* oval, int64_t* oidx, float* pval, int64_t* pidx, uint64_t* cand, int* counter, int batch, int n, int nchunks, int K, cudaStream_t stream) { if (K == 1) { tile_topk<1, 256, int64_t><<>>( x, n, n, pval, pidx, 1); return; } // One block per row (single kernel, no merge) for k == 8, where the // per-thread register top-K is small and the block count is high enough. if (K == 8 && nchunks == 1) { const int sh = (256 * K + 8 * K) * 8; tile_topk<8, 256, int64_t><<>>(x, n, n, oval, oidx, K); return; } const int per = (n + nchunks - 1) / nchunks; const int nused = ((per >> 5) + 2) & ~1; const int fsh = 2 * NB * 4 + nused * 4 + 256 * 8; // hi+lo hist + bitmask + sort buffer const int BLOCK = 256; if (K == 16) { fused_topk<16, BLOCK><<>>(x, n, nchunks, cand, oval, oidx, counter); } else if (K == 32) { fused_topk<32, BLOCK><<>>(x, n, nchunks, cand, oval, oidx, counter); } else { fused_topk<64, BLOCK><<>>(x, n, nchunks, cand, oval, oidx, counter); } } """ _CPP_SRC = r""" #include #include void topk_dispatch(const float* x, float* oval, int64_t* oidx, float* pval, int64_t* pidx, uint64_t* cand, int* counter, int batch, int n, int nchunks, int K, cudaStream_t stream); std::vector topk_forward(torch::Tensor x, int64_t k, torch::Tensor out_val, torch::Tensor out_idx, torch::Tensor pval, torch::Tensor pidx, torch::Tensor cand, torch::Tensor counter, int64_t nchunks) { TORCH_CHECK(x.is_cuda() && x.dtype() == torch::kFloat32, "x must be fp32 CUDA"); x = x.contiguous(); int batch = (int)x.size(0), n = (int)x.size(1); cudaStream_t stream = at::cuda::getCurrentCUDAStream(); topk_dispatch(x.data_ptr(), out_val.data_ptr(), out_idx.data_ptr(), pval.data_ptr(), pidx.data_ptr(), (uint64_t*)cand.data_ptr(), (int*)counter.data_ptr(), batch, n, (int)nchunks, (int)k, stream); return {out_val, out_idx}; } """ _mod = None def _get_module(): global _mod if _mod is None: from torch.utils.cpp_extension import load_inline _mod = load_inline( name="topk_bitonic_ext", cpp_sources=_CPP_SRC, cuda_sources=_CUDA_SRC, functions=["topk_forward"], no_implicit_headers=True, verbose=False, extra_cuda_cflags=["-O3", "--use_fast_math"], ) return _mod 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)) if k in (1, 8): nchunks = 1 # one block per row, single kernel (no merge) else: # Target ~256 blocks total (b*nchunks) for latency hiding, but keep # the merge candidate set C = nchunks*k <= 4096 and each block's # slice >= 256 elements so fixed per-block overhead stays amortized. nc_blocks = max(1, 256 // batch) nc_merge = max(1, 4096 // k) nchunks = max(1, min(nc_blocks, nc_merge, n // 256)) self._nchunks = nchunks self._ptr = 0 self._graph = None self._graph_failed = False self._out_val = None self._out_idx = None self._cand = None self._counter = None self._mod = None def __call__(self, x): g = self._graph if g is not None and self._ptr == x.data_ptr(): g.replay() return self._out_val, self._out_idx return self._build_and_run(x) def forward(self, x): return self.__call__(x) def _build_and_run(self, x): mod = self._mod if mod is None: mod = _get_module() self._mod = mod k, b, nchunks = self.k, self.batch, self._nchunks dev = x.device self._out_val = torch.empty((b, k), device=dev, dtype=torch.float32) self._out_idx = torch.empty((b, k), device=dev, dtype=torch.int64) self._cand = torch.empty((b * nchunks * (k if k > 1 else 1)), device=dev, dtype=torch.int64) self._counter = torch.zeros((b,), device=dev, dtype=torch.int32) self._ptr = x.data_ptr() # Warmup run (produces the correct output), then capture a CUDA graph # so replay bypasses Python/C++ launch overhead on later calls. mod.topk_forward(x, k, self._out_val, self._out_idx, self._out_val, self._out_idx, self._cand, self._counter, nchunks) torch.cuda.synchronize() if not self._graph_failed: try: g = torch.cuda.CUDAGraph() with torch.cuda.graph(g): mod.topk_forward(x, k, self._out_val, self._out_idx, self._out_val, self._out_idx, self._cand, self._counter, nchunks) self._graph = g except Exception: self._graph = None self._graph_failed = True return self._out_val, self._out_idx 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]