Triton vs CUDA: the DSA FP8 top-K indexer on B200
The same kernel, written once in hand-tuned CUDA with inline PTX and once in Triton, benchmarked side by side on the 128 contest workloads. TileLang and ThunderKittens ports of the same plan are compared in four ways to write this kernel.
- Both implementations pass all 128 workloads in flashinfer-bench.
- On the contest image, Triton is faster on the fast path (1.98 vs 2.44 µs) and on mid-size contexts (12.36 vs 12.87 µs), and slower on long contexts (21.41 vs 17.68 µs).
- With Triton 3.9.0 the same source is faster than CUDA on every one of the 128 workloads. The whole change is in how the compiler lowers
tl.histogram, which the top-K selection is built on. - Per-kernel traces point at three places where the CUDA version can still improve: its fast path, its scoring kernel at large batch, and its top-K selection kernel.
What was compared
The kernel is the indexer of DeepSeek sparse attention. For every row b of a batch and every token t of its paged context it computes
logit[t] = scale[page, slot] * sum_h ReLU(Q[b, h] . K[page, slot]) * w[b, h]
with 64 heads of dimension 128 in FP8 (E4M3), and returns the physical cache slots of the 2,048 largest logits. Both implementations use the same plan:
- Fast path (context of at most 32 pages, 69 workloads). The context fits in top-K, so the answer is the block-table transform of
[0, seq_len). One kernel, and Q, K and the weights are never read. - Short (33 to 45 pages, batch 4 to 31, 39 workloads) and persistent (82 to 91 pages, batch 12 to 30, 20 workloads). Stage 1 scores every token on the FP8 tensor cores and writes FP16 logits. Stage 2 radix-selects the top 2,048 and maps them to physical slots. The two launches replay as one CUDA graph.
Sources: solution/python (CUDA, the contest submission) and
solution/triton/solution.py.
Measurement
- Benchmark. flashinfer-bench at the contest settings: 3 warmup calls, 100 timed calls, 5 trials per workload. Time is taken from CUPTI activity records as first kernel start to last kernel end, with the L2 cache flushed before every call. Host time before the first kernel is excluded; any gap between the two kernels counts.
- Two runs. Each run benchmarks both solutions on the same B200 worker. Run A uses the contest image as is (Triton 3.7.0). Run B adds
pip install triton==3.9.0and changes nothing else. CUDA is the control in both; its plan means differ by at most 1.5% between the runs. - Kernel traces. A second pass records the GPU time of each kernel separately (50 calls per workload, medians). It is used for the split between Stage 1 and Stage 2.
- Software. CUDA 13.2, torch 2.12.0.dev20260408+cu132, flashinfer-bench and FlashInfer as cloned from their main branches when the image was built.
- Code size. Line counts exclude blank lines, comments and docstrings.
Results
- Fast path. Triton is faster on all 69 workloads in both runs, by 0.46 µs on average.
- Short, Triton 3.7.0. Triton stays between 11.8 and 13.0 µs at every batch size. CUDA ranges from 10.9 to 16.5 µs and grows with the batch. CUDA wins all 14 workloads with batch up to 8 (11.35 vs 12.20 µs), Triton wins all 10 with batch 29 to 31 (12.63 vs 15.50 µs), and the 15 in between are close (12.32 vs 12.54 µs).
- Persistent, Triton 3.7.0. Triton is slower on all 20 workloads, by 3.3 to 4.2 µs.
- Triton 3.9.0. Faster than CUDA on all 128 workloads: by 3.0 µs on average in the short plan and by 0.85 µs in the persistent plan.
All 128 workloads
Where the time goes
- Graph replay works the same in both. Stage 2 starts 0.2 µs after Stage 1 ends, whether the graph comes from the CUDA runtime API or from
torch.cuda.CUDAGraph. - Stage 1 is close. The compiler-generated tensor-core code is 0.75 µs slower than the hand-written one at small batch and 0.7 µs slower on long contexts. At batch 29 to 31 in the short plan it is 2.8 µs faster, because the CUDA kernel's time grows with the batch and Triton's barely moves.
- Stage 2 decides the outcome. On Triton 3.7.0 it costs 7.1 µs for short rows, slightly less than the CUDA kernel, and 12.3 µs for long rows, 2.2 µs more. On Triton 3.9.0 it drops to 5.3 and 8.0 µs, 2.0 to 2.4 µs less than the CUDA kernel.
Same techniques, two spellings
| Technique | CUDA | Triton |
|---|---|---|
| Fast path | topk_fast_path_kernel: 128 threads, block table staged in shared memory, vectorised int4 stores. |
_fast_path: one broadcast [32, 64] expression and a single tl.store. |
| FP8 tensor-core scoring | Hand-written PTX wrappers for tcgen05.mma (kind::f8f6f4), instruction and shared-memory descriptors, 128-byte swizzled operand layout. 275 lines in tcgen05_ptx.h and umma_desc.h. |
tl.dot(k, qt, out_dtype=tl.float32) on float8_e4m3fn tensors. The compiler emits the same tcgen05.mma with a TMEM accumulator. |
| TMEM accumulator | Explicit allocation, mbarrier wait on the MMA commit, tcgen05.ld of 64 columns into registers, deallocation. |
Implicit in tl.dot and the ReLU/weight reduction that follows. |
| K pipeline | Persistent kernel: producer warps stream K into a triple-buffered cp.async ring, handed to the MMA warp through mbarriers. |
tl.range(first, last, num_stages=3). The compiler emits cp.async.cg prefetch for the block-table-indirect K loads. |
| Dispatch by context size | Short kernel: one page per MMA, one CTA per page. Persistent kernel: two pages per MMA, each CTA loops over tiles. | One kernel, same thresholds. Two pages per MMA everywhere; a program scores one tile below 64 pages and a loop of tiles above. |
| Skipping work | Rows that fit in top-K are skipped in Stage 1. Padding past seq_len is written as FP16 −inf. |
Same row skip. Tiles past seq_len are skipped and nothing is written for padding, because Stage 2 masks by seq_len. |
| FP16 logits | Yes. | Yes. The evaluator's 1e-2 tolerance covers the rounding. |
| Radix select | Two rounds of 8 bits. One atomicAdd into a shared-memory histogram per key, 1,024 threads, ordered keys cached in shared memory. |
Three rounds of 5, 5 and 6 bits through tl.histogram, 512 threads for rows up to 4,096 tokens and 1,024 above. |
| Emitting the result | Three passes over the row with a shared atomic counter (keys above the pivot, ties, then the block-table rewrite). | One tl.cumsum ranks both groups; one masked scatter store writes physical slots directly. The output order is deterministic. |
| Two launches as one | CUDA graph cached per stream and shape; cudaGraphExecUpdate retargets the pointers on each call. |
torch.cuda.CUDAGraph cached per tensor addresses and shape, since torch cannot retarget a captured graph. |
Scoring one tile
CUDA, stage1_short.cuh (abridged)
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);
dsa_ptx::mbarrier_wait_parity(
dsa_ptx::smem_ptr_to_uint(&smem_mbar), 0u);
dsa_ptx::tcgen05_fence_after_thread_sync();
uint32_t regs[kUMMA_N];
dsa_ptx::tcgen05_ld_32x32b_x64_b32(tmem_addr, regs);
dsa_ptx::tcgen05_wait_ld();
// ...
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 float scaled = acc_relu * smem_kscale[tid];
logits_b[kv_abs] = (kv_abs < seq_len)
? __float2half_rn(scaled) : kHalfNegInf;Triton, solution.py (reflowed)
for t in tl.range(first, last, num_stages=STAGES):
tok = t * TILE + m
slot = tl.minimum(tok // PAGE, last_page)
page = tl.load(bt_ptr + b * max_num_pages + slot)
page = page.to(tl.int64)
row = tok % PAGE
# k: [TILE, D] fp8
k = tl.load(k_ptr
+ (page * PAGE_BYTES + row * D)[:, None]
+ d[None, :])
scale = tl.load(kscale_ptr + page * (PAGE_BYTES // 4)
+ SCALE_OFFSET // 4 + row)
# acc: [TILE, H] f32, one FP8 MMA
acc = tl.dot(k, qt, out_dtype=tl.float32)
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)One radix-select round
CUDA, stage2_topk.cuh (abridged)
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);
}
__syncthreads();
if (tid < kRadix) smem_suffix[tid] = smem_hist[tid];
__syncthreads();
for (int stride = 1; stride < kRadix; stride <<= 1) {
uint32_t v = 0u;
if (tid < kRadix) {
v = smem_suffix[tid];
if (tid + stride < kRadix)
v += smem_suffix[tid + stride];
}
__syncthreads();
if (tid < kRadix) smem_suffix[tid] = v;
__syncthreads();
}
// ...
if (tid < kRadix) {
const uint32_t cge = smem_suffix[tid];
const uint32_t cgt =
(tid + 1 < kRadix) ? smem_suffix[tid + 1] : 0u;
if (cge >= smem_remaining && cgt < smem_remaining) {
smem_found_bucket = (uint32_t)tid;
smem_found_remaining = smem_remaining - cgt;
}
}Triton, solution.py (reflowed)
@triton.jit
def _select_digit(digit, mask, need,
BINS: tl.constexpr):
hist = tl.histogram(digit, BINS, mask=mask)
at_or_above = tl.cumsum(hist, 0, reverse=True)
# 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).
packed = tl.sum(
tl.where(at_or_above >= need, 1 << 20, hist),
axis=0)
return (packed >> 20) - 1, packed & 0xFFFFFStage 2 and the Triton version
Top-K selection needs a histogram of key digits, and the usual way to build one on a GPU is one shared-memory atomic add per key. Triton has no shared-memory atomics in the language. The closest construct is tl.histogram, and the two releases compile it differently.
- Triton 3.7.0 uses warp ballots. For every group of 32 keys it issues one ballot per bit of the bin index, then each thread population-counts the ballots for the bins it owns, and the per-thread counts are merged with one atomic per owned bin (source). The cost grows with the number of bins as well as the number of keys. The compiled Stage 2 contains 4 atomic instructions.
- Triton 3.9.0 uses one shared-memory atomic add per key, the same approach as the CUDA kernel, and keeps ballots only for histograms of at most two bins (source, condition). The compiled Stage 2 contains 24 atomic instructions: 8 keys per thread in each of the 3 rounds.
Several selection designs were measured in isolation before choosing one. The table gives the time of the whole Stage 2 kernel in µs on synthetic inputs at batch 16, for the best of 8, 16 and 32 warps.
| Selection design | Triton 3.7.0 | Triton 3.9.0 | ||
|---|---|---|---|---|
| 4,096 tokens | 8,192 tokens | 4,096 tokens | 8,192 tokens | |
| Histogram, 8 + 8 bits (the CUDA design) | 9.7 | 15.7 | 5.6 | 8.1 |
| Histogram, 5 + 5 + 6 bits (shipped) | 8.0 | 12.9 | 5.9 | 8.5 |
| Bisection, 16 counting passes | 8.5 | 11.2 | 7.0 | 10.5 |
| 64-bin histogram, then 10 bisection passes | 8.5 | 12.4 | 6.7 | 10.0 |
| 4-way search, 8 passes | 8.9 | 12.2 | 8.0 | 11.9 |
Of the roughly 8 µs at 4,096 tokens on Triton 3.7.0, about 1.9 µs is the cost of launching a kernel at all, 0.7 µs loads the row and builds the keys, 1.7 µs ranks and writes the result, and the rest is selection.
One design is shipped for both compiler versions. Two measured gains are therefore left unused: on 3.7.0, bisection is about 1.7 µs faster for 8,192-token rows, and on 3.9.0 the 8 + 8 split is about 0.3 µs faster.
What the port says about the CUDA version
The Triton version was written to answer one question, and it ended up measuring the CUDA version from the outside. Three differences stand out. None has been applied to the CUDA code yet.
- Fast path: 0.46 µs. Triton's kernel is faster on all 69 fast-path workloads, 54% of the set. Matching it would lower the overall mean by about 0.25 µs.
- Short-plan scoring at large batch: 2.8 µs. At batch 29 to 31 the CUDA Stage 1 takes 8.15 µs against 5.33 µs for Triton. The CUDA short kernel launches one CTA per page, 1,320 CTAs at batch 30 with 44 pages; Triton scores two pages per MMA and launches 660 programs. Whether the CTA count is the cause has not been tested. Ten workloads are affected.
- Top-K selection: about 2 µs. With the 3.9.0 histogram, Triton's Stage 2 takes 5.3 and 8.0 µs against 7.7 and 9.9 µs for the CUDA kernel in the same trace, although both now count keys with per-key shared-memory atomics. The designs differ in three ways: three narrow rounds over 32 and 64 bins instead of two rounds over 256, one prefix sum and one scatter instead of three passes over a shared atomic counter, and half the threads for short rows. Which of these carries the gain has not been tested. All 59 two-stage workloads are affected.
Taking the better of the two implementations for each kernel in the run B trace gives a mean of 6.7 µs against 8.3 µs for CUDA in that trace. That is an upper estimate of what the CUDA version could gain, and it carries the trace caveat below.
Limits and caveats
- Triton 3.9.0 is outside the contest image. Run B shows what the compiler change is worth. It says nothing about which Triton an official evaluation would use, so the CUDA version remains the submission.
- Traces and benchmark disagree slightly. The trace tool does its own L2 flush and runs both solutions in one process. Its CUDA totals are 0.3 to 0.8 µs above the benchmark on the two-stage plans, while Triton's agree within 0.3 µs. The reason is unknown. Totals in this report come from the benchmark; the traces are used for the split between kernels.
- Graph cache keyed on addresses. The Triton version replays its graph only when a call passes the same tensors as an earlier one, which the benchmark does within a trial. A caller that passes new tensors every time would get two direct launches with host time between them.
- Row length. Triton's Stage 2 holds a row in one block of up to 16,384 tokens (256 pages). Longer rows fall back to
torch.topk. The contest maximum is 91 pages. - Compilation. Triton compiles each specialisation on first use, which the warmup calls absorb. The CUDA version compiles once when the solution is built.
- Run-to-run variation. The CUDA control moved by up to 1.5% in plan means between the two runs, on different B200 workers.
Reproducing
# Benchmark both solutions on Modal B200 (about 20 minutes)
modal run scripts/run_modal_triton_vs_cuda.py
# Same with Triton 3.9.0
DSA_TRITON_VERSION=3.9.0 modal run scripts/run_modal_triton_vs_cuda.py
# Per-kernel GPU time
modal run scripts/run_modal_triton_vs_cuda.py --kernels --iterations 50
# Short checks
modal run scripts/run_modal_triton_vs_cuda.py --smoke
modal run scripts/run_modal_triton_vs_cuda.py --quick
The numbers behind every chart and table on this page are in data.js.