Four ways to write the same FP8 top-K indexer
One kernel, four implementations, one B200. This walks through the math, the shared plan, the source for each step, and what the timings say. The listings are the first section below.
The first two numbers are the official flashinfer-bench measurement: CUDA events are replaced by CUPTI, the L2 cache is flushed, and the reported time is the span from the first kernel start to the last kernel end across 128 contest shapes. The last two are a smaller check, described below, on five synthetic shapes. They are comparable to each other. They are an upper bound on the contest number for the same shape.
The same pieces, side by side
Each step of the kernel is below. Pick a language and every step follows. PyTorch is the reference the other four implement: one loop, a matrix multiply, and torch.topk. The whole file is right after the tabs. The other listings are the source that was timed. A line that says ... is a cut between two regions of the same file.
Which kernel runs
The longest sequence in the batch, measured in pages of 64 tokens, picks the kernel. At 32 pages or fewer every live token already fits in the top 2048, so scoring is skipped.
// Stage-1 plan for a call; derivable from max_num_pages alone.
enum class Plan : uint8_t {
FastPath = 0, // context fits in top-K: skip Stage 1 and Stage 2
Short = 1, // kFastPathMaxPages < pages < kPersistentPageThreshold
PersistentWs = 2, // pages >= kPersistentPageThreshold
};
inline Plan select_plan(int max_num_pages) {
if (max_num_pages <= kFastPathMaxPages) return Plan::FastPath;
if (max_num_pages >= kPersistentPageThreshold) return Plan::PersistentWs;
return Plan::Short;
}
def _stage1_plan(batch, max_num_pages):
"""(pages_per_tile, tiles_per_prog, grid_x, stages, logits_per_row)."""
if max_num_pages < PERSISTENT_MIN_PAGES:
pages, stages = SHORT_PAGES_PER_TILE, 1
tiles = _ceil_div(max_num_pages, pages)
tiles_per_prog = 1
else:
pages, stages = 2, PERSISTENT_STAGES
tiles = _ceil_div(max_num_pages, pages)
programs = min(tiles, _ceil_div(PERSISTENT_PROGRAMS, batch))
tiles_per_prog = min(max(_ceil_div(tiles, programs), PERSISTENT_MIN_TILES),
PERSISTENT_MAX_TILES)
logits_per_row = tiles * pages * PAGE.value
return pages, tiles_per_prog, _ceil_div(tiles, tiles_per_prog), stages, logits_per_row
# ...
def kernel(q_index_fp8, k_index_cache_fp8, weights, seq_lens, block_table, topk_indices):
batch, max_num_pages = block_table.shape
if max_num_pages <= FAST_PATH_MAX_PAGES.value:
_fast_path[(batch,)](seq_lens, block_table, topk_indices, max_num_pages, num_warps=4)
return
def kernel(q_index_fp8, k_index_cache_fp8, weights, seq_lens, block_table, topk_indices):
batch, max_num_pages = block_table.shape
device = block_table.device
if max_num_pages <= FAST_MAX_PAGES:
def fast():
_fast_path(seq_lens, block_table, topk_indices)
key = (seq_lens.data_ptr(), block_table.data_ptr(), topk_indices.data_ptr(),
batch, max_num_pages)
_replay(key, device, fast)
return
void run(torch::Tensor q, torch::Tensor k, torch::Tensor weights, torch::Tensor seq_lens,
torch::Tensor block_table, torch::Tensor topk_indices) {
const int batch = block_table.size(0);
const int max_pages = block_table.size(1);
auto stream = at::cuda::getCurrentCUDAStream();
if (max_pages <= 32) {
fast_path<<<batch, 256, 0, stream>>>(
seq_lens.data_ptr<int>(), block_table.data_ptr<int>(),
topk_indices.data_ptr<int>(), max_pages);
check(cudaGetLastError(), "fast path");
return;
}
No page-count dispatch. Every row is scored, then the top 2048 are kept.
def kernel(
q_index_fp8: torch.Tensor, # [B, H, D]
k_index_cache_fp8: torch.Tensor, # [P, PS, 1, 132]
weights: torch.Tensor, # [B, H]
seq_lens: torch.Tensor, # [B]
block_table: torch.Tensor, # [B, M]
topk_indices: torch.Tensor, # [B, K] destination
) -> None:
"""Destination-passing wrapper matching ``solution/python/solution.py``."""
out, = run(q_index_fp8, k_index_cache_fp8, weights, seq_lens, block_table)
topk_indices.copy_(out) # [B, K]
# ... run(), one row at a time
for b in range(batch_size):
# S = number of valid logical tokens in this row
seq_len = int(seq_lens[b].item())
if seq_len == 0:
continue
baselines/pytorch_naive_reference.py, lines 174–184 and 122–126
Fast path
The output is the block-table remap of 0 .. seq_len, and -1 after that. Q, K, and the weights are never read.
__global__ __launch_bounds__(128)
void topk_fast_path_kernel(
const int* __restrict__ seq_lens,
const int* __restrict__ block_table,
int max_num_pages,
int* __restrict__ out_indices)
{
constexpr int kInts4PerRow = kTopK / 4; // 512 int4 per row
constexpr int kInt4PerThread = kInts4PerRow / 128; // 4 int4 per thread
const int b = blockIdx.x;
const int tid = threadIdx.x;
__shared__ int smem_bt[kFastPathMaxPages];
if (tid < kFastPathMaxPages) {
smem_bt[tid] = (tid < max_num_pages)
? block_table[b * max_num_pages + tid]
: 0;
}
const int seq_len = seq_lens[b];
int4* out4 = reinterpret_cast<int4*>(
out_indices + static_cast<size_t>(b) * kTopK);
__syncthreads();
#pragma unroll
for (int s = 0; s < kInt4PerThread; ++s) {
const int i4 = tid + s * 128; // 0..511
const int base = i4 << 2; // 0..2044, stride 4
const int page0 = (base + 0) >> 6; // / 64
const int page1 = (base + 1) >> 6;
const int page2 = (base + 2) >> 6;
const int page3 = (base + 3) >> 6;
const int slot0 = (base + 0) & 63;
const int slot1 = (base + 1) & 63;
const int slot2 = (base + 2) & 63;
const int slot3 = (base + 3) & 63;
int4 v;
v.x = (base + 0 < seq_len) ? (smem_bt[page0] << 6) + slot0 : -1;
v.y = (base + 1 < seq_len) ? (smem_bt[page1] << 6) + slot1 : -1;
v.z = (base + 2 < seq_len) ? (smem_bt[page2] << 6) + slot2 : -1;
v.w = (base + 3 < seq_len) ? (smem_bt[page3] << 6) + slot3 : -1;
out4[i4] = v;
}
}
@triton.jit
def _fast_path(seq_lens_ptr, bt_ptr, out_ptr, max_num_pages):
"""out[b] = block-table transform of [0, seq_len), -1 past seq_len."""
b = tl.program_id(0)
seq_len = tl.load(seq_lens_ptr + b)
p = tl.arange(0, FAST_PATH_MAX_PAGES)
j = tl.arange(0, PAGE)
# One load per page, not per token: [32] page ids broadcast to [32, 64].
page = tl.load(bt_ptr + b * max_num_pages + p, mask=p < max_num_pages, other=0)
tok = p[:, None] * PAGE + j[None, :]
phys = page[:, None] * PAGE + j[None, :]
tl.store(out_ptr + b * TOPK + tok, tl.where(tok < seq_len, phys, -1))
@tilelang.jit(target="cuda", pass_configs=_PASS)
def _fast_path(seq_lens, block_table, out):
"""out[b] = block-table transform of [0, seq_len), -1 past seq_len."""
B = T.dynamic("B")
max_pages = T.dynamic("max_pages")
seq_lens: T.Tensor((B,), T.int32)
block_table: T.Tensor((B, max_pages), T.int32)
out: T.Tensor((B, TOPK), T.int32)
with T.Kernel(B, threads=256) as b:
seq = seq_lens[b]
for n in T.Parallel(TOPK):
# seq_len never reaches a page the table does not hold.
page = block_table[b, T.min(n // PAGE, max_pages - 1)]
phys = page * PAGE + n % PAGE
out[b, n] = T.if_then_else(n < seq, phys, -1)
__global__ void fast_path(const int* __restrict__ seq_lens,
const int* __restrict__ block_table,
int* __restrict__ out,
int max_pages) {
const int b = blockIdx.x;
const int seq = seq_lens[b];
for (int n = threadIdx.x; n < kTopK; n += blockDim.x) {
const int page = block_table[b * max_pages + min(n / kPage, max_pages - 1)];
out[b * kTopK + n] = (n < seq) ? page * kPage + (n % kPage) : -1;
}
}
No bypass. The output row starts as -1, and a sequence shorter than 2048 simply selects fewer tokens.
# topk_indices: [B, K] int32, pre-filled with -1 padding
topk_indices = torch.full(
(batch_size, TOPK), -1, dtype=torch.int32, device=device
)
# ...
# ---- top-K over logical tokens ----------------------------------------
# topk_local: [actual_topk] logical ids in [0, S)
actual_topk = min(TOPK, seq_len)
_, topk_local = torch.topk(logits, actual_topk) # values unused
baselines/pytorch_naive_reference.py, lines 117–120 and 153–156
Gather a page into the MMA tile
The KV cache is paged, so the CTA copies tokens into the 128-byte swizzle the tensor core reads, and loads the FP32 scale that sits after the FP8 bytes. The CUDA short kernel scores one page and zeroes the other half of the M=128 tile. The persistent CUDA kernel and the three ports score two pages.
{
const uint4* src = reinterpret_cast<const uint4*>(
q_fp8 + static_cast<size_t>(b) * kNumHeads * kHeadDim);
uint4* dst = reinterpret_cast<uint4*>(smem_q);
constexpr int kVec = (kNumHeads * kHeadDim) / 16;
#pragma unroll 4
for (int i = tid; i < kVec; i += kThreads) dst[swizzle_16b(i)] = src[i];
}
const int page_idx = block_table[b * max_num_pages + tile_idx];
const uint8_t* page_ptr = kv_cache + static_cast<size_t>(page_idx) * kPageBytes;
{
const uint4* src = reinterpret_cast<const uint4*>(page_ptr);
uint4* dst = reinterpret_cast<uint4*>(smem_k);
constexpr int kVecReal = (kBlockKv * kHeadDim) / 16;
constexpr int kVecTotal = (kUMMA_M * kHeadDim) / 16;
const uint4 zero4 = make_uint4(0u, 0u, 0u, 0u);
#pragma unroll 4
for (int i = tid; i < kVecReal; i += kThreads)
dst[swizzle_16b(i)] = src[i];
#pragma unroll 4
for (int i = tid; i < (kVecTotal - kVecReal); i += kThreads)
dst[swizzle_16b(i + kVecReal)] = zero4;
}
if (tid < kBlockKv)
smem_kscale[tid] = reinterpret_cast<const float*>(page_ptr + kScaleOffsetBytes)[tid];
if (tid < kNumHeads)
smem_w[tid] = weights[b * kNumHeads + tid];
for t in tl.range(first, last, num_stages=STAGES):
tok = t * TILE + m # [TILE]
# Tokens past seq_len in the last tile re-read the row's final live
# page. That keeps every address valid without a masked load, and
# their logits are dropped by the store mask below.
slot = tl.minimum(tok // PAGE, last_page)
page = tl.load(bt_ptr + b * max_num_pages + slot).to(tl.int64)
row = tok % PAGE
k = tl.load(k_ptr + (page * PAGE_BYTES + row * D)[:, None] + d[None, :]) # [TILE, D] fp8
scale = tl.load(kscale_ptr + page * (PAGE_BYTES // 4) + SCALE_OFFSET // 4 + row)
tx = T.get_thread_binding()
# 128 threads cover a row's 8 chunks of 16 bytes. ldg32 is the
# widest load whose result is a scalar we can bitcast; a uint32x4
# from ldg128 cannot be indexed in this frontend.
for j in T.serial(4):
vid = tx + j * 128
h = vid // 8
col = (vid % 8) * 16
for part in T.serial(4):
words[part] = T.ldg32(q[b, h, col + part * 4])
for e in T.serial(16):
q_s[h, col + e] = gathered[e]
for j in T.serial(8):
vid = tx + j * 128
i = vid // 8
col = (vid % 8) * 16
tok = tile * TILE + i
slot = T.min(tok // PAGE, last_page)
page = T.cast(block_table[b, slot], "int64")
row = tok % PAGE
base = page * PAGE_BYTES + row * D + col
for part in T.serial(4):
words[part] = T.ldg32(k[base + part * 4])
for e in T.serial(16):
k_s[i, col + e] = gathered[e]
for h in T.Parallel(H):
w_s[h] = w[b, h]
for i in T.Parallel(TILE):
tok = tile * TILE + i
slot = T.min(tok // PAGE, last_page)
page = T.cast(block_table[b, slot], "int64")
row = tok % PAGE
scale_s[i] = kscale[page * SCALE_FLOATS + SCALE_OFFSET + row]
// One 16-byte store per vector, at the swizzled index the MMA descriptor
// reads. A byte-wise store through operator[] issues 16 shared stores
// for the same 16 bytes.
{
uint4* dst = reinterpret_cast<uint4*>(q_smem.data);
#pragma unroll
for (int j = 0; j < (kHeads * kDim) / 16 / kStage1Threads; ++j) {
const int v = tx + j * kStage1Threads;
const int h = v >> 3;
const int col = (v & 7) << 4;
const uint8_t* src = q + (static_cast<int64_t>(b) * kHeads + h) * kDim + col;
dst[swizzle_16b(v)] = *reinterpret_cast<const uint4*>(src);
}
}
{
uint4* dst = reinterpret_cast<uint4*>(k_smem.data);
uint4 regs[(kTile * kDim) / 16 / kStage1Threads];
int dest[(kTile * kDim) / 16 / kStage1Threads];
#pragma unroll
for (int j = 0; j < (kTile * kDim) / 16 / kStage1Threads; ++j) {
const int v = tx + j * kStage1Threads;
const int i = v >> 3;
const int col = (v & 7) << 4;
const int tok = tile * kTile + i;
const int slot = min(tok / kPage, last_page);
const int page = row_bt[slot];
const int row = tok % kPage;
const int64_t addr = static_cast<int64_t>(page) * kPageBytes + row * kDim + col;
regs[j] = *reinterpret_cast<const uint4*>(k + addr);
dest[j] = swizzle_16b(v);
}
#pragma unroll
for (int j = 0; j < (kTile * kDim) / 16 / kStage1Threads; ++j)
dst[dest[j]] = regs[j];
}
if (tx < kHeads) w_s[tx] = weights[b * kHeads + tx];
if (tx < kTile) {
const int tok = tile * kTile + tx;
const int slot = min(tok / kPage, last_page);
const int page = row_bt[slot];
const int row = tok % kPage;
scale_s[tx] = kscale[static_cast<int64_t>(page) * (kPageBytes / 4) + (kDim * kPage) / 4 + row];
}
The per-token scale is multiplied into K here. A non-negative scale makes that equal to scaling the ReLU'd dot afterwards.
# Per page the bytes are packed flat: [all FP8 | all scales], NOT
# interleaved as [fp8||scale] per token. Flatten, then split.
# kv_flat: [P, PS*132] = [P, 8448] uint8
kv_flat = cache_u8.view(num_pages, page_size * head_dim_sf)
# FP8 payload: first PS*D bytes per page
# fp8_bytes: [P, PS*D] = [P, 8192] uint8
# fp8: [P, PS, D] float8_e4m3fn
# fp8_f32: [P, PS, D] float32
fp8_bytes = kv_flat[:, : page_size * head_dim].contiguous()
fp8 = fp8_bytes.view(num_pages, page_size, head_dim).view(torch.float8_e4m3fn)
fp8_f32 = fp8.to(torch.float32)
# Scales: last PS*4 bytes per page -> PS float32s
# scale_bytes: [P, PS*4] = [P, 256] uint8
# scale: [P, PS, 1] float32
scale_bytes = kv_flat[:, page_size * head_dim :].contiguous()
scale = scale_bytes.view(torch.float32).view(num_pages, page_size, 1)
# Broadcast multiply: [P, PS, D] * [P, PS, 1] -> [P, PS, D]
return fp8_f32 * scale
# ...
# Logical tokens [0, S) live in the first Np = ceil(S / PS) pages.
# page_indices: [Np] — physical page ids from the block table
num_pages_for_seq = (seq_len + page_size - 1) // page_size
page_indices = block_table[b, :num_pages_for_seq].to(torch.long) # [Np]
# Gather those pages, flatten tokens, trim to S:
# K_all[page_indices]: [Np, PS, D]
# .reshape(-1, D): [Np*PS, D]
# [:seq_len]: [S, D]
K = K_all[page_indices].reshape(-1, head_dim)[:seq_len] # [S, D]
baselines/pytorch_naive_reference.py, lines 72–92 and 128–137
The matrix multiply
Q is 64×128 and the K tile is 128×128. The product is FP32 in tensor memory. CUDA writes the K loop as tcgen05.mma. Triton, TileLang, and ThunderKittens each call that instruction through their own name.
{
const auto instr = dsa_umma::make_instr_desc_f8f6f4(
dsa_umma::F8F6F4Format::E4M3, dsa_umma::F8F6F4Format::E4M3,
dsa_umma::CFormat::F32,
dsa_umma::Major::K, dsa_umma::Major::K,
kUMMA_M, kUMMA_N);
issue_umma_k_commit<kKIters>(
tmem_addr,
make_kmajor_desc(smem_k, kSboBytes),
make_kmajor_desc(smem_q, kSboBytes),
instr,
dsa_ptx::smem_ptr_to_uint(&smem_mbar),
warp_id, lane);
}
// issue_umma_k_commit, the loop that call hides. K steps by 32 bytes.
constexpr int kKStep = 32;
if (warp_id == 0) {
dsa_ptx::tcgen05_fence_after_thread_sync();
if (lane == 0) {
#pragma unroll
for (int k = 0; k < KIters; ++k) {
const int k_off = k * kKStep;
dsa_ptx::tcgen05_mma_f8f6f4_ss(
tmem_addr,
advance_k(a_base, k_off),
advance_k(b_base, k_off),
instr, (k == 0) ? 0u : 1u);
}
dsa_ptx::tcgen05_commit_1sm(mbar_addr);
}
}
solution/python/stage1_short.cuh, lines 116–129, and solution/python/stage1_common.cuh, lines 73–87
h = tl.arange(0, H)
d = tl.arange(0, D)
m = tl.arange(0, TILE)
# Loaded once per program and reused by every tile.
q = tl.load(q_ptr + b * (H * D) + h[:, None] * D + d[None, :]) # [H, D] fp8
qt = tl.trans(q) # [D, H]
w = tl.load(w_ptr + b * H + h) # [H] f32
first = tl.program_id(0) * tiles_per_prog
# Tiles entirely past seq_len are skipped: Stage 2 only reads logits below
# seq_len, so they never need a value.
last = tl.minimum(first + tiles_per_prog, (seq_len + TILE - 1) // TILE)
last_page = (seq_len - 1) // PAGE
for t in tl.range(first, last, num_stages=STAGES):
tok = t * TILE + m # [TILE]
# Tokens past seq_len in the last tile re-read the row's final live
# page. That keeps every address valid without a masked load, and
# their logits are dropped by the store mask below.
slot = tl.minimum(tok // PAGE, last_page)
page = tl.load(bt_ptr + b * max_num_pages + slot).to(tl.int64)
row = tok % PAGE
k = tl.load(k_ptr + (page * PAGE_BYTES + row * D)[:, None] + d[None, :]) # [TILE, D] fp8
scale = tl.load(kscale_ptr + page * (PAGE_BYTES // 4) + SCALE_OFFSET // 4 + row)
acc = tl.dot(k, qt, out_dtype=tl.float32) # [TILE, H]
q_s = T.alloc_shared((H, D), T.float8_e4m3fn)
w_s = T.alloc_shared((H,), T.float32)
k_s = T.alloc_shared((TILE, D), T.float8_e4m3fn)
scale_s = T.alloc_shared((TILE,), T.float32)
c_s = T.alloc_shared((TILE, H), T.float32)
acc = T.alloc_shared((TILE,), T.float32)
c_local = T.alloc_fragment((TILE, H), T.float32)
# ...
T.clear(c_local)
T.gemm(k_s, q_s, c_local, transpose_A=False, transpose_B=True)
// tcgen05.alloc is sync.aligned: the whole first warp has to execute it.
tensor_allocator<1, 1, false> tm{};
if (tx < 32) tm.provision(tmem_addr);
__syncthreads();
tm.set_addr(tmem_addr);
tt<float, kTile, kHeads> acc = tm.allocate<tt<float, kTile, kHeads>>(0);
// One thread issues the MMA. mm_ABt clears the accumulator, steps K by 32,
// and commits mma_done when the last step lands.
if (tx == 0) mm_ABt(acc, k_smem, q_smem, mma_done);
wait(mma_done, 0);
// A warpgroup holds the 128x64 accumulator as a 32x64 register tile.
rt_fl<32, kHeads> regs;
warpgroup::load_async(regs, acc);
tensor_load_wait();
warpgroup::sync(warpgroup::groupid() + 1);
warpgroup::store(c_smem, regs);
The product the other tabs issue as a tcgen05 MMA.
# ---- score ------------------------------------------------------------
# q[b]: [H, D]
# K.T: [D, S]
# q[b] @ K.T -> [H, S] raw head scores
# ReLU + per-head weight broadcast:
# weights[b]: [H]
# weights[b][:, None]: [H, 1]
# scores: [H, S]
scores = torch.relu(q[b] @ K.T) * weights[b][:, None] # [H, S]
ReLU, the head weight, and the scale
One logit per token: the scale for that token times the sum over the 64 heads of ReLU(dot) times the head weight. Tokens past the sequence length are left out of the select.
// logit = scale * sum_h ReLU(acc[h]) * weight[h]. Threads past seq_len
// write FP16 -inf so Stage 2's radix select cannot pick the padding.
if (tid < kBlockKv) {
const float* acc = reinterpret_cast<const float*>(regs);
float acc_relu = 0.0f;
#pragma unroll
for (int h = 0; h < kNumHeads; ++h) {
const float r = acc[h] > 0.0f ? acc[h] : 0.0f;
acc_relu = fmaf(r, smem_w[h], acc_relu);
}
const int kv_abs = kv_base + tid;
const float scaled = acc_relu * smem_kscale[tid];
logits_b[kv_abs] = (kv_abs < seq_len) ? __float2half_rn(scaled) : kHalfNegInf;
}
acc = tl.dot(k, qt, out_dtype=tl.float32) # [TILE, H]
logit = tl.sum(tl.maximum(acc, 0.0) * w[None, :], axis=1) * scale
tl.store(logits_ptr + b * row_stride + tok, logit.to(tl.float16),
mask=tok < seq_len)
T.clear(c_local)
T.gemm(k_s, q_s, c_local, transpose_A=False, transpose_B=True)
T.copy(c_local, c_s)
for i, h in T.Parallel(TILE, H):
c_s[i, h] = T.max(c_s[i, h], 0) * w_s[h]
T.reduce_sum(c_s, acc, dim=1)
T.sync_threads()
for i in T.Parallel(TILE):
tok = tile * TILE + i
if tok < seq:
logits[b, tok] = T.cast(acc[i] * scale_s[i], "float16")
// A warpgroup holds the 128x64 accumulator as a 32x64 register tile.
rt_fl<32, kHeads> regs;
warpgroup::load_async(regs, acc);
tensor_load_wait();
warpgroup::sync(warpgroup::groupid() + 1);
warpgroup::store(c_smem, regs);
__syncthreads();
// Thread i owns token i of this tile and reduces the 64 heads.
float sum = 0.f;
#pragma unroll
for (int h = 0; h < kHeads; ++h) sum += fmaxf(c_smem[{tx, h}], 0.f) * w_s[h];
const int tok = tile * kTile + tx;
if (tok < seq) logits[b * row_stride + tok] = __float2half(sum * scale_s[tx]);
ReLU, the head weight, and the sum over heads. The scale is already inside K.
# weights[b]: [H]
# weights[b][:, None]: [H, 1]
# scores: [H, S]
scores = torch.relu(q[b] @ K.T) * weights[b][:, None] # [H, S]
# Sum across heads -> one logit per logical token
# logits: [S]
logits = scores.sum(dim=0)
Radix rounds
FP16 bits are reordered so an unsigned compare matches float order. CUDA and ThunderKittens walk two 8-bit digits, high digit first, and cache the ordered keys in shared memory. Triton and TileLang walk digits of 5, 5, and 6 bits, because that is the histogram shape their compilers lower well.
// fp16 bits reordered so that unsigned integer comparison matches float
// ordering: flip the sign bit for positives, invert everything for negatives.
__device__ __forceinline__ uint16_t HalfToOrderedU16(__half h) {
const uint16_t bits = __half_as_ushort(h);
return (bits & 0x8000u) ? static_cast<uint16_t>(~bits)
: static_cast<uint16_t>(bits ^ 0x8000u);
}
// ...
// Two radix rounds (8 bits each, MSB first) narrow the ordered-uint16
// prefix until exactly top_k keys remain at or above that prefix.
#pragma unroll
for (int round = 0; round < kRadixRounds; ++round) {
const int shift = kOrderedBits - 8 - round * 8;
const uint16_t prefix_mask =
(round == 0) ? uint16_t{0}
: static_cast<uint16_t>(0xFFFFu << (kOrderedBits - round * 8));
for (int i = tid; i < kRadix; i += blockDim.x) smem_hist[i] = 0u;
__syncthreads();
const uint16_t prefix = smem_prefix;
if (round == 0 && use_ordered_cache) {
// prefix_mask == 0 on round 0, so every key is accepted.
for (int i = tid; i < seq_len; i += blockDim.x) {
const uint16_t ordered = HalfToOrderedU16(row_lg[i]);
smem_ordered[i] = ordered;
atomicAdd(&smem_hist[(ordered >> shift) & 0xFFu], 1u);
}
} else if (use_ordered_cache) {
#pragma unroll 4
for (int i = tid; i < cached_len; i += blockDim.x) {
const uint16_t ordered = smem_ordered[i];
if ((uint16_t)(ordered & prefix_mask) == prefix)
atomicAdd(&smem_hist[(ordered >> shift) & 0xFFu], 1u);
}
} else {
#pragma unroll 4
for (int i = tid; i < seq_len; i += blockDim.x) {
const uint16_t ordered = HalfToOrderedU16(row_lg[i]);
if ((uint16_t)(ordered & prefix_mask) == prefix)
atomicAdd(&smem_hist[(ordered >> shift) & 0xFFu], 1u);
}
}
@triton.jit
def _select_digit(digit, mask, need, BINS: tl.constexpr):
"""One radix-select round over the keys under `mask`.
Returns the digit of the need-th largest key and the number of keys whose
digit is larger.
"""
hist = tl.histogram(digit, BINS, mask=mask)
at_or_above = tl.cumsum(hist, 0, reverse=True) # keys with digit >= bin
# Bins [0, d] are exactly the ones that still have `need` keys at or above
# them. One sum gives both answers: how many such bins (high bits) and how
# many keys sit in the bins above d (low bits, always below `need`).
packed = tl.sum(tl.where(at_or_above >= need, 1 << 20, hist), axis=0)
return (packed >> 20) - 1, packed & 0xFFFFF
@triton.jit
def _stage2_topk(logit_bits_ptr, seq_lens_ptr, bt_ptr, out_ptr,
row_stride, max_num_pages, BLOCK: tl.constexpr):
"""Top-2048 of row b's logits as physical slot ids. One program per row.
Radix select on the FP16 bit patterns, then a prefix-sum compaction; BLOCK
is a power of two covering the whole row.
"""
b = tl.program_id(0)
seq_len = tl.load(seq_lens_ptr + b)
row_bt = bt_ptr + b * max_num_pages
row_out = out_ptr + b * TOPK
# Whole row is inside top-K: same transform as the fast path.
if seq_len <= TOPK:
n = tl.arange(0, TOPK)
keep = n < seq_len
page = tl.load(row_bt + n // PAGE, mask=keep, other=0)
tl.store(row_out + n, tl.where(keep, page * PAGE + n % PAGE, -1))
return
i = tl.arange(0, BLOCK)
valid = i < seq_len
bits = tl.load(logit_bits_ptr + b * row_stride + i, mask=valid, other=0)
bits = bits.to(tl.int32) & 0xFFFF
# FP16 bits reordered so integer order matches float order: positives move
# above 0x8000, negatives are mirrored below it. Slots past seq_len get -1,
# below every real key.
key = tl.where(valid, tl.where(bits >= 0x8000, 0xFFFF - bits, bits + 0x8000), -1)
# K-th largest key by radix select, 5 + 5 + 6 bits from the top. Triton
# 3.7 lowers tl.histogram to one warp ballot per bin-index bit per key, so
# three narrow rounds cost less than the two 8-bit rounds of the CUDA
# version. `above` counts the keys strictly beyond the pivot.
d, above = _select_digit(key >> 11, valid, TOPK, 32)
pivot = d << 11
d, more = _select_digit((key >> 6) & 31, (key >> 11) == d, TOPK - above, 32)
above += more
pivot = pivot | (d << 6)
d, more = _select_digit(key & 63, (key >> 6) == (pivot >> 6), TOPK - above, 64)
above += more
pivot = pivot | d
base = tx * elems
for j in T.serial(elems):
idx = base + j
src = T.min(idx, stride - 1)
raw = T.cast(bits[b, src], "int32") & 0xFFFF
# FP16 bits reordered so unsigned order matches float order.
key = T.if_then_else(raw >= 0x8000, 0xFFFF - raw, raw + 0x8000)
keys[idx] = T.if_then_else(idx < seq, key, -1)
if tx == 0:
pivot[0] = 0
above[0] = 0
T.sync_threads()
# 5 + 5 + 6 bits from the top. Same split as the Triton kernel:
# three narrow histograms rather than two 8-bit ones.
rounds = ((11, 31, 11, 32), (6, 31, 6, 32), (0, 63, 0, 64))
for shift, mask, place, nbins in rounds:
T.clear(hist)
T.sync_threads()
for j in T.serial(elems):
k = keys[base + j]
if shift == 11:
pred = k >= 0
digit = k >> 11
elif shift == 6:
pred = (k >> 11) == (pivot[0] >> 11)
digit = (k >> 6) & mask
else:
pred = (k >> 6) == (pivot[0] >> 6)
digit = k & mask
if pred:
T.atomic_add(hist[digit], 1)
T.sync_threads()
if tx == 0:
run[0] = 0
found_digit[0] = 0
found_above[0] = 0
need = TOPK - above[0]
for bin_i in T.serial(nbins):
bin_id = nbins - 1 - bin_i
c = hist[bin_id]
if run[0] < need:
if run[0] + c >= need:
found_digit[0] = bin_id
found_above[0] = run[0]
run[0] = run[0] + c
pivot[0] = pivot[0] | (found_digit[0] << place)
above[0] = above[0] + found_above[0]
T.sync_threads()
__device__ __forceinline__ uint16_t half_to_ordered(const __half* row, int i) {
const uint16_t bits = __half_as_ushort(row[i]);
return (bits & 0x8000u) ? static_cast<uint16_t>(~bits)
: static_cast<uint16_t>(bits ^ 0x8000u);
}
// ...
#pragma unroll
for (int round = 0; round < 2; ++round) {
const int shift = 8 - round * 8;
const uint16_t prefix_mask = (round == 0) ? uint16_t{0}
: static_cast<uint16_t>(0xFFFFu << (16 - round * 8));
for (int i = tx; i < kBins; i += kThreads) hist[i] = 0;
__syncthreads();
const uint16_t cur = prefix;
for (int i = tx; i < seq; i += kThreads) {
uint16_t key;
if (round == 0) {
key = half_to_ordered(row, i);
ordered[i] = key;
} else {
key = ordered[i];
}
if ((uint16_t)(key & prefix_mask) == cur)
atomicAdd(hist + ((key >> shift) & 0xFFu), 1u);
}
torch.topk in place of the radix select.
# ---- top-K over logical tokens ----------------------------------------
# topk_local: [actual_topk] logical ids in [0, S)
actual_topk = min(TOPK, seq_len)
_, topk_local = torch.topk(logits, actual_topk) # values unused
Keep the winners and remap them
Every key strictly above the pivot is taken. Ties at the pivot fill the remaining slots in token order. The stored id is block_table[token / 64] * 64 + token % 64.
// Emit every index strictly above the pivot, then indices equal to it,
// so ties break in a stable scan order. Then rewrite logical token ids
// as physical slots: block_table[tok/64]*64 + tok%64.
const uint16_t pivot = smem_prefix;
if (tid == 0) { smem_gt_count = 0; smem_emit_counter = 0; }
__syncthreads();
auto ordered_at = [&](int i) -> uint16_t {
return use_ordered_cache ? smem_ordered[i]
: HalfToOrderedU16(row_lg[i]);
};
{
int local = 0;
for (int i = tid; i < seq_len; i += blockDim.x)
if (ordered_at(i) > pivot) local++;
#pragma unroll
for (int off = 16; off > 0; off >>= 1)
local += __shfl_xor_sync(0xffffffffu, local, off);
if ((tid & 31) == 0) atomicAdd(&smem_gt_count, local);
}
__syncthreads();
const int gt_total = smem_gt_count;
for (int i = tid; i < seq_len; i += blockDim.x) {
if (ordered_at(i) > pivot) {
const int pos = atomicAdd(&smem_emit_counter, 1);
if (pos < gt_total) row_out[pos] = i;
}
}
__syncthreads();
for (int i = tid; i < seq_len; i += blockDim.x) {
if (ordered_at(i) == pivot) {
const int pos = atomicAdd(&smem_emit_counter, 1);
if (pos < top_k) row_out[pos] = i;
}
}
__syncthreads();
for (int i = tid; i < top_k; i += blockDim.x) {
const int tok = row_out[i];
if (tok >= 0 && tok < seq_len)
row_out[i] = row_bt[tok / kPageSize] * kPageSize + (tok % kPageSize);
else
row_out[i] = -1;
}
# Every key above the pivot is taken; ties at the pivot fill the rest in
# token order. One prefix sum ranks both groups: the low 16 bits count
# keys above the pivot, the high 16 bits count ties.
gt = key > pivot
eq = key == pivot
rank = tl.cumsum(gt.to(tl.int32) + (eq.to(tl.int32) << 16), 0)
pos = tl.where(gt, (rank & 0xFFFF) - 1, above + (rank >> 16) - 1)
take = gt | (eq & (pos < TOPK))
# Logical token id -> physical slot, fused into the emit.
page = tl.load(row_bt + i // PAGE, mask=take, other=0)
tl.store(row_out + pos, page * PAGE + i % PAGE, mask=take)
# Count keys strictly above the pivot, and ties, per thread.
pvt = pivot[0]
partial_gt[tx] = 0
partial_eq[tx] = 0
for j in T.serial(elems):
k = keys[base + j]
if k > pvt:
partial_gt[tx] = partial_gt[tx] + 1
elif k == pvt:
partial_eq[tx] = partial_eq[tx] + 1
count_gt[tx] = partial_gt[tx]
count_eq[tx] = partial_eq[tx]
T.sync_threads()
# Inclusive scan of the per-thread counts. `tmp` is the double buffer.
for step in T.serial(STAGE2_SCAN_STEPS):
offset = 1 << step
for i in T.Parallel(STAGE2_THREADS):
extra = T.if_then_else(i >= offset, partial_gt[i - offset], 0)
tmp[i] = partial_gt[i] + extra
T.sync_threads()
for i in T.Parallel(STAGE2_THREADS):
partial_gt[i] = tmp[i]
T.sync_threads()
for step in T.serial(STAGE2_SCAN_STEPS):
offset = 1 << step
for i in T.Parallel(STAGE2_THREADS):
extra = T.if_then_else(i >= offset, partial_eq[i - offset], 0)
tmp[i] = partial_eq[i] + extra
T.sync_threads()
for i in T.Parallel(STAGE2_THREADS):
partial_eq[i] = tmp[i]
T.sync_threads()
# Exclusive start of this thread's chunk, then a serial emit.
tmp[tx] = partial_gt[tx] - count_gt[tx]
count_gt[tx] = above[0] + (partial_eq[tx] - count_eq[tx])
for j in T.serial(elems):
idx = base + j
k = keys[idx]
if k > pvt:
page = block_table[b, idx // PAGE]
out[b, tmp[tx]] = page * PAGE + idx % PAGE
tmp[tx] = tmp[tx] + 1
elif k == pvt:
if count_gt[tx] < TOPK:
page = block_table[b, idx // PAGE]
out[b, count_gt[tx]] = page * PAGE + idx % PAGE
count_gt[tx] = count_gt[tx] + 1
const uint16_t pivot = prefix;
if (tx == 0) {
gt_count = 0;
emit = 0;
}
__syncthreads();
int local = 0;
for (int i = tx; i < seq; i += kThreads)
local += ordered[i] > pivot;
#pragma unroll
for (int off = 16; off > 0; off >>= 1)
local += __shfl_xor_sync(0xffffffffu, local, off);
if ((tx & 31) == 0) atomicAdd(>_count, local);
__syncthreads();
for (int i = tx; i < seq; i += kThreads) {
if (ordered[i] > pivot) {
const int pos = atomicAdd(&emit, 1);
if (pos < gt_count) row_out[pos] = i;
}
}
__syncthreads();
for (int i = tx; i < seq; i += kThreads) {
if (ordered[i] == pivot) {
const int pos = atomicAdd(&emit, 1);
if (pos < kTopK) row_out[pos] = i;
}
}
__syncthreads();
for (int i = tx; i < kTopK; i += kThreads) {
const int tok = row_out[i];
if (tok >= 0 && tok < seq)
row_out[i] = row_bt[tok / kPage] * kPage + (tok % kPage);
else
row_out[i] = -1;
}
Logical token id to a physical slot: page id times 64, plus the slot.
# ---- logical -> physical ----------------------------------------------
# page_col: [actual_topk] which block-table column (logical page)
# slot: [actual_topk] offset within the page
# physical: [actual_topk] page_id * PS + slot
page_col = topk_local // page_size
slot = topk_local % page_size
physical = page_indices[page_col] * page_size + slot
# Write into the output row; remaining K - actual_topk entries stay -1
topk_indices[b, :actual_topk] = physical.to(torch.int32)
The PyTorch reference, in full
The tabs above are slices of this file. This is the whole module: dequantize the paged cache, score each row, keep the top 2048, and remap them to physical slots. The function at the bottom is the two-row CPU check.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
"""Contest-faithful PyTorch baseline for the DSA FP8 Top-K indexer.
Definition reference from flashinfer-bench
(``dsa_topk_indexer_fp8_h64_d128_topk2048_ps64``), cleaned for reading.
Harness speedups are vs this naive Python path (not FlashInfer/DeepGEMM).
---------------------------------------------------------------------------
Notation used in comments below
---------------------------------------------------------------------------
B = batch_size
H = num_index_heads = 64
D = index_head_dim = 128
PS = page_size = 64
K = topk = 2048
P = num_pages # total pages in the KV pool
M = max_num_pages # block_table width (pages reserved per row)
S = seq_lens[b] # valid logical tokens in row b
Np = ceil(S / PS) # pages touched by row b
---------------------------------------------------------------------------
Math (per batch row b, logical token t < S)
---------------------------------------------------------------------------
page, slot = block_table[b, t // PS], t % PS
S_score[h] = sum_d Q[b,h,d] * K_dequant[page, slot, d] # FP8→FP32
logit[t] = scale[page,slot] * sum_h ReLU(S_score[h]) * weights[b,h]
topk_local = argmax_K(logit[0:S]) # logical ids
topk_phys[j] = block_table[b, j//PS] * PS + (j % PS) # physical ids
# unused slots padded with -1
---------------------------------------------------------------------------
KV cache layout (deep_gemm FP8, one page = 8448 bytes)
---------------------------------------------------------------------------
bytes [0, 8192) : PS * D FP8 values (64 tokens × 128 dims)
bytes [8192, 8448) : PS FP32 scales (one scale per token)
viewed as : [P, PS, 1, 132] int8
---------------------------------------------------------------------------
Tensor dictionary
---------------------------------------------------------------------------
q_index_fp8 [B, H, D] = [B, 64, 128] float8_e4m3fn
k_index_cache_fp8 [P, PS, 1, 132] = [P, 64, 1, 132] int8 (as uint8/FP8)
weights [B, H] = [B, 64] float32
seq_lens [B] int32
block_table [B, M] int32
-> topk_indices [B, K] = [B, 2048] int32
"""
from __future__ import annotations
import torch
H = 64
D = 128
PAGE_SIZE = 64
TOPK = 2048
HEAD_DIM_WITH_SCALE = 132 # D + 4 scale bytes
def dequant_fp8_kv_cache(k_index_cache_fp8: torch.Tensor) -> torch.Tensor:
"""Dequantize deep_gemm FP8 pages to FP32.
Input: k_index_cache_fp8 [P, PS, 1, 132] int8 (byte-identical to uint8)
Output: K_dequant [P, PS, D] float32
(= fp8_value * per-token scale, scale broadcast over D)
"""
# cache_u8: [P, PS, 1, 132] uint8
cache_u8 = k_index_cache_fp8.view(torch.uint8)
num_pages, page_size, _num_heads, head_dim_sf = cache_u8.shape
assert head_dim_sf == HEAD_DIM_WITH_SCALE
head_dim = head_dim_sf - 4 # 128
# Per page the bytes are packed flat: [all FP8 | all scales], NOT
# interleaved as [fp8||scale] per token. Flatten, then split.
# kv_flat: [P, PS*132] = [P, 8448] uint8
kv_flat = cache_u8.view(num_pages, page_size * head_dim_sf)
# FP8 payload: first PS*D bytes per page
# fp8_bytes: [P, PS*D] = [P, 8192] uint8
# fp8: [P, PS, D] float8_e4m3fn
# fp8_f32: [P, PS, D] float32
fp8_bytes = kv_flat[:, : page_size * head_dim].contiguous()
fp8 = fp8_bytes.view(num_pages, page_size, head_dim).view(torch.float8_e4m3fn)
fp8_f32 = fp8.to(torch.float32)
# Scales: last PS*4 bytes per page -> PS float32s
# scale_bytes: [P, PS*4] = [P, 256] uint8
# scale: [P, PS, 1] float32
scale_bytes = kv_flat[:, page_size * head_dim :].contiguous()
scale = scale_bytes.view(torch.float32).view(num_pages, page_size, 1)
# Broadcast multiply: [P, PS, D] * [P, PS, 1] -> [P, PS, D]
return fp8_f32 * scale
@torch.no_grad()
def run(
q_index_fp8: torch.Tensor, # [B, H, D]
k_index_cache_fp8: torch.Tensor, # [P, PS, 1, 132]
weights: torch.Tensor, # [B, H]
seq_lens: torch.Tensor, # [B]
block_table: torch.Tensor, # [B, M]
) -> tuple[torch.Tensor]:
"""Official-style reference: returns ``(topk_indices [B, K],)``."""
# q_index_fp8: [B, H, D]
batch_size, num_heads, head_dim = q_index_fp8.shape
# k_index_cache_fp8: [P, PS, 1, 132]
_num_pages, page_size, _, _ = k_index_cache_fp8.shape
assert num_heads == H and head_dim == D and page_size == PAGE_SIZE
device = q_index_fp8.device
# q: [B, H, D] fp32
# K_all: [P, PS, D] fp32 (dequantized pool; gathered per row below)
q = q_index_fp8.to(torch.float32)
K_all = dequant_fp8_kv_cache(k_index_cache_fp8)
# topk_indices: [B, K] int32, pre-filled with -1 padding
topk_indices = torch.full(
(batch_size, TOPK), -1, dtype=torch.int32, device=device
)
for b in range(batch_size):
# S = number of valid logical tokens in this row
seq_len = int(seq_lens[b].item())
if seq_len == 0:
continue
# Logical tokens [0, S) live in the first Np = ceil(S / PS) pages.
# page_indices: [Np] — physical page ids from the block table
num_pages_for_seq = (seq_len + page_size - 1) // page_size
page_indices = block_table[b, :num_pages_for_seq].to(torch.long) # [Np]
# Gather those pages, flatten tokens, trim to S:
# K_all[page_indices]: [Np, PS, D]
# .reshape(-1, D): [Np*PS, D]
# [:seq_len]: [S, D]
K = K_all[page_indices].reshape(-1, head_dim)[:seq_len] # [S, D]
# ---- score ------------------------------------------------------------
# q[b]: [H, D]
# K.T: [D, S]
# q[b] @ K.T -> [H, S] raw head scores
# ReLU + per-head weight broadcast:
# weights[b]: [H]
# weights[b][:, None]: [H, 1]
# scores: [H, S]
scores = torch.relu(q[b] @ K.T) * weights[b][:, None] # [H, S]
# Sum across heads -> one logit per logical token
# logits: [S]
logits = scores.sum(dim=0)
# ---- top-K over logical tokens ----------------------------------------
# topk_local: [actual_topk] logical ids in [0, S)
actual_topk = min(TOPK, seq_len)
_, topk_local = torch.topk(logits, actual_topk) # values unused
# ---- logical -> physical ----------------------------------------------
# page_col: [actual_topk] which block-table column (logical page)
# slot: [actual_topk] offset within the page
# physical: [actual_topk] page_id * PS + slot
page_col = topk_local // page_size
slot = topk_local % page_size
physical = page_indices[page_col] * page_size + slot
# Write into the output row; remaining K - actual_topk entries stay -1
topk_indices[b, :actual_topk] = physical.to(torch.int32)
# topk_indices: [B, K] int32
return (topk_indices,)
@torch.no_grad()
def kernel(
q_index_fp8: torch.Tensor, # [B, H, D]
k_index_cache_fp8: torch.Tensor, # [P, PS, 1, 132]
weights: torch.Tensor, # [B, H]
seq_lens: torch.Tensor, # [B]
block_table: torch.Tensor, # [B, M]
topk_indices: torch.Tensor, # [B, K] destination
) -> None:
"""Destination-passing wrapper matching ``solution/python/solution.py``."""
out, = run(q_index_fp8, k_index_cache_fp8, weights, seq_lens, block_table)
topk_indices.copy_(out) # [B, K]
def _demo_cpu() -> None:
"""Tiny synthetic example so you can refresh the math without a GPU."""
torch.manual_seed(0)
B, P, max_pages = 2, 8, 4
# seq_lens: [B] — row0 has 100 tokens, row1 has 50
seq_lens = torch.tensor([100, 50], dtype=torch.int32)
# block_table: [B, M]
block_table = torch.arange(B * max_pages, dtype=torch.int32).view(B, max_pages) % P
# q: [B, H, D] float8
q = torch.randn(B, H, D).to(torch.float8_e4m3fn)
# Build a deep_gemm-style cache: per page, FP8 bytes then FP32 scales.
# Resulting cache: [P, PS, 1, 132] int8
pages = []
for _ in range(P):
fp8 = torch.randn(PAGE_SIZE, D).to(torch.float8_e4m3fn).view(torch.uint8) # [PS, D]
scales = torch.ones(PAGE_SIZE, dtype=torch.float32) # [PS]
page = torch.empty(PAGE_SIZE * HEAD_DIM_WITH_SCALE, dtype=torch.uint8) # [8448]
page[: PAGE_SIZE * D] = fp8.reshape(-1) # [8192]
page[PAGE_SIZE * D :] = scales.view(torch.uint8).reshape(-1) # [256]
pages.append(page.view(PAGE_SIZE, 1, HEAD_DIM_WITH_SCALE)) # [PS, 1, 132]
cache = torch.stack(pages, dim=0).view(torch.int8) # [P, PS, 1, 132]
# weights: [B, H]
weights = torch.ones(B, H, dtype=torch.float32)
out, = run(q, cache, weights, seq_lens, block_table) # [B, K]
print("topk_indices shape:", tuple(out.shape))
print("row0 (first 8):", out[0, :8].tolist())
print("row0 padding (-1 count):", int((out[0] < 0).sum()))
print("row1 padding (-1 count):", int((out[1] < 0).sum()))
# seq_len=50 < 2048 => 2048 - 50 = 1998 pads on row1
assert int((out[1] < 0).sum()) == TOPK - 50
print("demo OK")
if __name__ == "__main__":
_demo_cpu()
baselines/pytorch_naive_reference.py, all 225 lines
The operation
For each query in a batch, score every token of a paged FP8 KV cache and return the top 2048 physical indices.
logit[t] = scale[page, slot] * sum_h ReLU(Q[b, h] · K[page, slot]) * w[b, h]
physical id = block_table[b, t / 64] * 64 + (t % 64)
Q is [B, 64, 128] FP8 E4M3. The cache is one byte buffer per page, 8448 bytes: 8192 FP8 values (64 tokens × 128) followed by 64 FP32 scales. The scale multiplies the ReLU'd dot product; it is not folded into the matrix multiply. Unused slots of the 2048-wide output are -1.
One plan, used by all four
The sequence length decides the kernel. max_num_pages is the longest sequence in the batch, in pages of 64 tokens.
| Pages | What runs | Why |
|---|---|---|
| ≤ 32 | Fast path | Every live token is inside the top 2048, so the output is the block-table remap of 0 .. seq_len. Q, K, and the weights are never read. |
| 33–63 | Stage 1, then stage 2 | Short enough that one tile per CTA fills the GPU. |
| ≥ 64 | Stage 1, then stage 2 | Same math. The CUDA version switches to a warp-specialized persistent stage 1 here; the ports keep one tile per CTA. |
Stage 1 scores two pages (128 tokens) per CTA. A Blackwell tcgen05 MMA multiplies the FP8 tile of K by the FP8 tile of Q into FP32 tensor memory. The epilogue applies ReLU, the per-head weight, a sum over the 64 heads, and the per-token scale, and writes an FP16 logit.
Stage 2 keeps the 2048 largest logits and remaps them through the block table. Rows at or under 2048 tokens skip the select and write the block-table ids directly.
Where the code is
| Version | Entry | Size | Contest image |
|---|---|---|---|
| CUDA | solution/python, solution.py::kernel | 13 files, 1,246 lines | This is what config.toml submits. |
| Triton | solution/triton/solution.py | 321 lines | Triton 3.7.0 is in the image. 3.9.0 was installed for the second run. |
| TileLang | solution/tilelang/solution.py | 384 lines | TileLang is built by flashinfer-bench. These numbers are from 0.1.15. |
| ThunderKittens | solution/tk/indexer.cu and solution.py | 373 + 48 lines | The headers are not in the contest image. |
| PyTorch | baselines/pytorch_naive_reference.py | 225 lines | The reference. It runs on CPU; it is not a contest submission. |
Every kernel(...) has the same six arguments: Q, the KV cache, the weights, the sequence lengths, the block table, and the output index buffer.
Run them
CUDA, the contest harness
modal run scripts/run_modal.py
This builds solution/python the way the contest does and prints a latency per workload. The Triton comparison uses the same harness for both languages:
modal run scripts/run_modal_triton_vs_cuda.py
Per-workload means, the three plans, and the Triton 3.7 versus 3.9 split are in the Triton report.
PyTorch, the reference
python baselines/pytorch_naive_reference.py
That runs a two-row CPU check of baselines/pytorch_naive_reference.py. The full listing is above, with the same six arguments as the other four. The per-token scale is multiplied into K before the dot. A non-negative scale makes that equal to scaling the ReLU'd dot afterwards, which is what the kernels do.
TileLang
Import solution.tilelang.solution and call kernel. The fast path and the stage-1-plus-stage-2 path are both captured in a CUDA graph, keyed on the tensor pointers, so a replay is two graph launches. T.gemm lowers to the same tcgen05 MMA. The gather is the part that stays in scalar code: a 16-byte load comes back as a vector the frontend cannot index, and a raw shared store of that vector would skip the swizzle the MMA reads, so each token is four 4-byte loads stored one FP8 value at a time.
ThunderKittens
Import solution.tk.solution and call kernel. The loader JIT-compiles indexer.cu with -DKITTENS_SM100, TORCH_CUDA_ARCH_LIST=10.0a, and include paths /opt/ThunderKittens/include and /opt/ThunderKittens/prototype. Clone ThunderKittens there first. Stage 1 is kittens::mm_ABt: one warp provisions tensor memory, one thread issues the MMA, and the CTA reduces the 64 heads. The paged gather is a 16-byte load stored at idx ^ ((idx >> 3) & 7), which is the swizzle the TK descriptor reads. Stage 2 is the CUDA select: 1024 threads, two 8-bit radix passes, an ordered-key cache of 16384 logits.
The contest numbers
Mean latency over the 128 workloads. CUDA and Triton 3.7.0 ran together. Triton 3.9.0 is the same source on a newer compiler, measured against a CUDA mean of 8.06 µs in that run.
| Plan | Workloads | CUDA | Triton 3.7 | Triton 3.9 |
|---|---|---|---|---|
| Fast path, ≤ 32 pages | 69 | 2.44 µs | 1.98 µs | 2.02 µs |
| Short, 33–63 pages | 39 | 12.87 µs | 12.36 µs | 10.10 µs |
| Persistent, ≥ 64 pages | 20 | 17.68 µs | 21.41 µs | 16.72 µs |
| All 128 | 128 | 8.00 µs | 8.18 µs | 6.78 µs |
On the contest compiler the two languages trade places by plan: Triton is ahead on the fast path and on short sequences, CUDA is ahead once the sequence is long enough for the persistent stage 1. Triton 3.9 is ahead on all 128. The change is the lowering of tl.histogram, which is the whole stage-2 digit count. The source did not change between 3.7 and 3.9.
TileLang and ThunderKittens, on five shapes
These two were timed with CUDA events around ten calls after three warmup calls. There is no L2 flush, and the clock stays running across the gap between stage 1 and stage 2, so a number here is larger than the CUPTI span of the same kernels. The CUDA and Triton columns are the nearest contest workload, copied from the 128-workload table, so the comparison is the right shape at the official timer.
| Shape | CUDA | Triton 3.7 | ThunderKittens | TileLang |
|---|---|---|---|---|
| Fast, batch 2, 8 pages | 2.39 µs | 1.91 µs | 3.4 µs | 15.4 µs |
| Short, batch 2, 40 pages | — | — | 12.3 µs | 30.5 µs |
| Short, batch 16, ~40–48 pages | 12.5–13.3 µs | 12.2–12.3 µs | 17.5 µs | 28.5 µs |
| Long, batch 2, 80 pages | — | — | 13.5 µs | 32.1 µs |
| Long, batch 16, ~90–96 pages | ~17.9 µs | ~21.5 µs | 24.4 µs | 44.0 µs |
Both ports passed a score check on all five shapes. Short rows matched the physical ids exactly, including the -1 padding. Long rows kept 2048 unique in-range ids, and the gap between the true 2048th score and the worst selected score stayed within 0.016 absolute.
What the gap is made of
On the fast path every version does the same block-table remap. A few microseconds there is the launch, and the TileLang fast-path smoke (15.4 µs) is that overhead on a two-kernel graph, not the remap itself. The scoring rows are where the implementations diverge.
ThunderKittens is the closer of the two ports. The MMA and the select match the CUDA kernel: 16-byte swizzled stores, one mm_ABt per two pages, and the 1024-thread 8-bit radix. The remaining gap on batch 16 (17.5 µs against a 13 µs contest row, 24.4 µs against 18 µs) is the epilogue, which round-trips the accumulator through shared memory before the head reduction, and the event timer, which counts the gap between the two launches. This port does not capture a CUDA graph.
TileLang pays for the gather and for a smaller stage 2. Four-byte loads plus scalar shared stores move the KV tile much more slowly than the 16-byte swizzled store, and the select is a 512-thread 5+5+6 radix whose histograms and scans live in shared memory. That is why 28.5 µs and 44.0 µs sit well above the other three on the same shapes. The first draft was several times slower still: a shared atomic per head, a K-dimension split into four MMA steps, and a persistent loop that left most of the GPU idle. One tile per CTA, one GEMM, and a warp reduction removed that.
Triton 3.9 is the fastest of the four on the contest harness. The source is the same plan, and the compiler version is the difference: 3.7 is 8.18 µs mean, 3.9 is 6.78 µs, with the gain concentrated in stage 2.
What to ship
config.toml keeps pointing at solution/python. That is the kernel the contest image builds, and it is the one measured by the official harness at 8.00 µs. Triton 3.9 is faster on that harness, and the contest image ships Triton 3.7, where the two are even. TileLang and ThunderKittens are in the tree so the same plan can be read and timed in each language; on these measurements they trail the CUDA and Triton kernels on every scoring shape.