DSA sparse attention, CUDA vs Triton

Four ways to write the same sparse attention kernel

One operation, four implementations, one B200. CUDA is the contest submission. Triton is the fused kernel from the comparison page. TileLang and ThunderKittens follow the same plan and were tuned on these 23 workloads. The listings are the source that was timed.

November 20, 2026 · NVIDIA B200 on Modal · definition dsa_sparse_attention_h16_ckv512_kpe64_topk2048_ps64 · repository

Triton 3.7.0, fused
7.88 µs
geomean · 0.37× CUDA · faster on 22 of 23
CUDA, the submission
21.1 µs
geomean · mean 31.4 µs
ThunderKittens
76.3 µs
geomean · 3.6× CUDA · one kernel
TileLang 0.1.15
95.9 µs
geomean · 4.5× CUDA · kernel time 39.6 µs

All four numbers are the same timer: the CUPTI span from the first kernel's start to the last kernel's end, L2 flushed, median of 10 calls after 3 warm-ups. Host time before the first launch is excluded. Time between launches is included, which is why the TileLang card is higher than the time its kernels actually spend running. Every version passes all 23 contest workloads. The largest absolute error against an fp32 reference is 0.010, which is bf16 rounding. A separate stress run of 18 synthetic calls, with the padding either at the tail or scattered and with up to 20 tokens, stays within 0.005.

The operation

For each of T tokens, 16 query heads, and up to 2,048 sparse key positions:

score = (q_nope · ckv + q_pe · kpe) · sm_scale
p     = softmax(score)          # computed in base 2
out   = p · ckv                 # the 512-d latent, not a separate value tensor
lse   = m + log2(l)             # base-2 log-sum-exp, −∞ when the row is empty

q_nope is [T, 16, 512] bf16, q_pe is [T, 16, 64], the caches are paged [pages, 64, dim], and sparse_indices is [T, 2048] int32 with −1 for padding. Padding may sit anywhere in the row. sm_scale is 0.1352337788608801. The kernels multiply by sm_scale · log2(e) once and stay in base 2 from there.

One plan, used by all four

A short token is scored by one program that walks the valid keys. A long token is split into G key-groups. Each group keeps a full 512-wide partial, because the program that merges column c has to read column c from every group. A group that only stored its own columns would have nothing to merge. G is 16 while T · 16 fits on the B200's 148 SMs, and smaller after that, so the programs that meet at the barrier are all resident.

StepCUDATritonThunderKittensTileLang
Scorewmmatl.dotmm_ABtT.gemm
Gathercp.async, 16 bytesmasked loads in the pipelined tileuint4 into the swizzled tileelement gather into shared
Softmaxper warp, base 2online, inside the tile looponline, across key tilesonline, across key tiles
Outputwmma of p · Vtl.dot, reusing the loaded Kmm_AB of padded probs · Vone T.gemm over all 512 columns
Mergea second kernelsame launch, a counter barriersame launch, atomicAdd plus a spina second kernel, both replayed from one CUDA graph

The same pieces, side by side

Each step is below. Pick a language and every step follows. First place is Doğaç Eldenk's winning Triton kernel, timed on the same 23 workloads. PyTorch is the fp32 reference the kernels are checked against. A line that says ... is a cut between two regions of the same file.

Which path runs

A short token is scored by one program and never publishes a partial. A long token is split across key-groups. CUDA chooses from the token count: eight or more tokens take the per-token kernel. The other three choose from how many programs fit on the GPU at once. Triton also looks at where the last valid index sits. First place looks only at the token count: two tokens or fewer never split the keys, and three or more always do. PyTorch does not split at all. One host loop gathers the valid keys and runs one softmax over the row.

  if (H == CPT_H && T >= 8) {
    path = 1;
    G_cpt = static_cast<uint8_t>(pick_split_G_cta_per_t(static_cast<int>(T)));
  }

solution/python/kernel.cu, lines 645–648

    pos = tl.arange(0, TOPK)
    scan = tl.load(row + pos)
    last = tl.max(tl.where((scan >= 0) & (scan < n_kv), pos, -1), axis=0)

    if last >= THRESH:
...
    else:
        # Names differ from the split branch: Triton merges same-named values
        # across the arms of a branch and their shapes are not the same.
        d_m, d_l, d_acc = _span(
            q, qp, ckv, kpe, row, last + 1, n_kv, sm_log2e, stride_ck, stride_kp, slot * W, m0, l0,
            H=H, D=D, D_PE=D_PE, W=W, STEP=1, B0=B0, B1=B1, B2=B2,
        )
        d_inv = tl.where(d_l > 0, 1.0 / d_l, 0.0)
        tl.store(out_ptr, (d_acc * d_inv[:, None]).to(tl.bfloat16))
        if slot == 0:
            tl.store(lse_ptr, tl.where(d_l > 0, d_m + tl.log2(tl.where(d_l > 0, d_l, 1.0)), float("-inf")))

solution/triton/kernel.py, lines 549–553 and 601–611

    def launch():
        partial(q_nope, q_pe, ckv, kpe, indices, part_m, part_l, part_acc, scale)
        merge(part_m, part_l, part_acc, out, lse)

    if not graph:
        launch()
        return
    key = (
        q_nope.data_ptr(), q_pe.data_ptr(), ckv.data_ptr(), kpe.data_ptr(),
        indices.data_ptr(), out.data_ptr(), lse.data_ptr(),
        n_tokens, ckv.shape[0], g, block, float(scale[0]),
    )
    _replay(key, q_nope.device, launch)

solution/tilelang/solution.py, lines 269–281

    int n_sm = 1;
    cudaDeviceGetAttribute(&n_sm, cudaDevAttrMultiProcessorCount, q_nope.get_device());
    int g = 16;
    while (g > 1 && n_tokens * g > n_sm) g >>= 1;
    if (g < 8) g = 1;
...
    if (g == 16) go(launch_g<16>);
    else if (g == 8) go(launch_g<8>);
    else go(launch_g<1>);

solution/tk/attention.cu, lines 483–487 and 505–507

# program_id(1) is reused as both split index (phase 1) and D-slice index
# (phase 2), so NUM_SPLITS also sets the combine-phase D tiling.
NUM_SPLITS = 16
...
    if num_tokens <= 2:
        _small_t_kernel[(num_tokens, NUM_SPLITS)](
            q_nope, q_pe,
            ckv_flat, kpe_flat,
            sparse_indices,
            output, lse,
            sm_scale * LOG2E,
            q_nope.stride(0), q_nope.stride(1),
            q_pe.stride(0), q_pe.stride(1),
            ckv_flat.stride(0),
            kpe_flat.stride(0),
            sparse_indices.stride(0),
            output.stride(0), output.stride(1),
            lse.stride(0),
            TOPK=TOPK, H=num_heads, D_CKV=D_ckv, D_KPE=D_kpe,
            BLOCK_N=64, BLOCK_D=BLOCK_D,
            num_warps=4, num_stages=2,
        )
        return
...
    _fused_split_combine_kernel[(num_tokens, NUM_SPLITS)](
        q_nope, q_pe,
        ckv_flat, kpe_flat,
        sparse_indices,
        partial_m, partial_l, partial_acc,
        counter,
        output, lse,
        sm_scale * LOG2E,
        q_nope.stride(0), q_nope.stride(1),
        q_pe.stride(0), q_pe.stride(1),
        ckv_flat.stride(0),
        kpe_flat.stride(0),
        sparse_indices.stride(0),
        partial_m.stride(0), partial_m.stride(1), partial_m.stride(2),
        partial_l.stride(0), partial_l.stride(1), partial_l.stride(2),
        partial_acc.stride(0), partial_acc.stride(1), partial_acc.stride(2), partial_acc.stride(3),
        output.stride(0), output.stride(1),
        lse.stride(0),
        target_count,
        TOPK=TOPK, H=num_heads, D_CKV=D_ckv, D_KPE=D_kpe,
        BLOCK_N=128, NUM_SPLITS=NUM_SPLITS, BLOCK_D=BLOCK_D,
        num_warps=4, num_stages=2,

Doğaç Eldenk, contest first place, sparse_fused.py, lines 312–314 and 332–350 and 356–377. Shown for comparison; it is not part of this repository.

def reference(q_nope, q_pe, ckv_cache, kpe_cache, sparse_indices, sm_scale):
    """fp32 PyTorch form of the definition's reference loop."""
    n_tokens, n_heads, dim = q_nope.shape
    ckv = ckv_cache.reshape(-1, dim)
    kpe = kpe_cache.reshape(-1, kpe_cache.shape[-1])
    out = torch.zeros((n_tokens, n_heads, dim), dtype=torch.float32, device=q_nope.device)
    lse = torch.full((n_tokens, n_heads), float("-inf"), dtype=torch.float32, device=q_nope.device)
    for t in range(n_tokens):
        idx = sparse_indices[t]
        idx = idx[idx != -1].long()
        if idx.numel() == 0:
            continue
        kc = ckv[idx].float()
        kp = kpe[idx].float()
        score = (q_nope[t].float() @ kc.T + q_pe[t].float() @ kp.T) * float(sm_scale)
        lse[t] = torch.logsumexp(score, dim=-1) / math.log(2.0)
        out[t] = torch.softmax(score, dim=-1) @ kc
    return out, lse

scripts/triton_profile_worker.py, lines 110–127. The fp32 reference. One host loop, no split and no barrier.

Gather the sparse keys

Each program loads the keys named by its slice of the index row. CUDA issues 16-byte cp.async copies. Triton masked-loads inside the tile loop, which is where Triton pipelines. ThunderKittens stores uint4 into the swizzled shared tile. TileLang copies one element at a time: a 16-byte load comes back as a vector this frontend cannot index.

    #pragma unroll
    for (int c = 0; c < TILE_CHUNKS_PT; ++c) {
      const int chunk = tid + c * TH;
      const int r = chunk / (D_CK / 8);
      const int ch16 = chunk % (D_CK / 8);
      const int k = k0 + r;
      const int g_idx = s_gidx[k];
      uint4* dst = reinterpret_cast<uint4*>(ckv_buf + r * D_CK) + ch16;
      if (g_idx >= 0) {
        const uint4* src =
            reinterpret_cast<const uint4*>(ckv_flat + static_cast<int64_t>(g_idx) * D_CK) + ch16;
        cp_async_16(__cvta_generic_to_shared(dst), src);
      } else {
        const uint4 zero = {0u, 0u, 0u, 0u};
        *dst = zero;
      }

solution/python/mla_cta.cuh, lines 196–211

    valid = (idx >= 0) & (idx < n_kv)
    rows = tl.where(valid, idx, 0).to(tl.int64)
    k = tl.load(
        ckv + rows[:, None] * stride_ck + tl.arange(0, D)[None, :],
        mask=valid[:, None], other=0.0,
    )
    kp = tl.load(
        kpe + rows[:, None] * stride_kp + tl.arange(0, D_PE)[None, :],
        mask=valid[:, None], other=0.0,
    )
    score = tl.dot(q, tl.trans(k))
    score = tl.dot(qp, tl.trans(kp), acc=score)
    score = tl.where(valid[None, :], score * sm_log2e, float("-inf"))

solution/triton/kernel.py, lines 410–422

            for tile in TL.serial(ntiles):
                for i in TL.Parallel(block):
                    pos = slot + (tile * block + i) * g
                    got = indices[token, pos]
                    ok = (got >= 0) and (got < n_kv)
                    idx_s[i] = TL.if_then_else(ok, got, 0)
                    valid_s[i] = TL.if_then_else(ok, 1, 0)
                if TL.get_thread_binding() == 0:
                    cnt[0] = 0
                TL.sync_threads()
                for i in TL.Parallel(block):
                    if valid_s[i] == 1:
                        TL.atomic_add(cnt[0], 1)
                for i, d in TL.Parallel(block, D):
                    k_s[i, d] = TL.if_then_else(valid_s[i] == 1, ckv[idx_s[i], d], TL.cast(0, "bfloat16"))
                for i, d in TL.Parallel(block, D_PE):
                    kp_s[i, d] = TL.if_then_else(valid_s[i] == 1, kpe[idx_s[i], d], TL.cast(0, "bfloat16"))

solution/tilelang/solution.py, lines 86–102

    for (int s = 0; s < kSubs; ++s) {
        for (int v = threadIdx.x; v < kVecs; v += kThreads) {
            const int row = v >> 3;
            const int vec = v & 7;
            uint4 bits = make_uint4(0, 0, 0, 0);
            if (row < row_limit) {
                const int src_col = col + s * kChunk + vec * 8;
                if (gather) {
                    const int id = idx[row];
                    if (id >= 0) {
                        const __nv_bfloat16* src =
                            cache + static_cast<long long>(id) * stride + src_col;
                        bits = *reinterpret_cast<const uint4*>(src);
                    }
                } else {
                    const __nv_bfloat16* src =
                        cache + static_cast<long long>(row) * stride + src_col;
                    bits = *reinterpret_cast<const uint4*>(src);
                }
            }
            out[s * kVecs + swizzle_16b(v)] = bits;
        }

solution/tk/attention.cu, lines 85–106

    offs_split = s + tl.arange(0, SPLIT_SIZE) * NUM_SPLITS
    idx_scan = tl.load(Indices_ptr + t * stride_idx_t + offs_split)
    num_valid = tl.sum((idx_scan >= 0).to(tl.int32), axis=0)
    max_bn = ((num_valid + BLOCK_N - 1) // BLOCK_N) * BLOCK_N

    for bn in range(0, max_bn, BLOCK_N):
        idx_ptrs = Indices_ptr + t * stride_idx_t + (s + (bn + offs_n) * NUM_SPLITS)
        idx = tl.load(idx_ptrs)
        valid = idx >= 0
        safe_idx = tl.where(valid, idx, 0).to(tl.int64)

        kc_ptrs = Ckv_ptr + safe_idx[:, None] * stride_kc_s + offs_ckv[None, :]
        kp_ptrs = Kpe_ptr + safe_idx[:, None] * stride_kp_s + offs_kpe[None, :]
        kc = tl.load(kc_ptrs, mask=valid[:, None], other=0.0, cache_modifier=".cg", eviction_policy="evict_first")
        kp = tl.load(kp_ptrs, mask=valid[:, None], other=0.0, cache_modifier=".cg", eviction_policy="evict_first")

Doğaç Eldenk, contest first place, sparse_fused.py, lines 78–92. Shown for comparison; it is not part of this repository.

        idx = sparse_indices[t]
        idx = idx[idx != -1].long()
        if idx.numel() == 0:
            continue
        kc = ckv[idx].float()
        kp = kpe[idx].float()

scripts/triton_profile_worker.py, lines 118–123. Boolean index, then one gather of the latent and the positional key.

Score, softmax, and the output dot

The score is q_nope · ckv + q_pe · kpe, scaled into base 2, then an online softmax. The output dot reuses the keys that were just gathered. Invalid positions stay at −∞, so they add nothing.

    // ---- Logit phase: WMMA GEMM, K-split across 16 warps ----------------
    {
      fragment<matrix_a, MMA_M, MMA_N, MMA_K, __nv_bfloat16, row_major> a_frag;
      fragment<matrix_b, MMA_M, MMA_N, MMA_K, __nv_bfloat16, col_major> b_frag;
      fragment<accumulator, MMA_M, MMA_N, MMA_K, float> c_frag;
      fill_fragment(c_frag, 0.f);

      #pragma unroll
      for (int ks = 0; ks < CK_KT_PER_WARP; ++ks) {
        const int k_off = (warp_id * CK_KT_PER_WARP + ks) * MMA_K;
        load_matrix_sync(a_frag, s_qn + k_off, D_CK);
        load_matrix_sync(b_frag, ckv_buf + k_off, D_CK);
        mma_sync(c_frag, a_frag, b_frag, c_frag);
      }

      if (warp_id < KP_KTILES) {
        const int k_off = warp_id * MMA_K;
        load_matrix_sync(a_frag, s_qp + k_off, D_KP);
        load_matrix_sync(b_frag, kpe_buf + k_off, D_KP);
        mma_sync(c_frag, a_frag, b_frag, c_frag);
      }

      store_matrix_sync(s_mma_scratch + warp_id * H_ * BK, c_frag, BK, mem_row_major);
    }
    __syncthreads();  // SYNC_A2

    // ---- Reduce partials + scale + mask → s_logits_tile -----------------
    if (tid < H_ * BK) {
      const int r = tid & (BK - 1);
      float sum = 0.f;
      #pragma unroll
      for (int w = 0; w < WARPS; ++w) {
        sum += s_mma_scratch[w * (H_ * BK) + tid];
      }
      const int k = tile * BK + r;
      const int g_idx = s_gidx[k];
      s_logits_tile[tid] = (g_idx >= 0) ? (sum * sm_scale_log2e) : -INFINITY;

solution/python/mla_cta.cuh, lines 259–295

    score = tl.dot(q, tl.trans(k))
    score = tl.dot(qp, tl.trans(kp), acc=score)
    score = tl.where(valid[None, :], score * sm_log2e, float("-inf"))

    m_new = tl.maximum(m, tl.max(score, axis=1))
    m_ref = tl.where(m_new == float("-inf"), 0.0, m_new)
    prob = tl.exp2(score - m_ref[:, None])
    if W == D:
        k_out = k
    else:
        k_out = tl.load(
            ckv + rows[:, None] * stride_ck + (col0 + tl.arange(0, W))[None, :],
            mask=valid[:, None], other=0.0,
        )
    mix = tl.dot(prob.to(tl.bfloat16), k_out)
    if FIRST:
        l_new = tl.sum(prob, axis=1)
        acc_new = mix
    else:
        # exp2(-inf) is 0, so an empty running state drops out by itself.
        alpha = tl.exp2(m - m_ref)
        l_new = l * alpha + tl.sum(prob, axis=1)
        acc_new = acc * alpha[:, None] + mix

solution/triton/kernel.py, lines 420–442

                TL.clear(score)
                TL.gemm(q_s, k_s, score, transpose_B=True, policy=TL.GemmWarpPolicy.FullRow)
                TL.clear(pe)
                TL.gemm(qp_s, kp_s, pe, transpose_B=True, policy=TL.GemmWarpPolicy.FullRow)
                for h, i in TL.Parallel(H, block):
                    total = (score[h, i] + pe[h, i]) * sm
                    score[h, i] = TL.if_then_else(valid_s[i] == 1, total, -1.0e30)

                # An empty tile must not move the running softmax. cnt is the
                # same value for every thread of the program.
                if cnt[0] > 0:
                    TL.reduce_max(score, m_row, dim=1)
                    for h in TL.Parallel(H):
                        m_row[h] = TL.max(m_row[h], m_i[h])
                        alpha_s[h] = TL.exp2(m_i[h] - m_row[h])
                        l_i[h] = l_i[h] * alpha_s[h]
                        m_i[h] = m_row[h]
                    for h, i in TL.Parallel(H, block):
                        score[h, i] = TL.exp2(score[h, i] - m_i[h])
                    TL.reduce_sum(score, row_sum, dim=1)
                    for h in TL.Parallel(H):
                        l_i[h] = l_i[h] + row_sum[h]
                    TL.sync_threads()
                    for h, i in TL.Parallel(H, block):
                        p_s[h, i] = TL.cast(score[h, i], "bfloat16")
                    # One gemm covers all 512 columns. k_s still holds the keys.
                    TL.clear(mix)
                    TL.gemm(p_s, k_s, mix, policy=TL.GemmWarpPolicy.FullRow)
                    for h, d in TL.Parallel(H, D):
                        acc_s[h, d] = acc_s[h, d] * alpha_s[h] + mix[h, d]

solution/tilelang/solution.py, lines 105–134

        for (int chunk = 0; chunk < kScoreChunks; ++chunk) {
            fill_tile(sk, ckv, kDim, s.idx, chunk * kWide, kTile, true);
            fill_tile(sq, q, stride_q, nullptr, chunk * kWide, kHeads, false);
            mma_chunk<false>(acc_tm, sk, sq, sem, phase, chunk == 0);
        }
        fill_tile(k_st, kpe, kDimPe, s.idx, 0, kTile, true);
        fill_tile(q_st, qp, stride_qp, nullptr, 0, kHeads, false);
        mma_chunk<false>(acc_tm, k_st, q_st, sem, phase, false);
        dump_acc(acc_tm, c_smem);

        for (int e = tx; e < kTile * kHeads; e += kThreads) {
            const int r = e / kHeads;
            const int h = e % kHeads;
            s.score[r][h] = (s.idx[r] >= 0) ? c_smem[{r, h}] * sm_log2e : -INFINITY;
        }
        __syncthreads();

        if (tx < kHeads) {
            float m_tile = -INFINITY;
            for (int i = 0; i < kTile; ++i) m_tile = fmaxf(m_tile, s.score[i][tx]);
            float l_tile = 0.f;
            for (int i = 0; i < kTile; ++i) {
                const float s_i = s.score[i][tx];
                const float p = (m_tile > -1.0e20f && s_i > -1.0e20f) ? exp2f(s_i - m_tile) : 0.f;
                s.prob[tx][i] = p;
                l_tile += p;
            }
            float alpha = 1.f;
            if (m_tile > -1.0e20f) {
                const float m_new = fmaxf(s.m[tx], m_tile);
                // Probs were computed against the tile max. The running total
                // lives at m_new, so both sides have to move there.
                alpha = (s.m[tx] > -1.0e20f) ? exp2f(s.m[tx] - m_new) : 0.f;
                const float scale_tile = exp2f(m_tile - m_new);
                for (int i = 0; i < kTile; ++i) s.prob[tx][i] *= scale_tile;
                s.l[tx] = s.l[tx] * alpha + l_tile * scale_tile;

solution/tk/attention.cu, lines 211–246

        logits = tl.dot(q_nope, tl.trans(kc))
        logits = tl.dot(q_pe, tl.trans(kp), acc=logits)
        logits = logits * sm_scale_log2e
        logits = tl.where(valid[None, :], logits, NEG_INF)

        m_new = tl.maximum(m_i, tl.max(logits, axis=1))
        m_new_safe = tl.where(m_new == NEG_INF, 0.0, m_new)
        alpha = tl.where(m_i == NEG_INF, 0.0, tl.exp2(m_i - m_new_safe))
        p = tl.exp2(logits - m_new_safe[:, None])
        l_i = l_i * alpha + tl.sum(p, axis=1)
        acc = acc * alpha[:, None]
        acc = tl.dot(p.to(tl.bfloat16), kc, acc=acc)

Doğaç Eldenk, contest first place, sparse_fused.py, lines 94–105. Shown for comparison; it is not part of this repository.

        score = (q_nope[t].float() @ kc.T + q_pe[t].float() @ kp.T) * float(sm_scale)
        lse[t] = torch.logsumexp(score, dim=-1) / math.log(2.0)
        out[t] = torch.softmax(score, dim=-1) @ kc

scripts/triton_profile_worker.py, lines 124–126. Natural-base softmax. The log-sum-exp is divided by ln(2) so lse matches the kernels.

Merge the partials

Each key-group keeps a full 512-wide partial. The program that owns a column range rescales every group's partial into one softmax and writes those columns. CUDA does this in a second kernel. Triton and ThunderKittens do it in the same launch, behind a counter. TileLang does it in a second kernel, and the host replays both from one CUDA graph.


  float m_final = -INFINITY;
  #pragma unroll
  for (int g = 0; g < G_; ++g) m_final = fmaxf(m_final, s_m[g]);

  if (m_final == -INFINITY) {
    const __nv_bfloat162 zero =
        __halves2bfloat162(f_to_bf16(0.f), f_to_bf16(0.f));
    reinterpret_cast<__nv_bfloat162*>(out + out_off)[tid] = zero;
    if (tid == 0) lse_out[lse_i] = -INFINITY;
    return;
  }

  float l_final = 0.f;
  #pragma unroll
  for (int g = 0; g < G_; ++g) {
    l_final += s_l[g] * exp2f(s_m[g] - m_final);
  }
  const float inv_l = 1.f / l_final;

  float o0 = 0.f, o1 = 0.f;
  const int i = tid;
  #pragma unroll
  for (int g = 0; g < G_; ++g) {
    const float alpha = exp2f(s_m[g] - m_final);
    // Phase 7i: partials are fp32 (was bf16). Each lane reads 2 fp32 values.
    const float2* op2 =
        reinterpret_cast<const float2*>(O_partial + o_part_base + g * D_CK);
    const float2 of = op2[i];
    o0 += of.x * alpha;
    o1 += of.y * alpha;
  }

  const __nv_bfloat162 packed =
      __halves2bfloat162(f_to_bf16(o0 * inv_l), f_to_bf16(o1 * inv_l));
  reinterpret_cast<__nv_bfloat162*>(out + out_off)[i] = packed;
  if (tid == 0) lse_out[lse_i] = m_final + log2f(l_final);

solution/python/mla_legacy.cuh, lines 612–648

        # Every thread has issued its stores before the arrival is counted.
        tl.debug_barrier()
        tl.atomic_add(counter + token, 1, sem="release")
        count = tl.load(counter + token, volatile=True)
        # The difference stays correct when the counter wraps around.
        while (count - target) < 0:
            count = tl.load(counter + token, volatile=True)
        tl.debug_barrier()

        # Merge columns `cols` of all G partials.
        m_top = m0
        for g in tl.static_range(G):
            m_top = tl.maximum(m_top, tl.load(part_m + (token * G + g) * H + heads, cache_modifier=".cg"))
        m_ref = tl.where(m_top == float("-inf"), 0.0, m_top)
        l_sum = l0
        mix = tl.zeros((H, W), tl.float32)
        for g in tl.static_range(G):
            src = (token * G + g) * H + heads
            weight = tl.exp2(tl.load(part_m + src, cache_modifier=".cg") - m_ref)
            l_sum += tl.load(part_l + src, cache_modifier=".cg") * weight
            piece = tl.load(part_acc + src[:, None] * D + cols[None, :], cache_modifier=".cg")
            mix += piece * weight[:, None]

        inv = tl.where(l_sum > 0, 1.0 / l_sum, 0.0)
        tl.store(out_ptr, (mix * inv[:, None]).to(tl.bfloat16))
        if slot == 0:
            tl.store(lse_ptr, tl.where(l_sum > 0, m_top + tl.log2(tl.where(l_sum > 0, l_sum, 1.0)), float("-inf")))

solution/triton/kernel.py, lines 574–600

            for src in TL.serial(g):
                for h in TL.Parallel(H):
                    m_top[h] = TL.max(m_top[h], part_m[token, src, h])
            for h in TL.Parallel(H):
                # -inf minus -inf is NaN. An empty token has no finite partial.
                m_top[h] = TL.if_then_else(m_top[h] < -1.0e20, 0, m_top[h])
            for src in TL.serial(g):
                for h in TL.Parallel(H):
                    weight = TL.exp2(part_m[token, src, h] - m_top[h])
                    l_sum[h] = l_sum[h] + part_l[token, src, h] * weight
                for h, c in TL.Parallel(H, width):
                    col = slot * width + c
                    weight = TL.exp2(part_m[token, src, h] - m_top[h])
                    merged[h, c] = merged[h, c] + part_acc[token, src, h, col] * weight
            for h, c in TL.Parallel(H, width):
                col = slot * width + c
                out[token, h, col] = TL.cast(
                    TL.if_then_else(l_sum[h] > 0, merged[h, c] / l_sum[h], 0), "bfloat16"
                )
            if slot == 0:
                for h in TL.Parallel(H):
                    lse[token, h] = TL.if_then_else(
                        l_sum[h] > 0, m_top[h] + TL.log2(TL.max(l_sum[h], 1.0e-30)), float("-inf")
                    )

solution/tilelang/solution.py, lines 162–185

    // Read the counter before this CTA's own increment. The next multiple of
    // G is the value it reaches once every key-group has published.
    if (tx == 0) target = (counter[token] & -G) + G;
    __syncthreads();
    const int slot_base = (token * G + slot) * kHeads;
    publish(part_acc, part_m, part_l, slot_base, running);
    __threadfence();
    __syncthreads();
    if (tx < 32) tm.deprovision();
    __syncthreads();
    if (tx == 0) {
        atomicAdd(counter + token, 1);
        int count;
        do {
            count = *static_cast<volatile int*>(counter + token);
        } while (count - target < 0);
    }
    __syncthreads();

    constexpr int kWidth = kDim / G;
    for (int c = tx; c < kWidth; c += kThreads) {
        const int col = slot * kWidth + c;
        float m_top[kHeads], l_sum[kHeads], mix[kHeads];
        for (int h = 0; h < kHeads; ++h) {
            m_top[h] = -INFINITY;
            l_sum[h] = 0.f;
            mix[h] = 0.f;
        }
        for (int g = 0; g < G; ++g) {
            const int base = (token * G + g) * kHeads;
            for (int h = 0; h < kHeads; ++h) m_top[h] = fmaxf(m_top[h], part_m[base + h]);
        }
        for (int g = 0; g < G; ++g) {
            const int base = (token * G + g) * kHeads;
            for (int h = 0; h < kHeads; ++h) {
                const float m_ref = m_top[h] > -1.0e20f ? m_top[h] : 0.f;
                const float weight = exp2f(part_m[base + h] - m_ref);
                l_sum[h] += part_l[base + h] * weight;
                mix[h] += part_acc[(base + h) * kDim + col] * weight;
            }
        }
        for (int h = 0; h < kHeads; ++h) {
            const float inv = l_sum[h] > 0.f ? 1.f / l_sum[h] : 0.f;
            out_row[h * stride_oh + col] = __float2bfloat16(mix[h] * inv);
        }
        if (c == 0 && slot == 0) {
            for (int h = 0; h < kHeads; ++h)
                lse_row[h] = l_sum[h] > 0.f ? m_top[h] + log2f(l_sum[h]) : -INFINITY;

solution/tk/attention.cu, lines 370–417

    # ===== Atomic barrier =====
    tl.atomic_add(Counter_ptr + t, 1, sem="release")

    count = tl.load(Counter_ptr + t, volatile=True)
    while count < target_count:
        count = tl.load(Counter_ptr + t, volatile=True)
    tl.debug_barrier()
...
    for si in tl.static_range(NUM_SPLITS):
        pm_ptr_s = Partial_m_ptr + t * stride_pm_t + si * stride_pm_s + offs_h * stride_pm_h
        pl_ptr_s = Partial_l_ptr + t * stride_pl_t + si * stride_pl_s + offs_h * stride_pl_h
        m_si = tl.load(pm_ptr_s)
        l_si = tl.load(pl_ptr_s)

        pacc_ptr_s = (
            Partial_acc_ptr
            + t * stride_pacc_t
            + si * stride_pacc_s
            + offs_h[:, None] * stride_pacc_h
            + offs_d[None, :] * stride_pacc_d
        )
        acc_si = tl.load(pacc_ptr_s)

        m_new = tl.maximum(m_global, m_si)
        m_new_safe = tl.where(m_new == NEG_INF, 0.0, m_new)
        alpha = tl.where(m_global == NEG_INF, 0.0, tl.exp2(m_global - m_new_safe))
        beta = tl.where(m_si == NEG_INF, 0.0, tl.exp2(m_si - m_new_safe))
        acc_comb = acc_comb * alpha[:, None] + acc_si * beta[:, None]
        l_global = l_global * alpha + l_si * beta
        m_global = m_new

Doğaç Eldenk, contest first place, sparse_fused.py, lines 121–127 and 137–159. Shown for comparison; it is not part of this repository.

        lse[t] = torch.logsumexp(score, dim=-1) / math.log(2.0)
        out[t] = torch.softmax(score, dim=-1) @ kc

scripts/triton_profile_worker.py, lines 125–126. The softmax already covers every gathered key, so there is no partial and no merge.

Why the fused kernel is faster than first place

Doğaç Eldenk's kernel is the same idea: one Triton launch, 16 programs per token, and a counter that lets those programs merge. On the official 50-iteration run it averages 10.2 µs, 0.45× the CUDA submission. run_fused averages 8.6 µs, 0.37×, and it is faster on every one of the 23 workloads. The full five-way table is on the comparison page. The gap comes from when the keys are split, and from how long a tile is.

Fused, this repositoryContest first place
One or two tokensIf the last valid index is below 128, each program scores the row and writes its own columns. Past that, the keys are split.Always the small kernel. All 16 programs score every key and each writes 32 columns. The keys are never split.
Three or more tokensThe same test, per token. A short token does not publish a partial and does not wait.Always a 16-way key split and the barrier, including a token with a few dozen keys.
TileThe smallest of 32, 64, and 128 that covers the positions up to the last valid index. The loads sit in a loop, so Triton pipelines them.64 on the small kernel and 128 on the split kernel. If a split contains any valid index, that program gathers one full block.

Three workloads are enough to see it. On 05f6de65 there are two tokens and the longer one has 288–337 keys. First place stays on the small kernel, so every program gathers and scores that whole row: 16.4 µs. The fused kernel splits the keys, and each program scores about a sixteenth of the span: 8.1 µs. 9f3f891b is the same situation, 14.3 µs against 8.0 µs.

68d6817d has 6 tokens and at most 32 keys each. First place splits because the token count is above 2. Each program gathers a 128-wide block as soon as its stride holds one valid index, writes a partial, and waits at the barrier: 11.2 µs. The fused kernel takes the direct path and skips the partials and the barrier: 4.4 µs.

On a dense call both kernels split 16 ways, and the gap shrinks to the tile. First place gathers 128 keys per program. The fused kernel stops at the last valid index and takes the smallest tile that covers it. 02d6ae9c (8 tokens, 303 keys) is 12.0 µs against 11.1 µs. Across the dense calls the difference stays inside about 1.3 µs.

CaseTKeysFusedFirst place
Shortest call, 0c23b10c123.94.8
Two long tokens, 05f6de6521718.116.4
Six short tokens, 68d6817d6184.411.2
Dense call, 02d6ae9c830311.112.0
Mean, all 238.610.2

Microseconds, the official 50-iteration timer. Fused is faster on the other 19 workloads as well; each one is on the comparison page.

Where the code is

Run them

modal run scripts/profile_frameworks.py
modal run scripts/profile_frameworks.py --which tk,tilelang --tilelang 16x128,16x64

The image is the contest image plus TileLang 0.1.15 and a checkout of ThunderKittens. The first run_commands block matches scripts/profile_triton.py so that layer stays cached. The timer and the reference live in scripts/triton_profile_worker.py. The result of the run below is artifacts/frameworks_final.json.

Four shapes, all 23 workloads

Latency is microseconds, the CUPTI span of this 10-iteration run. TileLang busy is the time its kernels actually spend running; the span includes the idle gaps between launches. Block 64 was slower on every workload that matters (geomean 97.6 µs against 95.9), so these are the 128-wide tile. The other 19 workloads sit between these rows. Every number is in artifacts/frameworks_final.json.

CaseTKeysCUDATritonThunderKittensTileLangTileLang busy
Shortest call, 0c23b10c123.44.047.081.826.3
Six short tokens, 68d6817d6189.64.351.379.825.4
Two long tokens, 05f6de65217122.88.264.288.331.4
Dense call, 02d6ae9c830351.811.0104.0113.460.8
Geomean, all 2321.17.8876.395.939.6
Mean, all 2331.48.5279.397.042.2

The CUDA and Triton means here (31.4 µs and 8.52 µs) are this 10-iteration run. The comparison page reports the official 50-iteration evaluator: 31.6 µs and 8.6 µs, workload by workload.

Why CUDA, ThunderKittens, and TileLang are slower

On the dense call (02d6ae9c, 8 tokens, 303 keys) Triton is one kernel and takes 11.0 µs. CUDA takes 51.8 µs in two kernels. ThunderKittens takes 104 µs in one kernel. TileLang's kernels take 46.2 µs and 6.6 µs, plus about 8 µs of small copies, so the GPU is busy for 60.8 µs. The span is 113 µs because the GPU waits between those launches.

CUDA was tuned for a 16-key WMMA tile and a second kernel that merges the partials. In the timed build, twelve of the 23 workloads took that per-head path, which is about 0.9 µs per tile. The source now picks the path from the token count: T >= 8 uses the per-token kernel, and a smaller call stays per-head. That shape rule was measured slightly faster than counting valid indices, and the decision is a comparison of T. The fused Triton kernel scores 32 to 128 keys in one pipelined tile and merges in the same launch. CUDA still wins the shortest call, 3.4 µs against 4.0. Past a handful of keys the 16-key tile and the second kernel are the whole gap: the dense call is 51.8 µs against 11.0.

ThunderKittens pays for the tensor-core tile. mm_ABt consumes 128 rows and a K that is a multiple of 64, and this problem has 16 heads and a 512-d latent, so most of each tile is padding. Scoring 128 keys is four K=128 steps plus the positional key. The output is eight more mm_ABs of 64 columns. Each step gathers into a swizzled tile, one thread issues the MMA, and every thread waits. One such tile is already about 50 µs on a token with two keys, which Triton scores in 4 µs. The 16-byte vector gather removed the scalar shared-memory cost. The number of MMA steps is still there.

TileLang pays for the gather and for two launches. A 16-byte load comes back as a vector this frontend cannot index, so a 128 by 512 key tile is copied one element at a time. The gemm itself is one call for the score and one call for all 512 output columns. The reported 95.9 µs geomean is that work plus the idle time between the partial kernel and the merge. Kernel-busy time is 39.6 µs.

Triton is one pipelined launch. The score, the softmax, and the output dot share the K that was just loaded, and the merge is a counter in that same kernel. On 16 heads by 512 that is worth more than the tensor-core instruction the other two are built around.

What is left to tune

ThunderKittens has a small-token opening and no dense one. A path that skips tcgen05 for a token under 128 keys would cut the calls that currently spend about 50 µs scoring a handful of keys. The dense call needs the 512-d multiply. Halving the number of steps means a K of 256, and doubling those tiles adds about 80 KB. The tiles already allocated, plus the running softmax, sit near the 227 KB a B200 block can hold, so that kernel was not built. The measured sequence is the one that fits: a scalar epilogue was 234 µs, half-width output MMAs were about 50 µs, and the wide score plus one mm_AB per 64 columns is the 47–104 µs in the table.

TileLang 0.1.15 has no unused knob that won a measurement. Block 128 beat block 64 (geomean 95.9 µs against 97.6). One output gemm beat eight chunk gemms. A CUDA graph of the two kernels beat folding them together with a grid sync, which moved the short call from 82 µs to 134 µs, and it beat the cython launcher, which took about 225 µs. A vectorized gather was slower than the element gather. The graph replays both kernels and still leaves the GPU idle between them. The remaining room is a later TileLang that can index a 16-byte load, or that can issue both kernels without that gap. It is not a parameter of this file.

What to ship

Ship run_fused. On the official 50-iteration run it averages 8.6 µs, 0.37× the CUDA submission, against 10.2 µs and 0.45× for the contest winner. It is faster than that kernel on every one of the 23 workloads, and faster than the CUDA submission on 22 of them. TileLang and ThunderKittens are correct, including scattered padding and token counts past the contest range, and they are the right way to read the algorithm in those languages. They are not the fast path for 16 heads and a 512-d latent.