KernelBench cuda · RTX PRO 6000

DeepSeek NSA Ergo 1.0

0.330 msgeomean latency across six shapes · lower is better

manually audited: clean

Amazon Ergo 1.0 (max effort, ergo-codex) wrote a 1,403-line hand-written SM120 CUDA/PTX block-sparse Native Sparse Attention pipeline using ldmatrix.sync, mma.sync.m16n8k16, and cp.async.cg. It computes exact fp32 per-block key means and causal diagonal prefix sums, selects exact top-8 blocks per query with larger-index tie-breaking, builds an inverted-index per-block work list in shared memory via counting sort, and runs block-sparse FlashAttention with online softmax inside a CUDA Graph keyed on live input pointers. Lands 0.330 ms geomean (0.2987 peak_fraction). Notably, at minute 264 Ergo hit a fake 14.80 score from an empty CUDA Graph (kernels still on the legacy default stream), immediately caught the warning itself, wrote an in-place overwrite probe, fixed all streams to at::cuda::getCurrentCUDAStream(), and kept the honest 0.2987 result.

harnessergo-codexthinkingmaxagent session6h 26mtotal wall6h 32mcheck5mbenchmark2soutput tokens561,461gpu-lock wait1h 4mgpu-lock held3h 10mregimecompute

Per-shape latencymilliseconds are the measured result; the dense-equivalent roofline is not a useful ceiling

1×16×2048×640.200 ms
1×16×4127×640.400 ms
1×8×8192×640.520 ms
1×8×8191×1280.694 ms
4×8×1024×640.165 ms
2×8×3000×640.271 ms

geomean(0.200 ms · 0.400 ms · 0.520 ms · 0.694 ms · 0.165 ms · 0.271 ms) = 0.330 ms

Kernel source (redacted)
"""DeepSeek NSA-inspired sparse attention (bench semantics) in CUDA.

Pipeline:
  1. block_stats: per-block key mean + inclusive within-block prefix sums.
  2. block_scores_topk: q @ block_mean -> block importance, override the
     diagonal (partially causal) block with q @ prefix, pick top-8 blocks.
  3. sparse_attn: block-sparse flash-style attention over the union of the
     selected blocks and the 64-token sliding window (online softmax).
"""
from __future__ import annotations

import math

import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline

BLOCK_SIZE = 64
TOP_N_BLOCKS = 8
SLIDING_WINDOW = 64

_CUDA_SRC = r"""
#include <torch/extension.h>
#include <cuda_runtime.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda_bf16.h>
#include <mma.h>
#include <cstdint>

using namespace nvcuda;

#define MAX_BLOCKS 128

__device__ __forceinline__ float bf2f(__nv_bfloat16 x) { return __bfloat162float(x); }

// ---------------------------------------------------------------------------
// 1. block statistics: mean key per block and inclusive prefix sum in-block
// ---------------------------------------------------------------------------
__global__ void block_stats_kernel(const __nv_bfloat16* __restrict__ K,
                                   float* __restrict__ kmean,
                                   float* __restrict__ kprefix,
                                   int S, int D, int n_blocks) {
    int bh = blockIdx.y;
    int bi = blockIdx.x;
    int d = threadIdx.x;
    if (d >= D) return;
    int64_t base = ((int64_t)bh * S + (int64_t)bi * 64) * D + d;
    int count = min(64, S - bi * 64);
    float sum = 0.f;
    for (int j = 0; j < count; ++j) {
        float x = bf2f(K[base + (int64_t)j * D]);
        sum += x;
        kprefix[base + (int64_t)j * D] = sum;
    }
    kmean[((int64_t)bh * n_blocks + bi) * D + d] = sum / (float)count;
}

// ---------------------------------------------------------------------------
// 2. block importance scores + top-8 selection
// ---------------------------------------------------------------------------
template<int TR, int TB, int DCHUNK, int KCHUNK, int D>
__global__ void block_scores_kernel(
        const __nv_bfloat16* __restrict__ Q,
        const float* __restrict__ kmean,
        float* __restrict__ scores_g,
        int S, int n_blocks, float scale) {
    constexpr int TQ = 64;
    const int QSTR = D + 8;
    const int KSTR = D + 8;
    int bh = blockIdx.y;
    int q0 = blockIdx.x * TQ;
    int tx = threadIdx.x % (TQ / TR);
    int ty = threadIdx.x / (TQ / TR);
    int nty = (min(KCHUNK, n_blocks) + TB - 1) / TB;

    extern __shared__ __nv_bfloat16 smem_bf16[];
    __nv_bfloat16* Qs = smem_bf16;
    float* Kc = (float*)(Qs + TQ * QSTR);

    // load Q tile (padded rows to avoid shared bank conflicts)
    {
        constexpr int V = 8; // 8 bf16 = 16 bytes
        int nvec = TQ * D / V;
        for (int i = threadIdx.x; i < nvec; i += blockDim.x) {
            int r = (i * V) / D, d = (i * V) % D;
            int gq = q0 + r;
            int4 val = make_int4(0,0,0,0);
            if (gq < S) val = *reinterpret_cast<const int4*>(Q + ((int64_t)bh * S + gq) * D + d);
            *reinterpret_cast<int4*>(Qs + r * QSTR + d) = val;
        }
    }
    __syncthreads();

    float acc[TR][TB];
    #pragma unroll
    for (int r = 0; r < TR; ++r)
        #pragma unroll
        for (int c = 0; c < TB; ++c) acc[r][c] = 0.f;

    for (int kc0 = 0; kc0 < n_blocks; kc0 += KCHUNK) {
        int kcols = min(KCHUNK, n_blocks - kc0);
        {
            constexpr int V = 4;
            int nvec = kcols * D / V;
            for (int i = threadIdx.x; i < nvec; i += blockDim.x) {
                int r = (i * V) / D, d = (i * V) % D;
                float4 val = *reinterpret_cast<const float4*>(kmean + ((int64_t)bh * n_blocks + kc0 + r) * D + d);
                *reinterpret_cast<float4*>(Kc + r * KSTR + d) = val;
            }
        }
        __syncthreads();
        if (ty < nty) {
            for (int d0 = 0; d0 < D; d0 += DCHUNK) {
                float qv[TR][DCHUNK];
                float kv[TB][DCHUNK];
                #pragma unroll
                for (int r = 0; r < TR; ++r)
                    #pragma unroll
                    for (int i = 0; i < DCHUNK; ++i)
                        qv[r][i] = bf2f(Qs[(tx * TR + r) * QSTR + d0 + i]);
                #pragma unroll
                for (int c = 0; c < TB; ++c)
                    #pragma unroll
                    for (int i = 0; i < DCHUNK; ++i)
                        kv[c][i] = Kc[(ty * TB + c) * KSTR + d0 + i];
                #pragma unroll
                for (int r = 0; r < TR; ++r)
                    #pragma unroll
                    for (int c = 0; c < TB; ++c)
                        #pragma unroll
                        for (int i = 0; i < DCHUNK; ++i)
                            acc[r][c] += qv[r][i] * kv[c][i];
            }
            #pragma unroll
            for (int r = 0; r < TR; ++r)
                #pragma unroll
                for (int c = 0; c < TB; ++c) {
                    int col = kc0 + ty * TB + c;
                    int gq = q0 + tx * TR + r;
                    if (col < n_blocks && gq < S)
                        scores_g[((int64_t)bh * S + gq) * n_blocks + col] = acc[r][c] * scale;
                }
        }
        __syncthreads();
    }
}

// one thread per query row: diagonal override + top-8 selection
template<int D>
__global__ void topk_kernel(
        const float* __restrict__ scores_g,
        const float* __restrict__ kprefix,
        const __nv_bfloat16* __restrict__ Q,
        int* __restrict__ sel,
        int S, int n_blocks, float scale) {
    int bh = blockIdx.y;
    int q0 = blockIdx.x * 64;
    int row = threadIdx.x;
    int t = q0 + row;
    if (t >= S) return;
    int bit = t / 64;
    int count = t - bit * 64 + 1;

    // diagonal block importance = q . prefix[t] * scale / count
    float diag = 0.f;
    #pragma unroll
    for (int d = 0; d < D; d += 4) {
        float4 pv = *reinterpret_cast<const float4*>(kprefix + ((int64_t)bh * S + t) * D + d);
        uint2 qv = *reinterpret_cast<const uint2*>(Q + ((int64_t)bh * S + t) * D + d);
        __nv_bfloat16 q0v = *reinterpret_cast<__nv_bfloat16*>(&qv.x);
        diag += bf2f(q0v) * pv.x;
        diag += bf2f(*reinterpret_cast<__nv_bfloat16*>(reinterpret_cast<char*>(&qv.x) + 2)) * pv.y;
        diag += bf2f(*reinterpret_cast<__nv_bfloat16*>(reinterpret_cast<char*>(&qv.y))) * pv.z;
        diag += bf2f(*reinterpret_cast<__nv_bfloat16*>(reinterpret_cast<char*>(&qv.y) + 2)) * pv.w;
    }
    diag = diag * scale / (float)count;

    if (n_blocks <= 32) {
    unsigned long long chosen_lo = 0, chosen_hi = 0;
    const float* srow = scores_g + ((int64_t)bh * S + t) * n_blocks;
    #pragma unroll
    for (int it = 0; it < 8; ++it) {
        float bs = -__int_as_float(0x7f800000);
        int bb = -1;
        int b = 0;
        for (; (n_blocks % 4 == 0) && (b + 3 < n_blocks); b += 4) {
            float4 v4 = *reinterpret_cast<const float4*>(srow + b);
            float v[4] = {v4.x, v4.y, v4.z, v4.w};
            #pragma unroll
            for (int i = 0; i < 4; ++i) {
                int bi = b + i;
                float x;
                if (bi > bit) x = -__int_as_float(0x7f800000);
                else if (bi == bit) x = diag;
                else x = v[i];
                bool used = (bi < 64) ? ((chosen_lo >> bi) & 1ULL)
                                      : ((chosen_hi >> (bi - 64)) & 1ULL);
                if (used) x = -__int_as_float(0x7f800000);
                bool better = (x > bs) || (x == bs && bi > bb);
                bs = better ? x : bs;
                bb = better ? bi : bb;
            }
        }
        for (; b < n_blocks; ++b) {
            float x;
            if (b > bit) x = -__int_as_float(0x7f800000);
            else if (b == bit) x = diag;
            else x = srow[b];
            bool used = (b < 64) ? ((chosen_lo >> b) & 1ULL)
                                 : ((chosen_hi >> (b - 64)) & 1ULL);
            if (used) x = -__int_as_float(0x7f800000);
            bool better = (x > bs) || (x == bs && b > bb);
            bs = better ? x : bs;
            bb = better ? b : bb;
        }
        int out_bi = (bb >= 0 && bb <= bit) ? bb : -1;
        sel[((int64_t)bh * S + t) * 8 + it] = out_bi;
        if (bb >= 0) {
            if (bb < 64) chosen_lo |= (1ULL << bb);
            else chosen_hi |= (1ULL << (bb - 64));
        }
    }    } else {
        float vals[128];
        #pragma unroll
        for (int b = 0; b < 128; ++b) {
            if (b >= n_blocks || b > bit) vals[b] = -__int_as_float(0x7f800000);
            else if (b == bit) vals[b] = diag;
            else vals[b] = scores_g[((int64_t)bh * S + t) * n_blocks + b];
        }
        #pragma unroll
        for (int it = 0; it < 8; ++it) {
            float bs = -__int_as_float(0x7f800000);
            int bb = -1;
            #pragma unroll
            for (int b = 0; b < 128; ++b) {
                float v = vals[b];
                bool better = (v > bs) || (v == bs && b > bb);
                bs = better ? v : bs;
                bb = better ? b : bb;
            }
            int out_bi = (bb >= 0 && bb <= bit) ? bb : -1;
            sel[((int64_t)bh * S + t) * 8 + it] = out_bi;
            if (bb >= 0) vals[bb] = -__int_as_float(0x7f800000);
        }
    }
}

// ---------------------------------------------------------------------------
// ldmatrix + mma.sync helpers (SM120 wmma lowering uses conflict-heavy LDS)
// ---------------------------------------------------------------------------
__device__ __forceinline__ uint32_t smem_u32(const void* p) {
    return static_cast<uint32_t>(__cvta_generic_to_shared(p));
}
__device__ __forceinline__ void ldmatrix_x4(uint32_t& r0, uint32_t& r1, uint32_t& r2,
                                            uint32_t& r3, const void* p) {
    uint32_t addr = smem_u32(p);
    asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];\n"
                 : "=r"(r0), "=r"(r1), "=r"(r2), "=r"(r3) : "r"(addr));
}
__device__ __forceinline__ void ldmatrix_x2(uint32_t& r0, uint32_t& r1, const void* p) {
    uint32_t addr = smem_u32(p);
    asm volatile("ldmatrix.sync.aligned.m8n8.x2.shared.b16 {%0,%1}, [%2];\n"
                 : "=r"(r0), "=r"(r1) : "r"(addr));
}
__device__ __forceinline__ void ldmatrix_x2_trans(uint32_t& r0, uint32_t& r1, const void* p) {
    uint32_t addr = smem_u32(p);
    asm volatile("ldmatrix.sync.aligned.m8n8.x2.trans.shared.b16 {%0,%1}, [%2];\n"
                 : "=r"(r0), "=r"(r1) : "r"(addr));
}
__device__ __forceinline__ void mma_m16n8k16(float* d, const uint32_t* a, const uint32_t* b) {
    asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 "
                 "{%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};\n"
                 : "+f"(d[0]), "+f"(d[1]), "+f"(d[2]), "+f"(d[3])
                 : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b[0]), "r"(b[1]));
}
__device__ __forceinline__ void cp_async16(void* smem, const void* gmem) {
    uint32_t addr = smem_u32(smem);
    asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" :: "r"(addr), "l"(gmem));
}
__device__ __forceinline__ void cp_async_commit() {
    asm volatile("cp.async.commit_group;\n" ::);
}
__device__ __forceinline__ void cp_async_wait0() {
    asm volatile("cp.async.wait_group 0;\n" ::);
}

// ---------------------------------------------------------------------------
// 3. sparse attention
// ---------------------------------------------------------------------------
template<int D, int TQ, int NW, int M_MAX, int SW>
__global__ void sparse_attn_kernel(
        const __nv_bfloat16* __restrict__ Q,
        const __nv_bfloat16* __restrict__ K,
        const __nv_bfloat16* __restrict__ V,
        const int* __restrict__ sel,
        __nv_bfloat16* __restrict__ O,
        int S, int n_blocks, float scale) {
    constexpr int NTOK = 64;
    constexpr int KSTR = D + 8;
    constexpr int PSTR = NTOK + 8;
    constexpr int SSTR = NTOK + 8;
    constexpr int OSTR = D + 8;
    int bh = blockIdx.y;
    int q0 = blockIdx.x * TQ;
    int tid = threadIdx.x;
    int warp = tid / 32;
    int lane = tid % 32;

    extern __shared__ __nv_bfloat16 smem_bf[];
    __nv_bfloat16* Kbuf = smem_bf;
    __nv_bfloat16* Vbuf = Kbuf + NTOK * KSTR;
    __nv_bfloat16* Qc = Vbuf + NTOK * KSTR;
    float* scores = (float*)(Qc + M_MAX * KSTR);
    __nv_bfloat16* P = (__nv_bfloat16*)(scores + M_MAX * SSTR);
    float* outp = (float*)(P + M_MAX * PSTR);
    float* alpha = outp + M_MAX * OSTR;
    uint16_t* list_all = (uint16_t*)(alpha + M_MAX);
    uint8_t* flags_all = (uint8_t*)(list_all + TQ * 10);
    int* offsets = (int*)(flags_all + TQ * 10);
    int* cursor = offsets + (n_blocks + 1);
    int* qpos = cursor + n_blocks;
    float* mval = (float*)(qpos + TQ);
    float* lval = mval + TQ;
    int* warp_row_count = (int*)(lval + TQ);
    uint8_t* warp_rows = (uint8_t*)(warp_row_count + NW);

    // Per-lane register state for the query owned by this lane.
    float my_acc[D];
    #pragma unroll
    for (int i = 0; i < D; ++i) my_acc[i] = 0.f;
    int myq = warp * 32 + lane;
    int gq = q0 + myq;
    bool q_valid = (myq < TQ) && (gq < S);

    // ---- counting sort: per-block work lists for this query tile ----
    for (int i = tid; i <= n_blocks; i += blockDim.x) offsets[i] = 0;
    __syncthreads();
    int my_sel[8];
    #pragma unroll
    for (int i = 0; i < 8; ++i) my_sel[i] = -1;
    if (myq < TQ) {
        int t = q0 + myq;
        if (t < S) {
            const int* sp = sel + ((int64_t)bh * S + t) * 8;
            #pragma unroll
            for (int i = 0; i < 8; ++i) my_sel[i] = sp[i];
            #pragma unroll
            for (int i = 0; i < 8; ++i) {
                int b = my_sel[i];
                if (b < 0) continue;
                bool dup = false;
                #pragma unroll
                for (int p = 0; p < 8; ++p) if (p < i && my_sel[p] == b) dup = true;
                if (!dup) atomicAdd(&offsets[b], 1);
            }
            int w0 = max(0, t + 1 - 64);
            int sb[2] = {t / 64, w0 / 64};
            #pragma unroll
            for (int si = 0; si < 2; ++si) {
                int b = sb[si];
                if (si == 1 && b == sb[0]) continue;
                bool in_sel = false;
                #pragma unroll
                for (int p = 0; p < 8; ++p) if (my_sel[p] == b) in_sel = true;
                if (!in_sel) atomicAdd(&offsets[b], 1);
            }
        }
    }
    __syncthreads();
    if (tid == 0) {
        int sum = 0;
        for (int b = 0; b < n_blocks; ++b) {
            int c = offsets[b];
            offsets[b] = sum;
            sum += c;
        }
        offsets[n_blocks] = sum;
    }
    __syncthreads();
    for (int i = tid; i < n_blocks; i += blockDim.x) cursor[i] = offsets[i];
    __syncthreads();
    if (myq < TQ) {
        int t = q0 + myq;
        if (t < S) {
            #pragma unroll
            for (int i = 0; i < 8; ++i) {
                int b = my_sel[i];
                if (b < 0) continue;
                bool dup = false;
                #pragma unroll
                for (int p = 0; p < 8; ++p) if (p < i && my_sel[p] == b) dup = true;
                if (dup) continue;
                int pos = atomicAdd(&cursor[b], 1);
                list_all[pos] = (uint16_t)myq;
                flags_all[pos] = 1;
            }
            int w0 = max(0, t + 1 - 64);
            int sb[2] = {t / 64, w0 / 64};
            #pragma unroll
            for (int si = 0; si < 2; ++si) {
                int b = sb[si];
                if (si == 1 && b == sb[0]) continue;
                bool in_sel = false;
                #pragma unroll
                for (int p = 0; p < 8; ++p) if (my_sel[p] == b) in_sel = true;
                if (in_sel) continue;
                int pos = atomicAdd(&cursor[b], 1);
                list_all[pos] = (uint16_t)myq;
                flags_all[pos] = 0;
            }
        }
    }
    for (int i = tid; i < TQ; i += blockDim.x) {
        mval[i] = -__int_as_float(0x7f800000);
        lval[i] = 0.f;
        qpos[i] = -1;
    }
    __syncthreads();

    int qend = min(S - 1, q0 + TQ - 1);
    int max_bi = qend / 64;

    for (int bi = 0; bi <= max_bi; ++bi) {
        int Mtot = offsets[bi + 1] - offsets[bi];
        if (Mtot == 0) continue;
        const uint16_t* blist = list_all + offsets[bi];
        const uint8_t* bflags = flags_all + offsets[bi];

        // load K, V block (async 16B copies)
        int tstart = bi * 64;
        {
            constexpr int Vv = 8;
            int nvec = NTOK * D / Vv;
            for (int i = tid; i < nvec; i += blockDim.x) {
                int r = (i * Vv) / D, d = (i * Vv) % D;
                int g = tstart + r;
                if (g < S) {
                    cp_async16(Kbuf + r * KSTR + d, K + ((int64_t)bh * S + g) * D + d);
                    cp_async16(Vbuf + r * KSTR + d, V + ((int64_t)bh * S + g) * D + d);
                } else {
                    *reinterpret_cast<int4*>(Kbuf + r * KSTR + d) = make_int4(0,0,0,0);
                    *reinterpret_cast<int4*>(Vbuf + r * KSTR + d) = make_int4(0,0,0,0);
                }
            }
            cp_async_commit();
            cp_async_wait0();
        }
        __syncthreads();

        for (int c0 = 0; c0 < Mtot; c0 += M_MAX) {
            int mc = min(M_MAX, Mtot - c0);
            int mp = (mc + 15) / 16 * 16;
            // build Qc (async 16B copies)
            {
                constexpr int Vv = 8;
                int nvec = mp * D / Vv;
                for (int i = tid; i < nvec; i += blockDim.x) {
                    int r = (i * Vv) / D, d = (i * Vv) % D;
                    if (r < mc) {
                        int ql = blist[c0 + r];
                        int gq2 = q0 + ql;
                        cp_async16(Qc + r * KSTR + d, Q + ((int64_t)bh * S + gq2) * D + d);
                    } else {
                        *reinterpret_cast<int4*>(Qc + r * KSTR + d) = make_int4(0,0,0,0);
                    }
                }
                cp_async_commit();
                cp_async_wait0();
            }
            __syncthreads();

            // QK^T: (mp x D) @ (D x 64) -> scores (mp x 64)
            {
                int ntiles_m = mp / 16;
                int ntiles_n = NTOK / 8;
                int ntiles = ntiles_m * ntiles_n;
                int l = lane;
                int arow = (l & 7) + ((l >> 3) & 1) * 8;
                int acol = ((l >> 4) & 1) * 8;
                int bl = l & 15;
                int bn = bl & 7;
                int bk = ((bl >> 3) & 1) * 8;
                int r0 = l >> 2, cc = (l & 3) * 2;
                for (int tile = warp; tile < ntiles; tile += NW) {
                    int tm = tile / ntiles_n;
                    int tn = tile % ntiles_n;
                    float d[4] = {0.f, 0.f, 0.f, 0.f};
                    for (int k0 = 0; k0 < D; k0 += 16) {
                        uint32_t a[4], b[2];
                        ldmatrix_x4(a[0], a[1], a[2], a[3],
                                    Qc + (tm * 16 + arow) * KSTR + k0 + acol);
                        ldmatrix_x2(b[0], b[1], Kbuf + (tn * 8 + bn) * KSTR + k0 + bk);
                        mma_m16n8k16(d, a, b);
                    }
                    *reinterpret_cast<float2*>(scores + (tm * 16 + r0) * SSTR + tn * 8 + cc) =
                        make_float2(d[0], d[1]);
                    *reinterpret_cast<float2*>(scores + (tm * 16 + r0 + 8) * SSTR + tn * 8 + cc) =
                        make_float2(d[2], d[3]);
                }
            }
            __syncthreads();

            // inverse map + per-warp row lists for this chunk
            for (int i = tid; i < NW; i += blockDim.x) warp_row_count[i] = 0;
            __syncthreads();
            for (int i = tid; i < mc; i += blockDim.x) {
                int qrow = blist[c0 + i];
                qpos[qrow] = i;
                int w = qrow >> 5;
                int rp = atomicAdd(&warp_row_count[w], 1);
                warp_rows[w * 32 + rp] = (uint8_t)i;
            }
            __syncthreads();

            if constexpr (SW == 8) {
            // online softmax for rows owned by this warp (4 rows/warp, 8 lanes/row)
            int nrows = warp_row_count[warp];
            int lane8 = lane & 7;
            int grp = lane >> 3;
            for (int ri = 0; ri < nrows; ri += 4) {
                int ridx = ri + grp;
                bool active = ridx < nrows;
                int r = active ? warp_rows[warp * 32 + ridx] : 0;
                int qrow = active ? blist[c0 + r] : 0;
                int fl = active ? bflags[c0 + r] : 0;
                int t = q0 + qrow;
                int w0 = max(0, t + 1 - 64);
                float sc[8];
                #pragma unroll
                for (int i = 0; i < 8; ++i) {
                    int g = bi * 64 + lane8 * 8 + i;
                    bool v = active && (g <= t) && (g < S) && (fl ? true : (g >= w0));
                    float sv = scores[r * SSTR + lane8 * 8 + i];
                    sc[i] = v ? sv * scale : -__int_as_float(0x7f800000);
                }
                float rmax = sc[0];
                #pragma unroll
                for (int i = 1; i < 8; ++i) rmax = fmaxf(rmax, sc[i]);
                #pragma unroll
                for (int off = 4; off > 0; off >>= 1)
                    rmax = fmaxf(rmax, __shfl_xor_sync(0xffffffff, rmax, off, 8));
                float mold = mval[qrow];
                float mnew = fmaxf(mold, rmax);
                float a = (mold == -__int_as_float(0x7f800000)) ? 0.f : __expf(mold - mnew);
                float ps[8];
                float rsum = 0.f;
                #pragma unroll
                for (int i = 0; i < 8; ++i) {
                    ps[i] = (active && sc[i] != -__int_as_float(0x7f800000))
                                ? __expf(sc[i] - mnew) : 0.f;
                    rsum += ps[i];
                }
                #pragma unroll
                for (int off = 4; off > 0; off >>= 1)
                    rsum += __shfl_xor_sync(0xffffffff, rsum, off, 8);
                float lnew = lval[qrow] * a + rsum;
                if (active && lane8 == 0) {
                    mval[qrow] = mnew;
                    lval[qrow] = lnew;
                    alpha[r] = a;
                }
                if (active) {
                    __nv_bfloat162 p0 = __floats2bfloat162_rn(ps[0], ps[1]);
                    __nv_bfloat162 p1 = __floats2bfloat162_rn(ps[2], ps[3]);
                    __nv_bfloat162 p2 = __floats2bfloat162_rn(ps[4], ps[5]);
                    __nv_bfloat162 p3 = __floats2bfloat162_rn(ps[6], ps[7]);
                    int4 packed;
                    packed.x = *reinterpret_cast<unsigned int*>(&p0);
                    packed.y = *reinterpret_cast<unsigned int*>(&p1);
                    packed.z = *reinterpret_cast<unsigned int*>(&p2);
                    packed.w = *reinterpret_cast<unsigned int*>(&p3);
                    *reinterpret_cast<int4*>(P + r * PSTR + lane8 * 8) = packed;
                }
            }
            } else {
            // online softmax for rows owned by this warp (8 rows/warp, 4 lanes/row)
            int nrows = warp_row_count[warp];
            int lane4 = lane & 3;
            int grp = lane >> 2;
            for (int ri = 0; ri < nrows; ri += 8) {
                int ridx = ri + grp;
                bool active = ridx < nrows;
                int r = active ? warp_rows[warp * 32 + ridx] : 0;
                int qrow = active ? blist[c0 + r] : 0;
                int fl = active ? bflags[c0 + r] : 0;
                int t = q0 + qrow;
                int w0 = max(0, t + 1 - 64);
                float sc[16];
                #pragma unroll
                for (int i = 0; i < 16; ++i) {
                    int g = bi * 64 + lane4 * 16 + i;
                    bool v = active && (g <= t) && (g < S) && (fl ? true : (g >= w0));
                    float sv = scores[r * SSTR + lane4 * 16 + i];
                    sc[i] = v ? sv * scale : -__int_as_float(0x7f800000);
                }
                float rmax = sc[0];
                #pragma unroll
                for (int i = 1; i < 16; ++i) rmax = fmaxf(rmax, sc[i]);
                #pragma unroll
                for (int off = 2; off > 0; off >>= 1)
                    rmax = fmaxf(rmax, __shfl_xor_sync(0xffffffff, rmax, off, 4));
                float mold = mval[qrow];
                float mnew = fmaxf(mold, rmax);
                float a = (mold == -__int_as_float(0x7f800000)) ? 0.f : __expf(mold - mnew);
                float ps[16];
                float rsum = 0.f;
                #pragma unroll
                for (int i = 0; i < 16; ++i) {
                    ps[i] = (active && sc[i] != -__int_as_float(0x7f800000))
                                ? __expf(sc[i] - mnew) : 0.f;
                    rsum += ps[i];
                }
                #pragma unroll
                for (int off = 2; off > 0; off >>= 1)
                    rsum += __shfl_xor_sync(0xffffffff, rsum, off, 4);
                float lnew = lval[qrow] * a + rsum;
                if (active && lane4 == 0) {
                    mval[qrow] = mnew;
                    lval[qrow] = lnew;
                    alpha[r] = a;
                }
                if (active) {
                    #pragma unroll
                    for (int h = 0; h < 2; ++h) {
                        __nv_bfloat162 p0 = __floats2bfloat162_rn(ps[h*8+0], ps[h*8+1]);
                        __nv_bfloat162 p1 = __floats2bfloat162_rn(ps[h*8+2], ps[h*8+3]);
                        __nv_bfloat162 p2 = __floats2bfloat162_rn(ps[h*8+4], ps[h*8+5]);
                        __nv_bfloat162 p3 = __floats2bfloat162_rn(ps[h*8+6], ps[h*8+7]);
                        int4 packed;
                        packed.x = *reinterpret_cast<unsigned int*>(&p0);
                        packed.y = *reinterpret_cast<unsigned int*>(&p1);
                        packed.z = *reinterpret_cast<unsigned int*>(&p2);
                        packed.w = *reinterpret_cast<unsigned int*>(&p3);
                        *reinterpret_cast<int4*>(P + r * PSTR + lane4 * 16 + h * 8) = packed;
                    }
                }
            }
            }
            __syncthreads();

            // P V: (mp x 64) @ (64 x D) -> outp (mp x D)
            {
                int ntiles_m = mp / 16;
                int ntiles_n = D / 8;
                int ntiles = ntiles_m * ntiles_n;
                int l = lane;
                int arow = (l & 7) + ((l >> 3) & 1) * 8;
                int acol = ((l >> 4) & 1) * 8;
                int bl = l & 15;
                int bkl = (bl & 7) + ((bl >> 3) & 1) * 8;
                int r0 = l >> 2, cc = (l & 3) * 2;
                for (int tile = warp; tile < ntiles; tile += NW) {
                    int tm = tile / ntiles_n;
                    int tn = tile % ntiles_n;
                    float d[4] = {0.f, 0.f, 0.f, 0.f};
                    for (int k0 = 0; k0 < NTOK; k0 += 16) {
                        uint32_t a[4], b[2];
                        ldmatrix_x4(a[0], a[1], a[2], a[3],
                                    P + (tm * 16 + arow) * PSTR + k0 + acol);
                        ldmatrix_x2_trans(b[0], b[1], Vbuf + (k0 + bkl) * KSTR + tn * 8);
                        mma_m16n8k16(d, a, b);
                    }
                    *reinterpret_cast<float2*>(outp + (tm * 16 + r0) * OSTR + tn * 8 + cc) =
                        make_float2(d[0], d[1]);
                    *reinterpret_cast<float2*>(outp + (tm * 16 + r0 + 8) * OSTR + tn * 8 + cc) =
                        make_float2(d[2], d[3]);
                }
            }
            __syncthreads();

            // online softmax accumulator update for this lane's query
            if (q_valid) {
                int r = qpos[myq];
                if (r >= 0) {
                    float a = alpha[r];
                    #pragma unroll
                    for (int d = 0; d < D; d += 4) {
                        float4 ov = *reinterpret_cast<const float4*>(outp + r * OSTR + d);
                        my_acc[d + 0] = my_acc[d + 0] * a + ov.x;
                        my_acc[d + 1] = my_acc[d + 1] * a + ov.y;
                        my_acc[d + 2] = my_acc[d + 2] * a + ov.z;
                        my_acc[d + 3] = my_acc[d + 3] * a + ov.w;
                    }
                }
            }
            for (int i = tid; i < mc; i += blockDim.x) qpos[blist[c0 + i]] = -1;
            __syncthreads();
        }
    }

    // write output
    if (q_valid) {
        float inv = 1.f / lval[myq];
        #pragma unroll
        for (int d = 0; d < D; d += 8) {
            __nv_bfloat162 p0 = __floats2bfloat162_rn(my_acc[d + 0] * inv, my_acc[d + 1] * inv);
            __nv_bfloat162 p1 = __floats2bfloat162_rn(my_acc[d + 2] * inv, my_acc[d + 3] * inv);
            __nv_bfloat162 p2 = __floats2bfloat162_rn(my_acc[d + 4] * inv, my_acc[d + 5] * inv);
            __nv_bfloat162 p3 = __floats2bfloat162_rn(my_acc[d + 6] * inv, my_acc[d + 7] * inv);
            int4 packed;
            packed.x = *reinterpret_cast<unsigned int*>(&p0);
            packed.y = *reinterpret_cast<unsigned int*>(&p1);
            packed.z = *reinterpret_cast<unsigned int*>(&p2);
            packed.w = *reinterpret_cast<unsigned int*>(&p3);
            *reinterpret_cast<int4*>(O + ((int64_t)bh * S + gq) * D + d) = packed;
        }
    }
}

template<int D, int TQ, int NW, int M_MAX>
__global__ void dense_attn_kernel(
        const __nv_bfloat16* __restrict__ Q,
        const __nv_bfloat16* __restrict__ K,
        const __nv_bfloat16* __restrict__ V,
        const int* __restrict__ sel,
        __nv_bfloat16* __restrict__ O,
        int S, int n_blocks, float scale) {
    constexpr int NTOK = 64;
    constexpr int KSTR = D + 8;
    constexpr int PSTR = NTOK + 8;
    constexpr int SSTR = NTOK + 8;
    constexpr int OSTR = D + 8;
    int bh = blockIdx.y;
    int q0 = blockIdx.x * TQ;
    int tid = threadIdx.x;
    int warp = tid / 32;
    int lane = tid % 32;

    extern __shared__ __nv_bfloat16 smem_bf[];
    __nv_bfloat16* Qs = smem_bf;
    __nv_bfloat16* Kbuf = Qs + TQ * KSTR;
    __nv_bfloat16* Vbuf = Kbuf + NTOK * KSTR;
    float* scores = (float*)(Vbuf + NTOK * KSTR);
    __nv_bfloat16* P = (__nv_bfloat16*)(scores + M_MAX * SSTR);
    float* outp = (float*)(P + M_MAX * PSTR);
    float* alpha = outp + M_MAX * OSTR;
    float* mval = alpha + M_MAX;
    float* lval = mval + TQ;

    // load Q tile
    for (int i = tid; i < TQ * D; i += blockDim.x) {
        int r = i / D, d = i % D;
        int gq = q0 + r;
        Qs[r * KSTR + d] = (gq < S) ? Q[((int64_t)bh * S + gq) * D + d]
                                    : __float2bfloat16(0.f);
    }
    for (int i = tid; i < TQ; i += blockDim.x) {
        mval[i] = -__int_as_float(0x7f800000);
        lval[i] = 0.f;
    }
    float my_acc[D];
    #pragma unroll
    for (int i = 0; i < D; ++i) my_acc[i] = 0.f;
    int myq = warp * 32 + lane;
    int gq = q0 + myq;
    bool q_valid = (myq < TQ) && (gq < S);
    __syncthreads();

    int qend = min(S - 1, q0 + TQ - 1);
    int max_bi = qend / 64;
    int rows_per_warp = M_MAX / NW;
    int grp = lane >> 3;
    int lane8 = lane & 7;

    for (int bi = 0; bi <= max_bi; ++bi) {
        int tstart = bi * 64;
        {
            constexpr int Vv = 8;
            int nvec = NTOK * D / Vv;
            for (int i = tid; i < nvec; i += blockDim.x) {
                int r = (i * Vv) / D, d = (i * Vv) % D;
                int g = tstart + r;
                if (g < S) {
                    cp_async16(Kbuf + r * KSTR + d, K + ((int64_t)bh * S + g) * D + d);
                    cp_async16(Vbuf + r * KSTR + d, V + ((int64_t)bh * S + g) * D + d);
                } else {
                    *reinterpret_cast<int4*>(Kbuf + r * KSTR + d) = make_int4(0,0,0,0);
                    *reinterpret_cast<int4*>(Vbuf + r * KSTR + d) = make_int4(0,0,0,0);
                }
            }
            cp_async_commit();
            cp_async_wait0();
        }
        __syncthreads();

        for (int c0 = 0; c0 < TQ; c0 += M_MAX) {
            int mc = min(M_MAX, TQ - c0);
            int mp = (mc + 15) / 16 * 16;
            // QK^T from Q tile
            {
                int ntiles_m = mp / 16;
                int ntiles_n = NTOK / 8;
                int ntiles = ntiles_m * ntiles_n;
                int l = lane;
                int arow = (l & 7) + ((l >> 3) & 1) * 8;
                int acol = ((l >> 4) & 1) * 8;
                int bl = l & 15;
                int bn = bl & 7;
                int bk = ((bl >> 3) & 1) * 8;
                int r0 = l >> 2, cc = (l & 3) * 2;
                for (int tile = warp; tile < ntiles; tile += NW) {
                    int tm = tile / ntiles_n;
                    int tn = tile % ntiles_n;
                    float d[4] = {0.f, 0.f, 0.f, 0.f};
                    for (int k0 = 0; k0 < D; k0 += 16) {
                        uint32_t a[4], b[2];
                        ldmatrix_x4(a[0], a[1], a[2], a[3],
                                    Qs + (c0 + tm * 16 + arow) * KSTR + k0 + acol);
                        ldmatrix_x2(b[0], b[1], Kbuf + (tn * 8 + bn) * KSTR + k0 + bk);
                        mma_m16n8k16(d, a, b);
                    }
                    *reinterpret_cast<float2*>(scores + (tm * 16 + r0) * SSTR + tn * 8 + cc) =
                        make_float2(d[0], d[1]);
                    *reinterpret_cast<float2*>(scores + (tm * 16 + r0 + 8) * SSTR + tn * 8 + cc) =
                        make_float2(d[2], d[3]);
                }
            }
            __syncthreads();

            // softmax over this block for rows in this chunk
            for (int ri = 0; ri < rows_per_warp; ri += 4) {
                int r = warp * rows_per_warp + ri + grp;
                bool active = (ri + grp) < rows_per_warp;
                int ql = c0 + r;
                int t = q0 + ql;
                bool row_valid = active && (ql < TQ) && (t < S);
                int w0 = max(0, t + 1 - 64);
                bool is_sel = false;
                if (row_valid) {
                    const int* sp = sel + ((int64_t)bh * S + t) * 8;
                    #pragma unroll
                    for (int i = 0; i < 8; ++i) if (sp[i] == bi) is_sel = true;
                }
                float sc[8];
                #pragma unroll
                for (int i = 0; i < 8; ++i) {
                    int g = bi * 64 + lane8 * 8 + i;
                    bool v = row_valid && (g <= t) && (g < S) && (is_sel || (g >= w0));
                    float sv = scores[r * SSTR + lane8 * 8 + i];
                    sc[i] = v ? sv * scale : -__int_as_float(0x7f800000);
                }
                float rmax = sc[0];
                #pragma unroll
                for (int i = 1; i < 8; ++i) rmax = fmaxf(rmax, sc[i]);
                #pragma unroll
                for (int off = 4; off > 0; off >>= 1)
                    rmax = fmaxf(rmax, __shfl_xor_sync(0xffffffff, rmax, off, 8));
                float mold = mval[ql];
                float mnew = fmaxf(mold, rmax);
                float a = (mold == -__int_as_float(0x7f800000)) ? 0.f : __expf(mold - mnew);
                float ps[8];
                float rsum = 0.f;
                #pragma unroll
                for (int i = 0; i < 8; ++i) {
                    ps[i] = (row_valid && sc[i] != -__int_as_float(0x7f800000))
                                ? __expf(sc[i] - mnew) : 0.f;
                    rsum += ps[i];
                }
                #pragma unroll
                for (int off = 4; off > 0; off >>= 1)
                    rsum += __shfl_xor_sync(0xffffffff, rsum, off, 8);
                float lnew = lval[ql] * a + rsum;
                if (row_valid && lane8 == 0) {
                    mval[ql] = mnew;
                    lval[ql] = lnew;
                    alpha[r] = a;
                }
                if (row_valid) {
                    __nv_bfloat162 p0 = __floats2bfloat162_rn(ps[0], ps[1]);
                    __nv_bfloat162 p1 = __floats2bfloat162_rn(ps[2], ps[3]);
                    __nv_bfloat162 p2 = __floats2bfloat162_rn(ps[4], ps[5]);
                    __nv_bfloat162 p3 = __floats2bfloat162_rn(ps[6], ps[7]);
                    int4 packed;
                    packed.x = *reinterpret_cast<unsigned int*>(&p0);
                    packed.y = *reinterpret_cast<unsigned int*>(&p1);
                    packed.z = *reinterpret_cast<unsigned int*>(&p2);
                    packed.w = *reinterpret_cast<unsigned int*>(&p3);
                    *reinterpret_cast<int4*>(P + r * PSTR + lane8 * 8) = packed;
                } else {
                    *reinterpret_cast<int4*>(P + r * PSTR + lane8 * 8) = make_int4(0,0,0,0);
                }
            }
            __syncthreads();

            // P V
            {
                int ntiles_m = mp / 16;
                int ntiles_n = D / 8;
                int ntiles = ntiles_m * ntiles_n;
                int l = lane;
                int arow = (l & 7) + ((l >> 3) & 1) * 8;
                int acol = ((l >> 4) & 1) * 8;
                int bl = l & 15;
                int bkl = (bl & 7) + ((bl >> 3) & 1) * 8;
                int r0 = l >> 2, cc = (l & 3) * 2;
                for (int tile = warp; tile < ntiles; tile += NW) {
                    int tm = tile / ntiles_n;
                    int tn = tile % ntiles_n;
                    float d[4] = {0.f, 0.f, 0.f, 0.f};
                    for (int k0 = 0; k0 < NTOK; k0 += 16) {
                        uint32_t a[4], b[2];
                        ldmatrix_x4(a[0], a[1], a[2], a[3],
                                    P + (tm * 16 + arow) * PSTR + k0 + acol);
                        ldmatrix_x2_trans(b[0], b[1], Vbuf + (k0 + bkl) * KSTR + tn * 8);
                        mma_m16n8k16(d, a, b);
                    }
                    *reinterpret_cast<float2*>(outp + (tm * 16 + r0) * OSTR + tn * 8 + cc) =
                        make_float2(d[0], d[1]);
                    *reinterpret_cast<float2*>(outp + (tm * 16 + r0 + 8) * OSTR + tn * 8 + cc) =
                        make_float2(d[2], d[3]);
                }
            }
            __syncthreads();

            // accumulator update
            if (q_valid && myq >= c0 && myq < c0 + mc) {
                int r = myq - c0;
                float a = alpha[r];
                #pragma unroll
                for (int d = 0; d < D; d += 4) {
                    float4 ov = *reinterpret_cast<const float4*>(outp + r * OSTR + d);
                    my_acc[d + 0] = my_acc[d + 0] * a + ov.x;
                    my_acc[d + 1] = my_acc[d + 1] * a + ov.y;
                    my_acc[d + 2] = my_acc[d + 2] * a + ov.z;
                    my_acc[d + 3] = my_acc[d + 3] * a + ov.w;
                }
            }
            __syncthreads();
        }
    }

    if (q_valid) {
        float inv = 1.f / lval[myq];
        #pragma unroll
        for (int d = 0; d < D; d += 8) {
            __nv_bfloat162 p0 = __floats2bfloat162_rn(my_acc[d + 0] * inv, my_acc[d + 1] * inv);
            __nv_bfloat162 p1 = __floats2bfloat162_rn(my_acc[d + 2] * inv, my_acc[d + 3] * inv);
            __nv_bfloat162 p2 = __floats2bfloat162_rn(my_acc[d + 4] * inv, my_acc[d + 5] * inv);
            __nv_bfloat162 p3 = __floats2bfloat162_rn(my_acc[d + 6] * inv, my_acc[d + 7] * inv);
            int4 packed;
            packed.x = *reinterpret_cast<unsigned int*>(&p0);
            packed.y = *reinterpret_cast<unsigned int*>(&p1);
            packed.z = *reinterpret_cast<unsigned int*>(&p2);
            packed.w = *reinterpret_cast<unsigned int*>(&p3);
            *reinterpret_cast<int4*>(O + ((int64_t)bh * S + gq) * D + d) = packed;
        }
    }
}

// ---------------------------------------------------------------------------
// host entry points
// ---------------------------------------------------------------------------
void block_stats(torch::Tensor K, torch::Tensor kmean, torch::Tensor kprefix) {
    cudaStream_t stream = at::cuda::getCurrentCUDAStream();
    int B = K.size(0), H = K.size(1), S = K.size(2), D = K.size(3);
    int n_blocks = (S + 63) / 64;
    dim3 grid(n_blocks, B * H);
    block_stats_kernel<<<grid, D, 0, stream>>>(reinterpret_cast<const __nv_bfloat16*>(K.data_ptr()),
                                    kmean.data_ptr<float>(), kprefix.data_ptr<float>(),
                                    S, D, n_blocks);
}

void block_scores(torch::Tensor Q, torch::Tensor kmean, torch::Tensor scores,
                  float scale) {
    cudaStream_t stream = at::cuda::getCurrentCUDAStream();
    int B = Q.size(0), H = Q.size(1), S = Q.size(2), D = Q.size(3);
    int n_blocks = (S + 63) / 64;
    int TQ = 64;
    int TR, TB, DCHUNK, nthreads;
    TR = 4; TB = 4; DCHUNK = 16;
    int KCHUNK = 128;
    int nty = (min(KCHUNK, n_blocks) + TB - 1) / TB;
    int ntx = TQ / TR;
    nthreads = ((ntx * nty + 31) / 32) * 32;
    int QSTR = D + 8, KSTR = D + 8;
    size_t smem = TQ * QSTR * sizeof(__nv_bfloat16) + KCHUNK * KSTR * sizeof(float);
    dim3 grid((S + TQ - 1) / TQ, B * H);
    if (D == 64) {
        if (n_blocks <= 64) {
            auto fn = block_scores_kernel<4,4,16,128,64>;
            static size_t attr_smem = 0;
            if (smem > attr_smem) {
                cudaFuncSetAttribute(fn, cudaFuncAttributeMaxDynamicSharedMemorySize, smem);
                attr_smem = smem;
            }
            fn<<<grid, nthreads, smem, stream>>>(
                reinterpret_cast<const __nv_bfloat16*>(Q.data_ptr()),
                kmean.data_ptr<float>(), scores.data_ptr<float>(), S, n_blocks, scale);
        } else {
            auto fn = block_scores_kernel<4,4,16,128,64>;
            static size_t attr_smem = 0;
            if (smem > attr_smem) {
                cudaFuncSetAttribute(fn, cudaFuncAttributeMaxDynamicSharedMemorySize, smem);
                attr_smem = smem;
            }
            fn<<<grid, nthreads, smem, stream>>>(
                reinterpret_cast<const __nv_bfloat16*>(Q.data_ptr()),
                kmean.data_ptr<float>(), scores.data_ptr<float>(), S, n_blocks, scale);
        }
    } else {
        if (n_blocks <= 64) {
            auto fn = block_scores_kernel<4,4,16,128,128>;
            static size_t attr_smem = 0;
            if (smem > attr_smem) {
                cudaFuncSetAttribute(fn, cudaFuncAttributeMaxDynamicSharedMemorySize, smem);
                attr_smem = smem;
            }
            fn<<<grid, nthreads, smem, stream>>>(
                reinterpret_cast<const __nv_bfloat16*>(Q.data_ptr()),
                kmean.data_ptr<float>(), scores.data_ptr<float>(), S, n_blocks, scale);
        } else {
            auto fn = block_scores_kernel<4,4,16,128,128>;
            static size_t attr_smem = 0;
            if (smem > attr_smem) {
                cudaFuncSetAttribute(fn, cudaFuncAttributeMaxDynamicSharedMemorySize, smem);
                attr_smem = smem;
            }
            fn<<<grid, nthreads, smem, stream>>>(
                reinterpret_cast<const __nv_bfloat16*>(Q.data_ptr()),
                kmean.data_ptr<float>(), scores.data_ptr<float>(), S, n_blocks, scale);
        }
    }
}

void topk(torch::Tensor scores, torch::Tensor kprefix, torch::Tensor Q,
          torch::Tensor sel, float scale) {
    cudaStream_t stream = at::cuda::getCurrentCUDAStream();
    int B = Q.size(0), H = Q.size(1), S = Q.size(2), D = Q.size(3);
    int n_blocks = (S + 63) / 64;
    dim3 grid((S + 63) / 64, B * H);
    if (D == 64) {
        topk_kernel<64><<<grid, 64, 0, stream>>>(
            scores.data_ptr<float>(), kprefix.data_ptr<float>(),
            reinterpret_cast<const __nv_bfloat16*>(Q.data_ptr()),
            sel.data_ptr<int>(), S, n_blocks, scale);
    } else {
        topk_kernel<128><<<grid, 64, 0, stream>>>(
            scores.data_ptr<float>(), kprefix.data_ptr<float>(),
            reinterpret_cast<const __nv_bfloat16*>(Q.data_ptr()),
            sel.data_ptr<int>(), S, n_blocks, scale);
    }
}


static void pick_config(int n_blocks, int D, int& TQ, int& M_MAX, int tq_override) {
    if (tq_override > 0) {
        TQ = tq_override;
        M_MAX = (D == 64) ? 32 : 16;
        return;
    }
    if (D == 64) {
        if (n_blocks <= 32) { TQ = 256; M_MAX = 64; }
        else if (n_blocks <= 48) { TQ = 256; M_MAX = 64; }
        else { TQ = 512; M_MAX = 64; }
    } else {
        if (n_blocks <= 32) { TQ = 256; M_MAX = 32; }
        else { TQ = 384; M_MAX = 32; }
    }
}

void sparse_attn(torch::Tensor Q, torch::Tensor K, torch::Tensor V,
                 torch::Tensor sel, torch::Tensor O, float scale, int tq_override) {
    cudaStream_t stream = at::cuda::getCurrentCUDAStream();
    int B = Q.size(0), H = Q.size(1), S = Q.size(2), D = Q.size(3);
    int n_blocks = (S + 63) / 64;
    if (false && n_blocks <= 32 && tq_override == 0) {
        int TQ = (D == 64) ? 256 : 128;
        int MM = (D == 64) ? 32 : 16;
        int NW = TQ / 32;
        size_t smem = TQ * (D + 8) * sizeof(__nv_bfloat16)
                    + 2 * 64 * (D + 8) * sizeof(__nv_bfloat16)
                    + MM * (64 + 8) * sizeof(float)
                    + MM * (64 + 8) * sizeof(__nv_bfloat16)
                    + MM * (D + 8) * sizeof(float)
                    + MM * sizeof(float)
                    + 2 * TQ * sizeof(float);
        dim3 grid((S + TQ - 1) / TQ, B * H);
        int nthreads = NW * 32;
        if (D == 64) {
            auto fn = dense_attn_kernel<64,256,8,32>;
            static size_t attr_smem = 0;
            if (smem > attr_smem) {
                cudaFuncSetAttribute(fn, cudaFuncAttributeMaxDynamicSharedMemorySize, smem);
                attr_smem = smem;
            }
            fn<<<grid, nthreads, smem, stream>>>(
                reinterpret_cast<const __nv_bfloat16*>(Q.data_ptr()),
                reinterpret_cast<const __nv_bfloat16*>(K.data_ptr()),
                reinterpret_cast<const __nv_bfloat16*>(V.data_ptr()),
                sel.data_ptr<int>(), reinterpret_cast<__nv_bfloat16*>(O.data_ptr()),
                S, n_blocks, scale);
        } else {
            auto fn = dense_attn_kernel<128,128,4,16>;
            static size_t attr_smem = 0;
            if (smem > attr_smem) {
                cudaFuncSetAttribute(fn, cudaFuncAttributeMaxDynamicSharedMemorySize, smem);
                attr_smem = smem;
            }
            fn<<<grid, nthreads, smem, stream>>>(
                reinterpret_cast<const __nv_bfloat16*>(Q.data_ptr()),
                reinterpret_cast<const __nv_bfloat16*>(K.data_ptr()),
                reinterpret_cast<const __nv_bfloat16*>(V.data_ptr()),
                sel.data_ptr<int>(), reinterpret_cast<__nv_bfloat16*>(O.data_ptr()),
                S, n_blocks, scale);
        }
        return;
    }
    int TQ, M_MAX;
    pick_config(n_blocks, D, TQ, M_MAX, tq_override);
    int NW = TQ / 32;
    size_t smem = 0;
    smem += 2 * 64 * (D + 8) * sizeof(__nv_bfloat16); // K,V
    smem += M_MAX * (D + 8) * sizeof(__nv_bfloat16);  // Qc
    smem += M_MAX * (64 + 8) * sizeof(float);         // scores
    smem += M_MAX * (64 + 8) * sizeof(__nv_bfloat16); // P
    smem += M_MAX * (D + 8) * sizeof(float);          // outp
    smem += M_MAX * sizeof(float);                    // alpha
    smem += TQ * 10 * sizeof(uint16_t) + TQ * 10 * sizeof(uint8_t); // work lists
    smem += (n_blocks + 1) * sizeof(int) + n_blocks * sizeof(int);  // offsets/cursor
    smem += TQ * sizeof(int);                         // qpos
    smem += 2 * TQ * sizeof(float);                   // mval/lval
    smem += NW * sizeof(int) + NW * 32 * sizeof(uint8_t); // warp rows
    dim3 grid((S + TQ - 1) / TQ, B * H);
    int nthreads = NW * 32;
    if (D == 64) {
        if (TQ == 128) {
            auto fn = sparse_attn_kernel<64,128,4,32,4>;
            static size_t attr_smem = 0;
            if (smem > attr_smem) {
                cudaFuncSetAttribute(fn, cudaFuncAttributeMaxDynamicSharedMemorySize, smem);
                attr_smem = smem;
            }
            fn<<<grid, nthreads, smem, stream>>>(
                reinterpret_cast<const __nv_bfloat16*>(Q.data_ptr()),
                reinterpret_cast<const __nv_bfloat16*>(K.data_ptr()),
                reinterpret_cast<const __nv_bfloat16*>(V.data_ptr()),
                sel.data_ptr<int>(), reinterpret_cast<__nv_bfloat16*>(O.data_ptr()),
                S, n_blocks, scale);
        } else if (TQ == 256) {
            if (M_MAX == 64) {
                auto fn = sparse_attn_kernel<64,256,8,64,4>;
                static size_t attr_smem = 0;
                if (smem > attr_smem) {
                    cudaFuncSetAttribute(fn, cudaFuncAttributeMaxDynamicSharedMemorySize, smem);
                    attr_smem = smem;
                }
                fn<<<grid, nthreads, smem, stream>>>(
                    reinterpret_cast<const __nv_bfloat16*>(Q.data_ptr()),
                    reinterpret_cast<const __nv_bfloat16*>(K.data_ptr()),
                    reinterpret_cast<const __nv_bfloat16*>(V.data_ptr()),
                    sel.data_ptr<int>(), reinterpret_cast<__nv_bfloat16*>(O.data_ptr()),
                    S, n_blocks, scale);
            } else {
                auto fn = sparse_attn_kernel<64,256,8,32,4>;
                static size_t attr_smem = 0;
                if (smem > attr_smem) {
                    cudaFuncSetAttribute(fn, cudaFuncAttributeMaxDynamicSharedMemorySize, smem);
                    attr_smem = smem;
                }
                fn<<<grid, nthreads, smem, stream>>>(
                    reinterpret_cast<const __nv_bfloat16*>(Q.data_ptr()),
                    reinterpret_cast<const __nv_bfloat16*>(K.data_ptr()),
                    reinterpret_cast<const __nv_bfloat16*>(V.data_ptr()),
                    sel.data_ptr<int>(), reinterpret_cast<__nv_bfloat16*>(O.data_ptr()),
                    S, n_blocks, scale);
            }
        } else if (TQ == 576) {
            auto fn = sparse_attn_kernel<64,576,18,64,8>;
            static size_t attr_smem = 0;
            if (smem > attr_smem) {
                cudaFuncSetAttribute(fn, cudaFuncAttributeMaxDynamicSharedMemorySize, smem);
                attr_smem = smem;
            }
            fn<<<grid, nthreads, smem, stream>>>(
                reinterpret_cast<const __nv_bfloat16*>(Q.data_ptr()),
                reinterpret_cast<const __nv_bfloat16*>(K.data_ptr()),
                reinterpret_cast<const __nv_bfloat16*>(V.data_ptr()),
                sel.data_ptr<int>(), reinterpret_cast<__nv_bfloat16*>(O.data_ptr()),
                S, n_blocks, scale);
        } else if (TQ == 512) {
            if (M_MAX == 64) {
                auto fn = sparse_attn_kernel<64,512,16,64,8>;
                static size_t attr_smem = 0;
                if (smem > attr_smem) {
                    cudaFuncSetAttribute(fn, cudaFuncAttributeMaxDynamicSharedMemorySize, smem);
                    attr_smem = smem;
                }
                fn<<<grid, nthreads, smem, stream>>>(
                    reinterpret_cast<const __nv_bfloat16*>(Q.data_ptr()),
                    reinterpret_cast<const __nv_bfloat16*>(K.data_ptr()),
                    reinterpret_cast<const __nv_bfloat16*>(V.data_ptr()),
                    sel.data_ptr<int>(), reinterpret_cast<__nv_bfloat16*>(O.data_ptr()),
                    S, n_blocks, scale);
            } else {
                auto fn = sparse_attn_kernel<64,512,16,32,8>;
                static size_t attr_smem = 0;
                if (smem > attr_smem) {
                    cudaFuncSetAttribute(fn, cudaFuncAttributeMaxDynamicSharedMemorySize, smem);
                    attr_smem = smem;
                }
                fn<<<grid, nthreads, smem, stream>>>(
                    reinterpret_cast<const __nv_bfloat16*>(Q.data_ptr()),
                    reinterpret_cast<const __nv_bfloat16*>(K.data_ptr()),
                    reinterpret_cast<const __nv_bfloat16*>(V.data_ptr()),
                    sel.data_ptr<int>(), reinterpret_cast<__nv_bfloat16*>(O.data_ptr()),
                    S, n_blocks, scale);
            }
        } else {
            auto fn = sparse_attn_kernel<64,1024,32,32,8>;
            static size_t attr_smem = 0;
            if (smem > attr_smem) {
                cudaFuncSetAttribute(fn, cudaFuncAttributeMaxDynamicSharedMemorySize, smem);
                attr_smem = smem;
            }
            fn<<<grid, nthreads, smem, stream>>>(
                reinterpret_cast<const __nv_bfloat16*>(Q.data_ptr()),
                reinterpret_cast<const __nv_bfloat16*>(K.data_ptr()),
                reinterpret_cast<const __nv_bfloat16*>(V.data_ptr()),
                sel.data_ptr<int>(), reinterpret_cast<__nv_bfloat16*>(O.data_ptr()),
                S, n_blocks, scale);
        }
    } else {
        if (TQ == 128) {
            auto fn = sparse_attn_kernel<128,128,4,16,4>;
            static size_t attr_smem = 0;
            if (smem > attr_smem) {
                cudaFuncSetAttribute(fn, cudaFuncAttributeMaxDynamicSharedMemorySize, smem);
                attr_smem = smem;
            }
            fn<<<grid, nthreads, smem, stream>>>(
                reinterpret_cast<const __nv_bfloat16*>(Q.data_ptr()),
                reinterpret_cast<const __nv_bfloat16*>(K.data_ptr()),
                reinterpret_cast<const __nv_bfloat16*>(V.data_ptr()),
                sel.data_ptr<int>(), reinterpret_cast<__nv_bfloat16*>(O.data_ptr()),
                S, n_blocks, scale);
        } else if (TQ == 256) {
            if (M_MAX == 32) {
                auto fn = sparse_attn_kernel<128,256,8,32,4>;
                static size_t attr_smem = 0;
                if (smem > attr_smem) {
                    cudaFuncSetAttribute(fn, cudaFuncAttributeMaxDynamicSharedMemorySize, smem);
                    attr_smem = smem;
                }
                fn<<<grid, nthreads, smem, stream>>>(
                    reinterpret_cast<const __nv_bfloat16*>(Q.data_ptr()),
                    reinterpret_cast<const __nv_bfloat16*>(K.data_ptr()),
                    reinterpret_cast<const __nv_bfloat16*>(V.data_ptr()),
                    sel.data_ptr<int>(), reinterpret_cast<__nv_bfloat16*>(O.data_ptr()),
                    S, n_blocks, scale);
            } else {
                auto fn = sparse_attn_kernel<128,256,8,16,4>;
                static size_t attr_smem = 0;
                if (smem > attr_smem) {
                    cudaFuncSetAttribute(fn, cudaFuncAttributeMaxDynamicSharedMemorySize, smem);
                    attr_smem = smem;
                }
                fn<<<grid, nthreads, smem, stream>>>(
                    reinterpret_cast<const __nv_bfloat16*>(Q.data_ptr()),
                    reinterpret_cast<const __nv_bfloat16*>(K.data_ptr()),
                    reinterpret_cast<const __nv_bfloat16*>(V.data_ptr()),
                    sel.data_ptr<int>(), reinterpret_cast<__nv_bfloat16*>(O.data_ptr()),
                    S, n_blocks, scale);
            }
        } else if (TQ == 384) {
            auto fn = sparse_attn_kernel<128,384,12,32,8>;
            static size_t attr_smem = 0;
            if (smem > attr_smem) {
                cudaFuncSetAttribute(fn, cudaFuncAttributeMaxDynamicSharedMemorySize, smem);
                attr_smem = smem;
            }
            fn<<<grid, nthreads, smem, stream>>>(
                reinterpret_cast<const __nv_bfloat16*>(Q.data_ptr()),
                reinterpret_cast<const __nv_bfloat16*>(K.data_ptr()),
                reinterpret_cast<const __nv_bfloat16*>(V.data_ptr()),
                sel.data_ptr<int>(), reinterpret_cast<__nv_bfloat16*>(O.data_ptr()),
                S, n_blocks, scale);
        } else if (TQ == 512) {
            if (M_MAX == 32) {
                auto fn = sparse_attn_kernel<128,512,16,32,8>;
                static size_t attr_smem = 0;
                if (smem > attr_smem) {
                    cudaFuncSetAttribute(fn, cudaFuncAttributeMaxDynamicSharedMemorySize, smem);
                    attr_smem = smem;
                }
                fn<<<grid, nthreads, smem, stream>>>(
                    reinterpret_cast<const __nv_bfloat16*>(Q.data_ptr()),
                    reinterpret_cast<const __nv_bfloat16*>(K.data_ptr()),
                    reinterpret_cast<const __nv_bfloat16*>(V.data_ptr()),
                    sel.data_ptr<int>(), reinterpret_cast<__nv_bfloat16*>(O.data_ptr()),
                    S, n_blocks, scale);
            } else {
                auto fn = sparse_attn_kernel<128,512,16,16,8>;
                static size_t attr_smem = 0;
                if (smem > attr_smem) {
                    cudaFuncSetAttribute(fn, cudaFuncAttributeMaxDynamicSharedMemorySize, smem);
                    attr_smem = smem;
                }
                fn<<<grid, nthreads, smem, stream>>>(
                    reinterpret_cast<const __nv_bfloat16*>(Q.data_ptr()),
                    reinterpret_cast<const __nv_bfloat16*>(K.data_ptr()),
                    reinterpret_cast<const __nv_bfloat16*>(V.data_ptr()),
                    sel.data_ptr<int>(), reinterpret_cast<__nv_bfloat16*>(O.data_ptr()),
                    S, n_blocks, scale);
            }
        } else {
            auto fn = sparse_attn_kernel<128,768,24,16,8>;
            static size_t attr_smem = 0;
            if (smem > attr_smem) {
                cudaFuncSetAttribute(fn, cudaFuncAttributeMaxDynamicSharedMemorySize, smem);
                attr_smem = smem;
            }
            fn<<<grid, nthreads, smem, stream>>>(
                reinterpret_cast<const __nv_bfloat16*>(Q.data_ptr()),
                reinterpret_cast<const __nv_bfloat16*>(K.data_ptr()),
                reinterpret_cast<const __nv_bfloat16*>(V.data_ptr()),
                sel.data_ptr<int>(), reinterpret_cast<__nv_bfloat16*>(O.data_ptr()),
                S, n_blocks, scale);
        }
    }
}
"""

_CPP_SRC = r"""
#include <torch/extension.h>
void block_stats(torch::Tensor K, torch::Tensor kmean, torch::Tensor kprefix);
void block_scores(torch::Tensor Q, torch::Tensor kmean, torch::Tensor scores,
                  float scale);
void topk(torch::Tensor scores, torch::Tensor kprefix, torch::Tensor Q,
          torch::Tensor sel, float scale);
void sparse_attn(torch::Tensor Q, torch::Tensor K, torch::Tensor V,
                 torch::Tensor sel, torch::Tensor O, float scale, int tq_override);
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("block_stats", &block_stats);
    m.def("block_scores", &block_scores);
    m.def("topk", &topk);
    m.def("sparse_attn", &sparse_attn);
}
"""

_ext = None


def _get_ext():
    global _ext
    if _ext is None:
        _ext = load_inline(
            name="nsa_cuda_ext",
            cpp_sources=[_CPP_SRC],
            cuda_sources=[_CUDA_SRC],
            extra_cuda_cflags=["-O3", "-arch=sm_120a"],
            verbose=False,
        )
    return _ext


class Model(nn.Module):
    def __init__(self, B: int, H: int, S: int, D: int):
        super().__init__()
        self.B, self.H, self.S, self.D = B, H, S, D
        self.register_buffer("_dummy", torch.zeros(1, dtype=torch.bfloat16))
        self.scale = 1.0 / math.sqrt(D)
        self._graph_cache = {}

    def _run_kernels(self, q, k, v, kmean, kprefix, scores, sel, out):
        ext = _get_ext()
        ext.block_stats(k, kmean, kprefix)
        ext.block_scores(q, kmean, scores, self.scale)
        ext.topk(scores, kprefix, q, sel, self.scale)
        ext.sparse_attn(q, k, v, sel, out, self.scale, 0)

    def forward(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor:
        B, H, S, D = q.shape
        n_blocks = (S + BLOCK_SIZE - 1) // BLOCK_SIZE
        key = (q.data_ptr(), k.data_ptr(), v.data_ptr(), B, H, S, D)
        entry = self._graph_cache.get(key)
        if entry is None:
            kmean = torch.empty((B, H, n_blocks, D), device=q.device, dtype=torch.float32)
            kprefix = torch.empty((B, H, S, D), device=q.device, dtype=torch.float32)
            scores = torch.empty((B, H, S, n_blocks), device=q.device, dtype=torch.float32)
            sel = torch.empty((B, H, S, TOP_N_BLOCKS), device=q.device, dtype=torch.int32)
            out = torch.empty((B, H, S, D), device=q.device, dtype=torch.bfloat16)
            # Warm up (also configures kernel attributes) before capture.
            self._run_kernels(q, k, v, kmean, kprefix, scores, sel, out)
            g = torch.cuda.CUDAGraph()
            with torch.cuda.graph(g):
                self._run_kernels(q, k, v, kmean, kprefix, scores, sel, out)
            entry = (g, out, kmean, kprefix, scores, sel)
            self._graph_cache[key] = entry
        else:
            g, out = entry[0], entry[1]
            g.replay()
        return out


def get_init_inputs():
    return [1, 16, 1024, 64]


def get_inputs():
    q = torch.randn(1, 16, 1024, 64, dtype=torch.bfloat16)
    k = torch.randn(1, 16, 1024, 64, dtype=torch.bfloat16)
    v = torch.randn(1, 16, 1024, 64, dtype=torch.bfloat16)
    return [q, k, v]

20261202_032942_ergo-codex_global.amazon.ergo-1.0_02_deepseek_nsa