"""Top-k via Triton: packed int64 sort with tl.topk.""" import torch import torch.nn as nn import triton import triton.language as tl @triton.jit def argmax_kernel(x_ptr, out_vals, out_idxs, n, batch_stride, out_stride, BLOCK_N: tl.constexpr): row = tl.program_id(0) offs = tl.arange(0, BLOCK_N) mask = offs < n x = tl.load(x_ptr + row * batch_stride + offs, mask=mask, other=float('-inf')) idx = tl.argmax(x, axis=0) val = tl.load(x_ptr + row * batch_stride + idx) tl.store(out_vals + row * out_stride, val) tl.store(out_idxs + row * out_stride, idx.to(tl.int64)) @triton.jit def topk_kernel(x_ptr, out_vals, out_idxs, batch_stride, out_stride, n, K: tl.constexpr, BLOCK_N: tl.constexpr): row = tl.program_id(0) offs = tl.arange(0, BLOCK_N) mask = offs < n x = tl.load(x_ptr + row * batch_stride + offs, mask=mask, other=float('-inf')) bits = x.to(tl.uint32, bitcast=True) neg = bits >= 0x80000000 transformed = tl.where(neg, ~bits, bits | 0x80000000) packed = (transformed.to(tl.int64) << 32) | offs.to(tl.int64) packed = packed ^ (tl.full((), 1, tl.int64) << 63) top_packed = tl.topk(packed, K) top_flipped = top_packed ^ (tl.full((), 1, tl.int64) << 63) top_transformed = (top_flipped >> 32).to(tl.uint32) top_idx = (top_flipped & 0xFFFFFFFF).to(tl.int32) was_pos = ((top_transformed >> 31) & 1).to(tl.int1) orig_bits = tl.where(was_pos, top_transformed ^ 0x80000000, ~top_transformed) vals = orig_bits.to(tl.float32, bitcast=True) k_offs = tl.arange(0, K) tl.store(out_vals + row * out_stride + k_offs, vals) tl.store(out_idxs + row * out_stride + k_offs, top_idx.to(tl.int64)) @triton.jit def local_topk_kernel(x_ptr, inter_vals, inter_idxs, batch_stride, chunk_size, chunks_per_row, n, K: tl.constexpr, BLOCK_N: tl.constexpr): pid = tl.program_id(0) row = pid // chunks_per_row chunk = pid % chunks_per_row chunk_start = chunk * chunk_size offs = tl.arange(0, BLOCK_N) global_offs = chunk_start + offs mask = global_offs < n x = tl.load(x_ptr + row * batch_stride + global_offs, mask=mask, other=float('-inf')) bits = x.to(tl.uint32, bitcast=True) neg = bits >= 0x80000000 transformed = tl.where(neg, ~bits, bits | 0x80000000) packed = (transformed.to(tl.int64) << 32) | global_offs.to(tl.int64) packed = packed ^ (tl.full((), 1, tl.int64) << 63) top_packed = tl.topk(packed, K) top_flipped = top_packed ^ (tl.full((), 1, tl.int64) << 63) top_transformed = (top_flipped >> 32).to(tl.uint32) top_idx = (top_flipped & 0xFFFFFFFF).to(tl.int32) was_pos = ((top_transformed >> 31) & 1).to(tl.int1) orig_bits = tl.where(was_pos, top_transformed ^ 0x80000000, ~top_transformed) vals = orig_bits.to(tl.float32, bitcast=True) k_offs = tl.arange(0, K) base = pid * K tl.store(inter_vals + base + k_offs, vals) tl.store(inter_idxs + base + k_offs, top_idx) @triton.jit def merge_kernel(inter_vals, inter_idxs, out_vals, out_idxs, chunks_per_row, K: tl.constexpr, TOTAL: tl.constexpr, TPAD: tl.constexpr): row = tl.program_id(0) offs = tl.arange(0, TPAD) base = row * chunks_per_row * K mask = offs < TOTAL vals = tl.load(inter_vals + base + offs, mask=mask, other=float('-inf')) idxs = tl.load(inter_idxs + base + offs, mask=mask, other=0) bits = vals.to(tl.uint32, bitcast=True) neg = bits >= 0x80000000 transformed = tl.where(neg, ~bits, bits | 0x80000000) packed = (transformed.to(tl.int64) << 32) | idxs.to(tl.int64) packed = packed ^ (tl.full((), 1, tl.int64) << 63) top_packed = tl.topk(packed, K) top_flipped = top_packed ^ (tl.full((), 1, tl.int64) << 63) top_transformed = (top_flipped >> 32).to(tl.uint32) top_idx = (top_flipped & 0xFFFFFFFF).to(tl.int32) was_pos = ((top_transformed >> 31) & 1).to(tl.int1) orig_bits = tl.where(was_pos, top_transformed ^ 0x80000000, ~top_transformed) top_vals = orig_bits.to(tl.float32, bitcast=True) k_offs = tl.arange(0, K) tl.store(out_vals + row * K + k_offs, top_vals) tl.store(out_idxs + row * K + k_offs, top_idx.to(tl.int64)) def _next_pow2(x): p = 1 while p < x: p <<= 1 return p 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): batch, n = x.shape[0], x.shape[1] k = self.k out_values = torch.empty(batch, k, dtype=torch.float32, device=x.device) out_indices = torch.empty(batch, k, dtype=torch.int64, device=x.device) if k == 1: BLOCK_N = _next_pow2(n) nw = min(32, max(1, BLOCK_N // 256)) argmax_kernel[(batch,)]( x, out_values, out_indices, n, x.stride(0), 1, BLOCK_N=BLOCK_N, num_warps=nw, ) return out_values, out_indices BLOCK_N = _next_pow2(n) if BLOCK_N <= 8192: nw = min(32, max(1, BLOCK_N // 256)) topk_kernel[(batch,)]( x, out_values, out_indices, x.stride(0), k, n, K=k, BLOCK_N=BLOCK_N, num_warps=nw, ) return out_values, out_indices chunk_size = 4096 chunks_per_row = (n + chunk_size - 1) // chunk_size total_blocks = batch * chunks_per_row CHUNK_N = _next_pow2(chunk_size) inter_vals = torch.empty(batch * chunks_per_row * k, dtype=torch.float32, device=x.device) inter_idxs = torch.empty(batch * chunks_per_row * k, dtype=torch.int32, device=x.device) nw1 = min(16, max(1, CHUNK_N // 256)) local_topk_kernel[(total_blocks,)]( x, inter_vals, inter_idxs, x.stride(0), chunk_size, chunks_per_row, n, K=k, BLOCK_N=CHUNK_N, num_warps=nw1, ) total = chunks_per_row * k TPAD = _next_pow2(total) nw2 = min(16, max(1, TPAD // 256)) merge_kernel[(batch,)]( inter_vals, inter_idxs, out_values, out_indices, chunks_per_row, K=k, TOTAL=total, TPAD=TPAD, num_warps=nw2, ) return out_values, out_indices 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]