KernelBench hard deprecated · H100
TopK Bitonic GPT-5.5
passdid not score
agent session30mtotal wall30mcheck5sbenchmark—output tokens120,962gpu-lock wait0sgpu-lock held5sregimememory
Per-shape vs governing ceilingeach shape graded against whichever binds — fp32 compute or HBM bandwidth
No per-shape benchmark data archived for this run.
Kernel source (redacted)
from __future__ import annotations
import os
os.environ["TORCH_CUDA_ARCH_LIST"] = "9.0"
os.environ.setdefault("MAX_JOBS", "2")
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
_CPP_SRC = r"""
#include <torch/extension.h>
void topk_cuda(torch::Tensor x,
torch::Tensor out_values,
torch::Tensor out_indices,
torch::Tensor partial_values,
torch::Tensor partial_indices,
torch::Tensor counters,
int64_t k,
int64_t chunks);
void topk_forward(torch::Tensor x,
torch::Tensor out_values,
torch::Tensor out_indices,
torch::Tensor partial_values,
torch::Tensor partial_indices,
torch::Tensor counters,
int64_t k,
int64_t chunks) {
topk_cuda(x, out_values, out_indices, partial_values, partial_indices, counters, k, chunks);
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("topk_forward", &topk_forward, "fixed shape selection forward");
}
"""
_CUDA_SRC = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <cub/block/block_radix_sort.cuh>
#include <stdint.h>
#include <limits.h>
#define CUDA_CHECK(err) do { \
cudaError_t err__ = (err); \
if (err__ != cudaSuccess) { \
TORCH_CHECK(false, cudaGetErrorString(err__)); \
} \
} while (0)
__device__ __forceinline__ bool better(float a, int ia, float b, int ib) {
return (a > b) || ((a == b) && (ia < ib));
}
__device__ __forceinline__ uint32_t ordered_key(float v) {
const uint32_t bits = __float_as_uint(v);
return (bits & 0x80000000u) ? ~bits : (bits ^ 0x80000000u);
}
__device__ __forceinline__ void grid_barrier(int* barrier_count, int* barrier_sense, int total_blocks) {
__shared__ int local_sense;
if (threadIdx.x == 0) {
const int sense = *barrier_sense;
const int old = atomicAdd(barrier_count, 1);
if (old == total_blocks - 1) {
*barrier_count = 0;
__threadfence();
atomicAdd(barrier_sense, 1);
} else {
volatile int* sense_ptr = barrier_sense;
while (*sense_ptr == sense) {
}
}
local_sense = *barrier_sense;
}
__syncthreads();
}
template<int K>
__device__ __forceinline__ void init_list(float (&vals)[K], int (&idxs)[K]) {
#pragma unroll 1
for (int i = 0; i < K; ++i) {
vals[i] = -INFINITY;
idxs[i] = INT_MAX;
}
}
template<int K>
__device__ __forceinline__ void insert_item(float v, int idx, float (&vals)[K], int (&idxs)[K]) {
if (!better(v, idx, vals[K - 1], idxs[K - 1])) {
return;
}
int pos = K - 1;
#pragma unroll 1
for (int j = K - 1; j > 0; --j) {
if (better(v, idx, vals[j - 1], idxs[j - 1])) {
vals[j] = vals[j - 1];
idxs[j] = idxs[j - 1];
pos = j - 1;
} else {
break;
}
}
vals[pos] = v;
idxs[pos] = idx;
}
template<int K>
__device__ __forceinline__ void merge_lists(const float* av,
const int* ai,
const float* bv,
const int* bi,
float (&outv)[K],
int (&outi)[K]) {
int pa = 0;
int pb = 0;
#pragma unroll 1
for (int t = 0; t < K; ++t) {
if (pb >= K || (pa < K && better(av[pa], ai[pa], bv[pb], bi[pb]))) {
outv[t] = av[pa];
outi[t] = ai[pa];
++pa;
} else {
outv[t] = bv[pb];
outi[t] = bi[pb];
++pb;
}
}
}
template<int K, int BLOCK_THREADS>
__device__ __forceinline__ void reduce_block_topk(float (&vals)[K],
int (&idxs)[K],
float* smem_vals,
int* smem_idxs) {
const int tid = threadIdx.x;
const int base = tid * K;
#pragma unroll 1
for (int i = 0; i < K; ++i) {
smem_vals[base + i] = vals[i];
smem_idxs[base + i] = idxs[i];
}
__syncthreads();
for (int stride = BLOCK_THREADS >> 1; stride > 0; stride >>= 1) {
if (tid < stride) {
const int other = (tid + stride) * K;
merge_lists<K>(smem_vals + base, smem_idxs + base,
smem_vals + other, smem_idxs + other,
vals, idxs);
#pragma unroll 1
for (int i = 0; i < K; ++i) {
smem_vals[base + i] = vals[i];
smem_idxs[base + i] = idxs[i];
}
}
__syncthreads();
}
}
template<int BLOCK_THREADS>
__global__ void argmax_kernel(const float* __restrict__ x,
float* __restrict__ outv,
int64_t* __restrict__ outi,
int n) {
const int row = blockIdx.x;
const int tid = threadIdx.x;
const float* row_ptr = x + static_cast<int64_t>(row) * n;
float best = -INFINITY;
int best_idx = INT_MAX;
for (int col = tid; col < n; col += BLOCK_THREADS) {
const float v = row_ptr[col];
if (better(v, col, best, best_idx)) {
best = v;
best_idx = col;
}
}
extern __shared__ unsigned char raw_smem[];
float* smem_vals = reinterpret_cast<float*>(raw_smem);
int* smem_idxs = reinterpret_cast<int*>(smem_vals + BLOCK_THREADS);
smem_vals[tid] = best;
smem_idxs[tid] = best_idx;
__syncthreads();
for (int stride = BLOCK_THREADS >> 1; stride > 0; stride >>= 1) {
if (tid < stride) {
const int other = tid + stride;
if (better(smem_vals[other], smem_idxs[other], smem_vals[tid], smem_idxs[tid])) {
smem_vals[tid] = smem_vals[other];
smem_idxs[tid] = smem_idxs[other];
}
}
__syncthreads();
}
if (tid == 0) {
outv[row] = smem_vals[0];
outi[row] = static_cast<int64_t>(smem_idxs[0]);
}
}
template<int K, int BLOCK_THREADS>
__global__ void one_block_kernel(const float* __restrict__ x,
float* __restrict__ outv,
int64_t* __restrict__ outi,
int n) {
const int row = blockIdx.x;
const int tid = threadIdx.x;
const float* row_ptr = x + static_cast<int64_t>(row) * n;
float vals[K];
int idxs[K];
init_list<K>(vals, idxs);
for (int col = tid; col < n; col += BLOCK_THREADS) {
insert_item<K>(row_ptr[col], col, vals, idxs);
}
extern __shared__ unsigned char raw_smem[];
float* smem_vals = reinterpret_cast<float*>(raw_smem);
int* smem_idxs = reinterpret_cast<int*>(smem_vals + BLOCK_THREADS * K);
reduce_block_topk<K, BLOCK_THREADS>(vals, idxs, smem_vals, smem_idxs);
if (tid == 0) {
const int64_t out_base = static_cast<int64_t>(row) * K;
#pragma unroll 1
for (int i = 0; i < K; ++i) {
outv[out_base + i] = vals[i];
outi[out_base + i] = static_cast<int64_t>(idxs[i]);
}
}
}
template<int K, int BLOCK_THREADS>
__global__ void multi_block_kernel(const float* __restrict__ x,
float* __restrict__ outv,
int64_t* __restrict__ outi,
float* __restrict__ partial_vals,
int* __restrict__ partial_idxs,
int* __restrict__ counters,
int n,
int chunks) {
const int block = blockIdx.x;
const int row = block / chunks;
const int chunk = block - row * chunks;
const int tid = threadIdx.x;
const int start = static_cast<int>((static_cast<int64_t>(n) * chunk) / chunks);
const int stop = static_cast<int>((static_cast<int64_t>(n) * (chunk + 1)) / chunks);
const float* row_ptr = x + static_cast<int64_t>(row) * n;
float vals[K];
int idxs[K];
init_list<K>(vals, idxs);
for (int col = start + tid; col < stop; col += BLOCK_THREADS) {
insert_item<K>(row_ptr[col], col, vals, idxs);
}
extern __shared__ unsigned char raw_smem[];
float* smem_vals = reinterpret_cast<float*>(raw_smem);
int* smem_idxs = reinterpret_cast<int*>(smem_vals + BLOCK_THREADS * K);
reduce_block_topk<K, BLOCK_THREADS>(vals, idxs, smem_vals, smem_idxs);
__shared__ int last_block;
if (tid == 0) {
const int pbase = (row * chunks + chunk) * K;
#pragma unroll 1
for (int i = 0; i < K; ++i) {
partial_vals[pbase + i] = vals[i];
partial_idxs[pbase + i] = idxs[i];
}
__threadfence();
const int old = atomicAdd(counters + row, 1);
last_block = (old == chunks - 1);
}
__syncthreads();
if (!last_block) {
return;
}
init_list<K>(vals, idxs);
const int total = chunks * K;
const int row_base = row * chunks * K;
for (int t = tid; t < total; t += BLOCK_THREADS) {
insert_item<K>(partial_vals[row_base + t], partial_idxs[row_base + t], vals, idxs);
}
reduce_block_topk<K, BLOCK_THREADS>(vals, idxs, smem_vals, smem_idxs);
if (tid == 0) {
const int64_t out_base = static_cast<int64_t>(row) * K;
#pragma unroll 1
for (int i = 0; i < K; ++i) {
outv[out_base + i] = vals[i];
outi[out_base + i] = static_cast<int64_t>(idxs[i]);
}
counters[row] = 0;
}
}
template<int K, int BLOCK_THREADS>
void set_one_attr() {
CUDA_CHECK(cudaFuncSetAttribute(one_block_kernel<K, BLOCK_THREADS>,
cudaFuncAttributeMaxDynamicSharedMemorySize,
BLOCK_THREADS * K * static_cast<int>(sizeof(float) + sizeof(int))));
}
template<int K, int BLOCK_THREADS>
void set_multi_attr() {
CUDA_CHECK(cudaFuncSetAttribute(multi_block_kernel<K, BLOCK_THREADS>,
cudaFuncAttributeMaxDynamicSharedMemorySize,
BLOCK_THREADS * K * static_cast<int>(sizeof(float) + sizeof(int))));
}
template<int K, int BT>
void launch_one(const float* x, float* outv, int64_t* outi, int batch, int n, cudaStream_t stream) {
const int smem = BT * K * static_cast<int>(sizeof(float) + sizeof(int));
set_one_attr<K, BT>();
one_block_kernel<K, BT><<<batch, BT, smem, stream>>>(x, outv, outi, n);
}
template<int K, int BT>
void launch_multi(const float* x,
float* outv,
int64_t* outi,
float* pvals,
int* pidxs,
int* counters,
int batch,
int n,
int chunks,
cudaStream_t stream) {
const int smem = BT * K * static_cast<int>(sizeof(float) + sizeof(int));
set_multi_attr<K, BT>();
multi_block_kernel<K, BT><<<batch * chunks, BT, smem, stream>>>(
x, outv, outi, pvals, pidxs, counters, n, chunks);
}
template<int K, int BLOCK_THREADS, typename IndexOut>
__device__ __forceinline__ void select_shared_to_output(float* svals,
int* sidxs,
int count,
float* red_vals,
int* red_idxs,
int* red_pos,
float* outv,
IndexOut* outi,
int64_t out_base) {
const int tid = threadIdx.x;
#pragma unroll 1
for (int r = 0; r < K; ++r) {
float best = -INFINITY;
int best_idx = INT_MAX;
int best_pos = -1;
for (int p = tid; p < count; p += BLOCK_THREADS) {
const float v = svals[p];
const int idx = sidxs[p];
if (better(v, idx, best, best_idx)) {
best = v;
best_idx = idx;
best_pos = p;
}
}
red_vals[tid] = best;
red_idxs[tid] = best_idx;
red_pos[tid] = best_pos;
__syncthreads();
for (int stride = BLOCK_THREADS >> 1; stride > 0; stride >>= 1) {
if (tid < stride) {
const int other = tid + stride;
if (better(red_vals[other], red_idxs[other], red_vals[tid], red_idxs[tid])) {
red_vals[tid] = red_vals[other];
red_idxs[tid] = red_idxs[other];
red_pos[tid] = red_pos[other];
}
}
__syncthreads();
}
if (tid == 0) {
outv[out_base + r] = red_vals[0];
outi[out_base + r] = static_cast<IndexOut>(red_idxs[0]);
if (red_pos[0] >= 0) {
svals[red_pos[0]] = -INFINITY;
sidxs[red_pos[0]] = INT_MAX;
}
}
__syncthreads();
}
}
template<int K, int BLOCK_THREADS>
__global__ void select_one_kernel(const float* __restrict__ x,
float* __restrict__ outv,
int64_t* __restrict__ outi,
int n,
int capacity) {
const int row = blockIdx.x;
const int tid = threadIdx.x;
const float* row_ptr = x + static_cast<int64_t>(row) * n;
extern __shared__ unsigned char raw_smem[];
float* svals = reinterpret_cast<float*>(raw_smem);
int* sidxs = reinterpret_cast<int*>(svals + capacity);
float* red_vals = reinterpret_cast<float*>(sidxs + capacity);
int* red_idxs = reinterpret_cast<int*>(red_vals + BLOCK_THREADS);
int* red_pos = red_idxs + BLOCK_THREADS;
for (int p = tid; p < capacity; p += BLOCK_THREADS) {
if (p < n) {
svals[p] = row_ptr[p];
sidxs[p] = p;
} else {
svals[p] = -INFINITY;
sidxs[p] = INT_MAX;
}
}
__syncthreads();
select_shared_to_output<K, BLOCK_THREADS, int64_t>(
svals, sidxs, n, red_vals, red_idxs, red_pos, outv, outi, static_cast<int64_t>(row) * K);
}
template<int K, int BLOCK_THREADS>
__global__ void select_multi_kernel(const float* __restrict__ x,
float* __restrict__ outv,
int64_t* __restrict__ outi,
float* __restrict__ partial_vals,
int* __restrict__ partial_idxs,
int* __restrict__ counters,
int n,
int chunks,
int tile_cap) {
const int block = blockIdx.x;
const int row = block / chunks;
const int chunk = block - row * chunks;
const int tid = threadIdx.x;
const int start = static_cast<int>((static_cast<int64_t>(n) * chunk) / chunks);
const int stop = static_cast<int>((static_cast<int64_t>(n) * (chunk + 1)) / chunks);
const int count = stop - start;
const float* row_ptr = x + static_cast<int64_t>(row) * n;
extern __shared__ unsigned char raw_smem[];
float* svals = reinterpret_cast<float*>(raw_smem);
int* sidxs = reinterpret_cast<int*>(svals + tile_cap);
float* red_vals = reinterpret_cast<float*>(sidxs + tile_cap);
int* red_idxs = reinterpret_cast<int*>(red_vals + BLOCK_THREADS);
int* red_pos = red_idxs + BLOCK_THREADS;
for (int p = tid; p < tile_cap; p += BLOCK_THREADS) {
if (p < count) {
svals[p] = row_ptr[start + p];
sidxs[p] = start + p;
} else {
svals[p] = -INFINITY;
sidxs[p] = INT_MAX;
}
}
__syncthreads();
const int pbase = (row * chunks + chunk) * K;
select_shared_to_output<K, BLOCK_THREADS, int>(
svals, sidxs, count, red_vals, red_idxs, red_pos, partial_vals, partial_idxs, pbase);
__shared__ int last_block;
if (tid == 0) {
__threadfence();
const int old = atomicAdd(counters + row, 1);
last_block = (old == chunks - 1);
}
__syncthreads();
if (!last_block) {
return;
}
const int total = chunks * K;
const int row_base = row * total;
#pragma unroll 1
for (int r = 0; r < K; ++r) {
float best = -INFINITY;
int best_idx = INT_MAX;
int best_pos = -1;
for (int p = tid; p < total; p += BLOCK_THREADS) {
const float v = partial_vals[row_base + p];
const int idx = partial_idxs[row_base + p];
if (better(v, idx, best, best_idx)) {
best = v;
best_idx = idx;
best_pos = p;
}
}
red_vals[tid] = best;
red_idxs[tid] = best_idx;
red_pos[tid] = best_pos;
__syncthreads();
for (int stride = BLOCK_THREADS >> 1; stride > 0; stride >>= 1) {
if (tid < stride) {
const int other = tid + stride;
if (better(red_vals[other], red_idxs[other], red_vals[tid], red_idxs[tid])) {
red_vals[tid] = red_vals[other];
red_idxs[tid] = red_idxs[other];
red_pos[tid] = red_pos[other];
}
}
__syncthreads();
}
if (tid == 0) {
const int64_t out_base = static_cast<int64_t>(row) * K;
outv[out_base + r] = red_vals[0];
outi[out_base + r] = static_cast<int64_t>(red_idxs[0]);
if (red_pos[0] >= 0) {
partial_vals[row_base + red_pos[0]] = -INFINITY;
}
}
__syncthreads();
}
if (tid == 0) {
counters[row] = 0;
}
}
template<int K, int BT>
void launch_select_one(const float* x, float* outv, int64_t* outi, int batch, int n, cudaStream_t stream) {
const int capacity = n;
const int smem = capacity * static_cast<int>(sizeof(float) + sizeof(int)) +
BT * static_cast<int>(sizeof(float) + sizeof(int) + sizeof(int));
CUDA_CHECK(cudaFuncSetAttribute(select_one_kernel<K, BT>,
cudaFuncAttributeMaxDynamicSharedMemorySize,
smem));
select_one_kernel<K, BT><<<batch, BT, smem, stream>>>(x, outv, outi, n, capacity);
}
template<int K, int BT>
void launch_select_multi(const float* x,
float* outv,
int64_t* outi,
float* pvals,
int* pidxs,
int* counters,
int batch,
int n,
int chunks,
cudaStream_t stream) {
const int tile_cap = (n + chunks - 1) / chunks;
const int smem = tile_cap * static_cast<int>(sizeof(float) + sizeof(int)) +
BT * static_cast<int>(sizeof(float) + sizeof(int) + sizeof(int));
CUDA_CHECK(cudaFuncSetAttribute(select_multi_kernel<K, BT>,
cudaFuncAttributeMaxDynamicSharedMemorySize,
smem));
select_multi_kernel<K, BT><<<batch * chunks, BT, smem, stream>>>(
x, outv, outi, pvals, pidxs, counters, n, chunks, tile_cap);
}
template<int BLOCK_THREADS, int RADIX_BLOCKS>
__global__ void radix64_single_row_kernel(const float* __restrict__ x,
float* __restrict__ outv,
int64_t* __restrict__ outi,
float* __restrict__ candidates_v,
int* __restrict__ candidates_i,
int* __restrict__ counters,
int n,
int candidate_cap) {
const int tid = threadIdx.x;
const int bid = blockIdx.x;
const int seg_start = static_cast<int>((static_cast<int64_t>(n) * bid) / RADIX_BLOCKS);
const int seg_stop = static_cast<int>((static_cast<int64_t>(n) * (bid + 1)) / RADIX_BLOCKS);
extern __shared__ unsigned char raw_smem[];
int* bin_counts = reinterpret_cast<int*>(raw_smem);
float* red_vals = reinterpret_cast<float*>(bin_counts + 16 * BLOCK_THREADS);
int* red_idxs = reinterpret_cast<int*>(red_vals + BLOCK_THREADS);
int* red_pos = red_idxs + BLOCK_THREADS;
if (bid == 0 && tid == 0) {
counters[2] = counters[3] = counters[4] = counters[5] = 0;
counters[6] = counters[7] = counters[8] = counters[9] = 0;
counters[10] = counters[11] = counters[12] = counters[13] = 0;
counters[14] = counters[15] = counters[16] = counters[17] = 0;
counters[18] = 0;
}
grid_barrier(counters, counters + 1, RADIX_BLOCKS);
uint32_t prefix = 0;
uint32_t mask = 0;
int kth = 64;
#pragma unroll 1
for (int shift = 28; shift >= 0; shift -= 4) {
int local_bins[16];
#pragma unroll
for (int b = 0; b < 16; ++b) {
local_bins[b] = 0;
}
for (int col = seg_start + tid; col < seg_stop; col += BLOCK_THREADS) {
const uint32_t key = ordered_key(x[col]);
if ((key & mask) == prefix) {
const int bin = static_cast<int>((key >> shift) & 15u);
local_bins[bin] += 1;
}
}
#pragma unroll
for (int b = 0; b < 16; ++b) {
bin_counts[b * BLOCK_THREADS + tid] = local_bins[b];
}
__syncthreads();
for (int stride = BLOCK_THREADS >> 1; stride > 0; stride >>= 1) {
if (tid < stride) {
#pragma unroll
for (int b = 0; b < 16; ++b) {
bin_counts[b * BLOCK_THREADS + tid] += bin_counts[b * BLOCK_THREADS + tid + stride];
}
}
__syncthreads();
}
if (tid == 0) {
#pragma unroll
for (int b = 0; b < 16; ++b) {
atomicAdd(counters + 2 + b, bin_counts[b * BLOCK_THREADS]);
}
}
grid_barrier(counters, counters + 1, RADIX_BLOCKS);
int next_kth = kth;
int chosen = 0;
#pragma unroll
for (int b = 15; b >= 0; --b) {
const int c = counters[2 + b];
if (c >= next_kth) {
chosen = b;
break;
}
next_kth -= c;
}
prefix |= (static_cast<uint32_t>(chosen) << shift);
mask |= (0xFu << shift);
kth = next_kth;
if (bid == 0 && tid == 0) {
#pragma unroll
for (int b = 0; b < 16; ++b) {
counters[2 + b] = 0;
}
}
grid_barrier(counters, counters + 1, RADIX_BLOCKS);
}
const uint32_t threshold = prefix;
for (int col = seg_start + tid; col < seg_stop; col += BLOCK_THREADS) {
const float v = x[col];
if (ordered_key(v) >= threshold) {
const int pos = atomicAdd(counters + 18, 1);
if (pos < candidate_cap) {
candidates_v[pos] = v;
candidates_i[pos] = col;
}
}
}
grid_barrier(counters, counters + 1, RADIX_BLOCKS);
if (bid == 0) {
int count = counters[18];
if (count > candidate_cap) {
count = candidate_cap;
}
#pragma unroll 1
for (int r = 0; r < 64; ++r) {
float best = -INFINITY;
int best_idx = INT_MAX;
int best_pos = -1;
for (int p = tid; p < count; p += BLOCK_THREADS) {
const float v = candidates_v[p];
const int idx = candidates_i[p];
if (better(v, idx, best, best_idx)) {
best = v;
best_idx = idx;
best_pos = p;
}
}
red_vals[tid] = best;
red_idxs[tid] = best_idx;
red_pos[tid] = best_pos;
__syncthreads();
for (int stride = BLOCK_THREADS >> 1; stride > 0; stride >>= 1) {
if (tid < stride) {
const int other = tid + stride;
if (better(red_vals[other], red_idxs[other], red_vals[tid], red_idxs[tid])) {
red_vals[tid] = red_vals[other];
red_idxs[tid] = red_idxs[other];
red_pos[tid] = red_pos[other];
}
}
__syncthreads();
}
if (tid == 0) {
outv[r] = red_vals[0];
outi[r] = static_cast<int64_t>(red_idxs[0]);
if (red_pos[0] >= 0) {
candidates_v[red_pos[0]] = -INFINITY;
}
}
__syncthreads();
}
if (tid == 0) {
counters[18] = 0;
}
}
}
void launch_radix64_single(const float* x,
float* outv,
int64_t* outi,
float* candidates_v,
int* candidates_i,
int* counters,
int n,
int candidate_cap,
cudaStream_t stream) {
constexpr int BT = 256;
constexpr int RB = 64;
const int smem = 16 * BT * static_cast<int>(sizeof(int)) +
BT * static_cast<int>(sizeof(float) + sizeof(int) + sizeof(int));
radix64_single_row_kernel<BT, RB><<<RB, BT, smem, stream>>>(
x, outv, outi, candidates_v, candidates_i, counters, n, candidate_cap);
}
template<int BLOCK_THREADS, int ITEMS_PER_THREAD, int K>
__global__ void cub_sort64_single_row_kernel(const float* __restrict__ x,
float* __restrict__ outv,
int64_t* __restrict__ outi,
float* __restrict__ partial_vals,
int* __restrict__ partial_idxs,
int* __restrict__ counters,
int chunks) {
using BlockSort = cub::BlockRadixSort<float, BLOCK_THREADS, ITEMS_PER_THREAD, int>;
__shared__ typename BlockSort::TempStorage sort_storage;
__shared__ float red_vals[BLOCK_THREADS];
__shared__ int red_idxs[BLOCK_THREADS];
__shared__ int red_pos[BLOCK_THREADS];
__shared__ int last_block;
const int tid = threadIdx.x;
const int chunk = blockIdx.x;
constexpr int TILE = BLOCK_THREADS * ITEMS_PER_THREAD;
const int start = chunk * TILE;
float keys[ITEMS_PER_THREAD];
int vals[ITEMS_PER_THREAD];
#pragma unroll
for (int item = 0; item < ITEMS_PER_THREAD; ++item) {
const int col = start + item * BLOCK_THREADS + tid;
keys[item] = x[col];
vals[item] = col;
}
BlockSort(sort_storage).SortDescending(keys, vals);
__syncthreads();
#pragma unroll
for (int item = 0; item < ITEMS_PER_THREAD; ++item) {
const int rank = tid * ITEMS_PER_THREAD + item;
if (rank < K) {
partial_vals[chunk * K + rank] = keys[item];
partial_idxs[chunk * K + rank] = vals[item];
}
}
__syncthreads();
if (tid == 0) {
__threadfence();
const int old = atomicAdd(counters, 1);
last_block = (old == chunks - 1);
}
__syncthreads();
if (!last_block) {
return;
}
const int total = chunks * K;
#pragma unroll 1
for (int r = 0; r < K; ++r) {
float best = -INFINITY;
int best_idx = INT_MAX;
int best_pos = -1;
for (int p = tid; p < total; p += BLOCK_THREADS) {
const float v = partial_vals[p];
const int idx = partial_idxs[p];
if (better(v, idx, best, best_idx)) {
best = v;
best_idx = idx;
best_pos = p;
}
}
red_vals[tid] = best;
red_idxs[tid] = best_idx;
red_pos[tid] = best_pos;
__syncthreads();
for (int stride = BLOCK_THREADS >> 1; stride > 0; stride >>= 1) {
if (tid < stride) {
const int other = tid + stride;
if (better(red_vals[other], red_idxs[other], red_vals[tid], red_idxs[tid])) {
red_vals[tid] = red_vals[other];
red_idxs[tid] = red_idxs[other];
red_pos[tid] = red_pos[other];
}
}
__syncthreads();
}
if (tid == 0) {
outv[r] = red_vals[0];
outi[r] = static_cast<int64_t>(red_idxs[0]);
if (red_pos[0] >= 0) {
partial_vals[red_pos[0]] = -INFINITY;
}
}
__syncthreads();
}
if (tid == 0) {
counters[0] = 0;
}
}
void launch_cub_sort64_single(const float* x,
float* outv,
int64_t* outi,
float* partial_vals,
int* partial_idxs,
int* counters,
int chunks,
cudaStream_t stream) {
constexpr int BT = 256;
constexpr int ITEMS = 16;
constexpr int K = 64;
cub_sort64_single_row_kernel<BT, ITEMS, K><<<chunks, BT, 0, stream>>>(
x, outv, outi, partial_vals, partial_idxs, counters, chunks);
}
void topk_cuda(torch::Tensor x,
torch::Tensor out_values,
torch::Tensor out_indices,
torch::Tensor partial_values,
torch::Tensor partial_indices,
torch::Tensor counters,
int64_t k64,
int64_t chunks64) {
TORCH_CHECK(x.is_cuda(), "input must be CUDA");
TORCH_CHECK(x.scalar_type() == torch::kFloat32, "input must be fp32");
TORCH_CHECK(x.dim() == 2, "input must be 2D");
TORCH_CHECK(x.is_contiguous(), "input must be contiguous");
const int batch = static_cast<int>(x.size(0));
const int n = static_cast<int>(x.size(1));
const int k = static_cast<int>(k64);
const int chunks = static_cast<int>(chunks64);
TORCH_CHECK(k == 1 || k == 8 || k == 16 || k == 32 || k == 64, "unsupported k");
cudaStream_t stream = at::cuda::getCurrentCUDAStream();
const float* x_ptr = x.data_ptr<float>();
float* outv_ptr = out_values.data_ptr<float>();
int64_t* outi_ptr = out_indices.data_ptr<int64_t>();
if (k == 1) {
constexpr int BT = 256;
const int smem = BT * static_cast<int>(sizeof(float) + sizeof(int));
argmax_kernel<BT><<<batch, BT, smem, stream>>>(x_ptr, outv_ptr, outi_ptr, n);
C10_CUDA_KERNEL_LAUNCH_CHECK();
return;
}
if (batch == 1 && n == 131072 && k == 64) {
launch_cub_sort64_single(x_ptr, outv_ptr, outi_ptr,
partial_values.data_ptr<float>(),
partial_indices.data_ptr<int>(),
counters.data_ptr<int>(),
chunks,
stream);
C10_CUDA_KERNEL_LAUNCH_CHECK();
return;
}
if (chunks <= 1) {
switch (k) {
case 8:
launch_select_one<8, 256>(x_ptr, outv_ptr, outi_ptr, batch, n, stream);
break;
case 16:
launch_select_one<16, 256>(x_ptr, outv_ptr, outi_ptr, batch, n, stream);
break;
case 32:
launch_select_one<32, 256>(x_ptr, outv_ptr, outi_ptr, batch, n, stream);
break;
case 64:
launch_select_one<64, 256>(x_ptr, outv_ptr, outi_ptr, batch, n, stream);
break;
}
} else {
float* pvals = partial_values.data_ptr<float>();
int* pidxs = partial_indices.data_ptr<int>();
int* ctrs = counters.data_ptr<int>();
switch (k) {
case 8:
launch_select_multi<8, 256>(x_ptr, outv_ptr, outi_ptr, pvals, pidxs, ctrs, batch, n, chunks, stream);
break;
case 16:
launch_select_multi<16, 256>(x_ptr, outv_ptr, outi_ptr, pvals, pidxs, ctrs, batch, n, chunks, stream);
break;
case 32:
launch_select_multi<32, 256>(x_ptr, outv_ptr, outi_ptr, pvals, pidxs, ctrs, batch, n, chunks, stream);
break;
case 64:
launch_select_multi<64, 256>(x_ptr, outv_ptr, outi_ptr, pvals, pidxs, ctrs, batch, n, chunks, stream);
break;
}
}
C10_CUDA_KERNEL_LAUNCH_CHECK();
}
"""
_ext = load_inline(
name="topk_fixed_hopper_ext_v10",
cpp_sources=_CPP_SRC,
cuda_sources=_CUDA_SRC,
extra_cflags=["-O2"],
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.chunks = self._choose_chunks(batch, n, k)
self.register_buffer("_dummy", torch.zeros(1))
self.register_buffer("_out_values", torch.empty((batch, k), dtype=torch.float32), persistent=False)
self.register_buffer("_out_indices", torch.empty((batch, k), dtype=torch.int64), persistent=False)
self.register_buffer("_partial_values", torch.empty((max(1, batch * self.chunks), k), dtype=torch.float32), persistent=False)
self.register_buffer("_partial_indices", torch.empty((max(1, batch * self.chunks), k), dtype=torch.int32), persistent=False)
self.register_buffer("_counters", torch.zeros((max(32, batch),), dtype=torch.int32), persistent=False)
@staticmethod
def _choose_chunks(batch: int, n: int, k: int) -> int:
if k == 1:
return 1
if batch == 1 and n >= 131072 and k == 64:
return 32
if batch <= 16 and k <= 16:
return 8
if batch <= 32 and k >= 32:
return 1
return 1
def forward(self, x: torch.Tensor):
_ext.topk_forward(
x,
self._out_values,
self._out_indices,
self._partial_values,
self._partial_indices,
self._counters,
self.k,
self.chunks,
)
return self._out_values, self._out_indices
batch = 64
n = 8192
k = 8
def get_inputs():
return [torch.randn(batch, n, dtype=torch.float32)]
def get_init_inputs():
return [batch, n, k]
20260618_041839_codex_gpt-5.5_05_topk_bitonic