KernelBench cuda · RTX PRO 6000

DeepSeek NSA GPT-6.2 Astra

0.123 msgeomean latency across six shapes · lower is better

manually audited: clean

GPT-6.2 Astra wrote a key-stationary NSA pipeline in one hour: K/V pre-packed into tensor-core fragment order, block selection scored on tensor cores with fp32-class TF32 hi+lo block means and the reference tie rule, each selected 64-key block attended once for every query that chose it, then a log-sum-exp merge. 0.123 ms geomean, no caches or graphs.

harnesscodexagent session1h 5mtotal wall1h 11mcheck5mbenchmark2soutput tokens44,845gpu-lock wait8mgpu-lock held10mregimecompute

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

1×16×2048×640.071 ms
1×16×4127×640.147 ms
1×8×8192×640.168 ms
1×8×8191×1280.284 ms
4×8×1024×640.064 ms
2×8×3000×640.110 ms

geomean(0.071 ms · 0.147 ms · 0.168 ms · 0.284 ms · 0.064 ms · 0.110 ms) = 0.123 ms

Kernel source (redacted)
"""Block-selected causal attention on CUDA."""
from functools import lru_cache

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


_CUDA = r"""
#include <ATen/ATen.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAGuard.h>
#include <c10/cuda/CUDAException.h>
#include <cuda_runtime.h>
#include <math_constants.h>
#include <cuda_bf16.h>

using bf = __nv_bfloat16;
constexpr unsigned FULL = 0xffffffffu;
constexpr int SLOTS = 10;

__device__ __forceinline__ unsigned pair_bf(float a, float b) {
    __nv_bfloat162 x = __floats2bfloat162_rn(a, b);
    return reinterpret_cast<unsigned &>(x);
}
__device__ __forceinline__ unsigned pair_raw(bf a, bf b) {
    return unsigned(__bfloat16_as_ushort(a)) | (unsigned(__bfloat16_as_ushort(b)) << 16);
}
__device__ __forceinline__ void mma(float (&c)[4], unsigned a0, unsigned a1, unsigned a2, unsigned a3,
                                    unsigned b0, unsigned b1) {
    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};"
                 : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3])
                 : "r"(a0), "r"(a1), "r"(a2), "r"(a3), "r"(b0), "r"(b1));
}

__device__ __forceinline__ unsigned tf32(float x) {
    unsigned u;
    asm("cvt.rna.tf32.f32 %0, %1;" : "=r"(u) : "f"(x));
    return u;
}

template <int D>
__global__ void prepare(const bf *q, const bf *k, const bf *v, uint4 *kp, uint4 *vp, uint4 *means,
                        float *current, int S, int N) {
    int b = blockIdx.x, h = blockIdx.y, tid = threadIdx.x;
    int warp = tid / 32, lane = tid % 32;
    size_t base = (size_t(h) * S + b * 64) * D;
    int valid = min(64, S - b * 64);
    __shared__ __align__(16) bf tile[64][D + 8];
    __shared__ float sums[8][D];
// Pack both operands in the register order of a 16-by-16 tensor core tile.
#pragma unroll
    for (int operand = 0; operand < 2; operand++) {
        for (int i = tid; i < 64 * D / 8; i += 256) {
            int r = i / (D / 8), c = (i % (D / 8)) * 8;
            uint4 u = make_uint4(0, 0, 0, 0);
            if (r < valid)
                u = *reinterpret_cast<const uint4 *>((operand == 0 ? v : k) + base + r * D + c);
            *reinterpret_cast<uint4 *>(&tile[r][c]) = u;
        }
        __syncthreads();
        for (int i = tid; i < 64 * D / 8; i += 256) {
            int f = i / 32, g = lane / 4, p = (lane % 4) * 2;
            if (operand == 0) {
                int r = (f / (D / 16)) * 16 + p, c = (f % (D / 16)) * 16 + g;
                vp[(size_t(h) * N + b) * (64 * D / 8) + i] = make_uint4(
                    pair_raw(tile[r][c], tile[r + 1][c]), pair_raw(tile[r + 8][c], tile[r + 9][c]),
                    pair_raw(tile[r][c + 8], tile[r + 1][c + 8]),
                    pair_raw(tile[r + 8][c + 8], tile[r + 9][c + 8]));
            } else {
                int r = (f % 4) * 16 + g, c = (f / 4) * 16 + p;
                kp[(size_t(h) * N + b) * (64 * D / 8) + i] = make_uint4(
                    pair_raw(tile[r][c], tile[r][c + 1]), pair_raw(tile[r][c + 8], tile[r][c + 9]),
                    pair_raw(tile[r + 8][c], tile[r + 8][c + 1]),
                    pair_raw(tile[r + 8][c + 8], tile[r + 8][c + 9]));
            }
        }
        __syncthreads();
    }
    // Prefix sums supply the mean for the query's own partial block.
    // The common 1/sqrt(D) factor can be omitted during ranking.
    float prefix[D / 32];
#pragma unroll
    for (int j = 0; j < D / 32; j++) {
        float s = 0;
#pragma unroll
        for (int r = 0; r < 8; r++)
            s += __bfloat162float(tile[8 * warp + r][lane + 32 * j]);
        sums[warp][lane + 32 * j] = s;
    }
    __syncthreads();
#pragma unroll
    for (int j = 0; j < D / 32; j++) {
        float s = 0;
        for (int w = 0; w < warp; w++)
            s += sums[w][lane + 32 * j];
        prefix[j] = s;
        if (warp == 7) {
            int d = lane + 32 * j;
            float mean = (s + sums[7][d]) * (1.f / 64);
            // A high part and a residual preserve close block rankings.
            unsigned hi = tf32(mean), lo = tf32(mean - __uint_as_float(hi));
            int fragment = ((h * ((N + 7) / 8) + b / 8) * (D / 8) + d / 8) * 32 + (b % 8) * 4 + d % 4;
            reinterpret_cast<uint2 *>(means + fragment)[(d % 8) / 4] = make_uint2(hi, lo);
        }
    }
#pragma unroll
    for (int r = 0; r < 8; r++) {
        int row = warp * 8 + r;
        if (row < valid) {
            float dot = 0;
#pragma unroll
            for (int j = 0; j < D / 32; j++) {
                prefix[j] += __bfloat162float(tile[row][lane + 32 * j]);
                dot = fmaf(prefix[j], __bfloat162float(q[base + row * D + lane + 32 * j]), dot);
            }
#pragma unroll
            for (int delta = 16; delta; delta /= 2)
                dot += __shfl_down_sync(FULL, dot, delta);
            if (lane == 0)
                current[h * S + b * 64 + row] = dot / (row + 1);
        }
    }
}

__device__ __forceinline__ void score_mma(float (&c)[4], unsigned a0, unsigned a1, unsigned a2,
                                          unsigned a3, unsigned b0, unsigned b1) {
    asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.tf32.tf32.f32 "
                 "{%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};"
                 : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3])
                 : "r"(a0), "r"(a1), "r"(a2), "r"(a3), "r"(b0), "r"(b1));
}

// Each warp ranks the causal blocks for one query. A local block that is
// already in the top eight keeps its full causal extent.
template <int GROUPS>
__device__ __forceinline__ void rank_query(const float *scores, float current, int t, int lane,
                                           unsigned char *slots, unsigned char *count) {
    int last = t / 64, total = min(8, last + 1);
    int slot[GROUPS];
#pragma unroll
    for (int i = 0; i < GROUPS; i++)
        slot[i] = 255;
    if (last < 8) {
        if (lane <= last)
            slot[0] = lane;
    } else {
        float val[GROUPS];
#pragma unroll
        for (int i = 0; i < GROUPS; i++) {
            int b = 32 * i + lane;
            val[i] = b == last ? current : b < last ? scores[b] : -CUDART_INF_F;
        }
#pragma unroll
        for (int j = 0; j < 8; j++) {
            float best = val[0];
#pragma unroll
            for (int i = 1; i < GROUPS; i++)
                best = fmaxf(best, val[i]);
            unsigned u = __float_as_uint(best);
            unsigned ordered = u ^ ((int(u) < 0) ? 0xffffffffu : 0x80000000u);
            unsigned largest = __reduce_max_sync(FULL, ordered);
            int idx = -1;
#pragma unroll
            for (int i = 0; i < GROUPS; i++)
                if (val[i] == best)
                    idx = 32 * i + lane;
            int winner = __reduce_max_sync(FULL, ordered == largest ? idx : -1);
#pragma unroll
            for (int i = 0; i < GROUPS; i++)
                if (32 * i + lane == winner) {
                    slot[i] = j;
                    val[i] = -CUDART_INF_F;
                }
        }
        for (int b = max(0, (t - 63) / 64); b <= last; b++) {
            int local = 255;
#pragma unroll
            for (int i = 0; i < GROUPS; i++)
                if (b / 32 == i)
                    local = slot[i];
            if (__shfl_sync(FULL, local, b % 32) == 255) {
#pragma unroll
                for (int i = 0; i < GROUPS; i++)
                    if (32 * i + lane == b)
                        slot[i] = total;
                total++;
            }
        }
    }
    if (lane == 0)
        *count = total;
#pragma unroll
    for (int i = 0; i < GROUPS; i++)
        slots[32 * i + lane] = slot[i];
}

__device__ __forceinline__ unsigned load_pair(const bf *ptr) {
    return *reinterpret_cast<const unsigned *>(ptr);
}

// Tensor core attention for 16 routed queries against one 64-key block.
template <int D>
__device__ __forceinline__ void attend_block(const bf *q, const uint4 *kp, const uint4 *vp, bf *parts,
                                             float *lse, int b, int entry0, int entry1, bool valid0,
                                             bool valid1, int lane, int p) {
    int t0 = entry0 / 16, t1 = entry1 / 16;
    const bf *q0 = q + t0 * D;
    const bf *q1 = q + t1 * D;
    float sc[8][4] = {};
#pragma unroll
    for (int d = 0; d < D / 16; d++) {
        unsigned a0 = load_pair(q0 + d * 16 + p), a1 = load_pair(q1 + d * 16 + p);
        unsigned a2 = load_pair(q0 + d * 16 + p + 8), a3 = load_pair(q1 + d * 16 + p + 8);
#pragma unroll
        for (int j = 0; j < 4; j++) {
            uint4 f = kp[(d * 4 + j) * 32 + lane];
            mma(sc[2 * j], a0, a1, a2, a3, f.x, f.y);
            mma(sc[2 * j + 1], a0, a1, a2, a3, f.z, f.w);
        }
    }
    // Base-2 logits. Local-only routes mask off the older end of the block.
    const float scale = (D == 64 ? 0.125f : 0.08838834764831844f) * 1.4426950408889634f;
    float sums[2], maxima[2];
#pragma unroll
    for (int r = 0; r < 2; r++) {
        int t = r ? t1 : t0, e = r ? entry1 : entry0;
        int lo = (e % 16 >= 8) ? t - 63 : 0;
        float m = -CUDART_INF_F;
#pragma unroll
        for (int j = 0; j < 8; j++) {
#pragma unroll
            for (int x = 0; x < 2; x++) {
                int key = b * 64 + j * 8 + p + x;
                float y = (key >= lo && key <= t) ? sc[j][2 * r + x] * scale : -CUDART_INF_F;
                sc[j][2 * r + x] = y;
                m = fmaxf(m, y);
            }
        }
        m = fmaxf(m, __shfl_xor_sync(FULL, m, 1));
        m = fmaxf(m, __shfl_xor_sync(FULL, m, 2));
        float z = 0;
#pragma unroll
        for (int j = 0; j < 8; j++) {
#pragma unroll
            for (int x = 0; x < 2; x++) {
                float y = exp2f(sc[j][2 * r + x] - m);
                z += y;
                sc[j][2 * r + x] = y;
            }
        }
        z += __shfl_xor_sync(FULL, z, 1);
        z += __shfl_xor_sync(FULL, z, 2);
        sums[r] = 1.f / z;
        maxima[r] = m + log2f(z);
    }
    int dest0 = t0 * SLOTS + entry0 % 16;
    int dest1 = t1 * SLOTS + entry1 % 16;

    if (p == 0) {
        if (valid0)
            lse[dest0] = maxima[0];
        if (valid1)
            lse[dest1] = maxima[1];
    }
    unsigned probs[4][4];
#pragma unroll
    for (int j = 0; j < 4; j++) {
#pragma unroll
        for (int a = 0; a < 4; a++) {
            float *s = &sc[2 * j + a / 2][2 * (a % 2)];
            probs[j][a] = pair_bf(s[0], s[1]);
        }
    }
// Interleave four column pairs per lane. A subgroup writes 64 contiguous
// bytes of one query's partial output in a single vector instruction.
#pragma unroll
    for (int tile = 0; tile < D / 32; tile++) {
        uint4 row0, row1;
#pragma unroll
        for (int half = 0; half < 2; half++) {
            int d = tile * 2 + half;
            float y[2][4] = {};
#pragma unroll
            for (int j = 0; j < 4; j++) {
                uint4 f = vp[(j * (D / 16) + d) * 32 + lane];
                unsigned *a = probs[j];
                mma(y[0], a[0], a[1], a[2], a[3], f.x, f.y);
                mma(y[1], a[0], a[1], a[2], a[3], f.z, f.w);
            }
#pragma unroll
            for (int j = 0; j < 2; j++) {
                reinterpret_cast<unsigned *>(&row0)[2 * half + j] =
                    pair_bf(y[j][0] * sums[0], y[j][1] * sums[0]);
                reinterpret_cast<unsigned *>(&row1)[2 * half + j] =
                    pair_bf(y[j][2] * sums[1], y[j][3] * sums[1]);
            }
        }
        int col = tile * 32 + p * 4;
        if (valid0)
            *reinterpret_cast<uint4 *>(parts + dest0 * D + col) = row0;
        if (valid1)
            *reinterpret_cast<uint4 *>(parts + dest1 * D + col) = row1;
    }
}

template <int D, int CHUNK, int WARPS>
__global__ void sparse_tiles(const bf *q, const uint4 *kp, const uint4 *vp, const unsigned char *routes,
                             bf *parts, float *lse, int S, int N) {
    // Launch only the lower triangle of (query chunk, key block) pairs.
    constexpr int BPC = CHUNK / 64, GROUPS = CHUNK / 32;
    const int chunk = (int)((sqrtf(1.f + 8.f * blockIdx.x / BPC) - 1.f) * 0.5f);
    const int b = blockIdx.x - BPC * chunk * (chunk + 1) / 2, h = blockIdx.y;
    const int tid = threadIdx.x, lane = tid % 32, warp = tid / 32;
    __shared__ int warp_counts[CHUNK / 32], list[CHUNK];
    constexpr int PER_THREAD = GROUPS / WARPS;
    int row[PER_THREAD], slot[PER_THREAD], rank[PER_THREAD];
#pragma unroll
    for (int i = 0; i < PER_THREAD; i++) {
        int r = tid + 32 * WARPS * i;
        row[i] = chunk * CHUNK + r;
        int query_tile = h * ((S + CHUNK - 1) / CHUNK) + chunk;
        slot[i] =
            (row[i] >= b * 64 && row[i] < S) ? routes[(size_t(query_tile) * N + b) * CHUNK + r] : 255;
        unsigned mask = __ballot_sync(FULL, slot[i] < SLOTS);
        rank[i] = __popc(mask & ((1u << lane) - 1));
        if (lane == 0)
            warp_counts[warp + WARPS * i] = __popc(mask);
    }
    __syncthreads();
    // Compact the selected rows so every MMA sees up to 16 live queries.
    int prefix = lane < GROUPS ? warp_counts[lane] : 0;
#pragma unroll
    for (int delta = 1; delta < GROUPS; delta *= 2) {
        int prev = __shfl_up_sync(FULL, prefix, delta);
        if (lane >= delta)
            prefix += prev;
    }
    int n = __shfl_sync(FULL, prefix, GROUPS - 1);
#pragma unroll
    for (int i = 0; i < PER_THREAD; i++) {
        int w = warp + WARPS * i;
        int prev = __shfl_sync(FULL, prefix, max(0, w - 1));
        if (slot[i] < SLOTS)
            list[(w ? prev : 0) + rank[i]] = row[i] * 16 + slot[i];
    }
    __syncthreads();
    kp += (h * N + b) * (64 * D / 8);
    vp += (h * N + b) * (64 * D / 8);
    for (int base = warp * 16; base < n; base += WARPS * 16) {
        int g = lane / 4, p = (lane % 4) * 2;
        int entry0 = list[min(base + g, n - 1)], entry1 = list[min(base + g + 8, n - 1)];
        attend_block<D>(q + h * S * D, kp, vp, parts + h * S * SLOTS * D, lse + h * S * SLOTS, b,
                        entry0, entry1, base + g < n, base + g + 8 < n, lane, p);
    }
}

template <int D>
__device__ __forceinline__ void merge_row(const bf *parts, const float *lse, int n, bf *out, int lane) {
    float l = (lane < n) ? lse[lane] : -CUDART_INF_F;
    float m = l;
#pragma unroll
    for (int i = 8; i; i /= 2)
        m = fmaxf(m, __shfl_xor_sync(FULL, m, i));
    float w = exp2f(l - __shfl_sync(FULL, m, 0));
    float sum = w;
#pragma unroll
    for (int i = 8; i; i /= 2)
        sum += __shfl_xor_sync(FULL, sum, i);
    w /= __shfl_sync(FULL, sum, 0);
    float acc[D / 32] = {};
#pragma unroll 1
    for (int i = 0; i < n; i++) {
        float a = __shfl_sync(FULL, w, i);
#pragma unroll
        for (int d = 0; d < D / 32; d += 2) {
            const auto u = *reinterpret_cast<const __nv_bfloat162 *>(
                parts + i * D + 32 * d + (lane / 16) * 32 + (lane % 4) * 8 + ((lane % 16) / 4) * 2);
            float2 x = __bfloat1622float2(u);
            acc[d] = fmaf(a, x.x, acc[d]);
            acc[d + 1] = fmaf(a, x.y, acc[d + 1]);
        }
    }
#pragma unroll
    for (int d = 0; d < D / 32; d += 2)
        *reinterpret_cast<unsigned *>(out + 32 * d + lane * 2) = pair_bf(acc[d], acc[d + 1]);
}

template <int D>
__global__ void combine(const bf *parts, const float *lse, const unsigned char *counts, bf *out,
                        int rows) {
    int row = blockIdx.x * 8 + threadIdx.x / 32, lane = threadIdx.x % 32;
    if (row < rows)
        merge_row<D>(parts + row * SLOTS * D, lse + row * SLOTS, counts[row], out + row * D, lane);
}

template <int D, int GROUPS>
__global__ void select_blocks(const bf *q, const uint4 *means, const float *current,
                              unsigned char *routes, unsigned char *counts, int S, int N,
                              int chunk_size) {
    constexpr int ROWS = 64, WIDTH = 32 * GROUPS;
    constexpr int COL_WARPS = 8 / (ROWS / 16);
    int tile = blockIdx.x * ROWS, h = blockIdx.y;
    int warp = threadIdx.x / 32, lane = threadIdx.x % 32, g = lane / 4, p = lane % 4;
    int last = tile / 64;
    __shared__ float scores[ROWS][WIDTH];
    __shared__ unsigned char slots[ROWS][WIDTH + 4];
    if (last >= 8) {
        int t0 = min(tile + (warp / COL_WARPS) * 16 + g, S - 1),
            t1 = min(tile + (warp / COL_WARPS) * 16 + g + 8, S - 1);
        unsigned a[D / 8][4];
#pragma unroll
        for (int j = 0; j < D / 8; j++) {
            a[j][0] = __float_as_uint(__bfloat162float(q[(h * S + t0) * D + j * 8 + p]));
            a[j][1] = __float_as_uint(__bfloat162float(q[(h * S + t1) * D + j * 8 + p]));
            a[j][2] = __float_as_uint(__bfloat162float(q[(h * S + t0) * D + j * 8 + p + 4]));
            a[j][3] = __float_as_uint(__bfloat162float(q[(h * S + t1) * D + j * 8 + p + 4]));
        }
        for (int col = (warp % COL_WARPS) * 8; col < last; col += COL_WARPS * 8) {
            float high[4] = {}, low[4] = {};
            const uint4 *fragment = means + ((h * ((N + 7) / 8) + col / 8) * (D / 8)) * 32 + lane;
#pragma unroll
            for (int j = 0; j < D / 8; j++) {
                uint4 key = col + g < N ? fragment[j * 32] : make_uint4(0, 0, 0, 0);
                score_mma(high, a[j][0], a[j][1], a[j][2], a[j][3], key.x, key.z);
                score_mma(low, a[j][0], a[j][1], a[j][2], a[j][3], key.y, key.w);
            }
#pragma unroll
            for (int i = 0; i < 4; i++)
                scores[(warp / COL_WARPS) * 16 + g + 8 * (i / 2)][col + 2 * p + (i % 2)] =
                    high[i] + low[i];
        }
    }
    __syncthreads();
    for (int r = warp; r < ROWS; r += 8) {
        if (tile + r < S) {
            rank_query<GROUPS>(scores[r], current[h * S + tile + r], tile + r, lane, slots[r],
                               counts + h * S + tile + r);
        } else {
#pragma unroll
            for (int i = 0; i < GROUPS; i++)
                slots[r][32 * i + lane] = 255;
        }
    }
    __syncthreads();
    int chunks = (S + chunk_size - 1) / chunk_size;
    size_t grid_base = ((size_t(h) * chunks + tile / chunk_size) * N) * chunk_size + tile % chunk_size;
    for (int i = threadIdx.x; i < (last + 1) * ROWS / 4; i += 256) {
        int b = i / (ROWS / 4), r = (i % (ROWS / 4)) * 4;
        uchar4 x = make_uchar4(slots[r][b], slots[r + 1][b], slots[r + 2][b], slots[r + 3][b]);
        *reinterpret_cast<uchar4 *>(routes + grid_base + b * chunk_size + r) = x;
    }
}

// Beyond the shared-memory ranking tile, stream the means through a warp
// and keep its eight winners in lanes 0..7.
template <int D>
__global__ void select_long(const bf *q, const uint4 *means, const float *current,
                            unsigned char *routes, unsigned char *counts, int S, int N,
                            int chunk_size) {
    int lane = threadIdx.x % 32, t = blockIdx.x * 8 + threadIdx.x / 32, h = blockIdx.y;
    if (t >= S)
        return;
    int chunks = (S + chunk_size - 1) / chunk_size;
    unsigned char *row =
        routes + ((size_t(h) * chunks + t / chunk_size) * N) * chunk_size + t % chunk_size;
    int last = t / 64, id = -1;
    float best = -CUDART_INF_F, query[D / 32];
#pragma unroll
    for (int j = 0; j < D / 32; j++)
        query[j] = __bfloat162float(q[(size_t(h) * S + t) * D + 32 * j + lane]);
    for (int b = lane; b <= last; b += 32)
        row[(size_t)b * chunk_size] = 255;
    __syncwarp();
    for (int b = 0; b <= last; b++) {
        float dot = 0.f;
        if (b == last)
            dot = current[h * S + t];
        else {
#pragma unroll
            for (int j = 0; j < D / 32; j++) {
                int d = 32 * j + lane;
                size_t f =
                    ((size_t(h) * ((N + 7) / 8) + b / 8) * (D / 8) + d / 8) * 32 + (b % 8) * 4 + d % 4;
                uint2 key = reinterpret_cast<const uint2 *>(means + f)[(d % 8) / 4];
                dot = fmaf(query[j], __uint_as_float(key.x) + __uint_as_float(key.y), dot);
            }
#pragma unroll
            for (int delta = 16; delta; delta /= 2)
                dot += __shfl_xor_sync(FULL, dot, delta);
        }
        int pos = __popc(__ballot_sync(FULL, lane < 8 && best > dot));
        float prev = __shfl_up_sync(FULL, best, 1);
        int prev_id = __shfl_up_sync(FULL, id, 1);
        if (lane == pos) {
            best = dot;
            id = b;
        } else if (lane > pos) {
            best = prev;
            id = prev_id;
        }
    }
    if (lane < 8 && id >= 0)
        row[(size_t)id * chunk_size] = lane;
    int total = min(last + 1, 8);
    for (int b = max(0, (t - 63) / 64); b <= last; b++) {
        if (!__any_sync(FULL, lane < 8 && id == b)) {
            if (lane == 0)
                row[(size_t)b * chunk_size] = total;
            total++;
        }
    }
    if (lane == 0)
        counts[h * S + t] = total;
}

template <int D>
void run(const at::Tensor &q, const at::Tensor &k, const at::Tensor &v, at::Tensor &o) {
    const int H = q.size(0) * q.size(1), S = q.size(2), N = (S + 63) / 64;
    const int groups = (N + 31) / 32;

    auto opt = q.options();
    auto packed = at::empty({2, H, N, 64, D}, opt);
    auto means = at::empty({H, (N + 7) / 8, 8, D, 2}, opt.dtype(at::kInt));
    auto current = at::empty({H, S}, opt.dtype(at::kFloat));
    // Consume the partials while they still fit in L2.
    size_t bytes_per_head = size_t(S) * SLOTS * D * sizeof(bf);
    int head_batch =
        bytes_per_head * H <= (96u << 20) ? H : std::max(1, int((48u << 20) / bytes_per_head));
    const int chunk_size = S > 3072 ? 512 : 256;
    const int chunks = (S + chunk_size - 1) / chunk_size;
    auto routes = at::empty({H, chunks, N, chunk_size}, opt.dtype(at::kByte));
    auto counts = at::empty({H, S}, opt.dtype(at::kByte));
    auto parts = at::empty({head_batch, S, SLOTS, D}, opt);
    auto lse = at::empty({head_batch, S, SLOTS}, opt.dtype(at::kFloat));
    auto stream = at::cuda::getCurrentCUDAStream();
    auto Q = (const bf *)q.data_ptr(), K = (const bf *)k.data_ptr(), V = (const bf *)v.data_ptr();
    auto KP = (uint4 *)packed.data_ptr(), VP = KP + (size_t)H * N * 64 * D / 8;
    auto M = (uint4 *)means.data_ptr();
    auto C = current.data_ptr<float>();
    auto R = routes.data_ptr<unsigned char>(), T = counts.data_ptr<unsigned char>();
    auto P = (bf *)parts.data_ptr(), O = (bf *)o.data_ptr();
    auto L = lse.data_ptr<float>();
    prepare<D><<<dim3(N, H), 256, 0, stream>>>(Q, K, V, KP, VP, M, C, S, N);
    if (groups <= 4) {
        const decltype(&select_blocks<D, 1>) selectors[] = {select_blocks<D, 1>, select_blocks<D, 2>,
                                                            select_blocks<D, 3>, select_blocks<D, 4>};
        auto select = selectors[groups - 1];
        select<<<dim3(N, H), 256, 0, stream>>>(Q, M, C, R, T, S, N, chunk_size);
    } else {
        select_long<D><<<dim3((S + 7) / 8, H), 256, 0, stream>>>(Q, M, C, R, T, S, N, chunk_size);
    }
    auto attend = chunk_size == 256 ? sparse_tiles<D, 256, 8> : sparse_tiles<D, 512, 8>;
    int tiles = (chunk_size / 64) * chunks * (chunks - 1) / 2 + N;
    for (int h = 0; h < H; h += head_batch) {
        int batch = std::min(head_batch, H - h);
        size_t packed_offset = size_t(h) * N * 64 * D / 8;
        attend<<<dim3(tiles, batch), 256, 0, stream>>>(
            Q + size_t(h) * S * D, KP + packed_offset, VP + packed_offset,
            R + size_t(h) * chunks * N * chunk_size, P, L, S, N);
        combine<D><<<(batch * S + 7) / 8, 256, 0, stream>>>(P, L, T + h * S, O + size_t(h) * S * D,
                                                            batch * S);
    }
    C10_CUDA_KERNEL_LAUNCH_CHECK();
}

at::Tensor nsa(at::Tensor q, at::Tensor k, at::Tensor v) {
    TORCH_CHECK(q.is_cuda() && k.device() == q.device() && v.device() == q.device(),
                "Expected CUDA tensors");
    TORCH_CHECK(q.dim() == 4 && q.sizes() == k.sizes() && q.sizes() == v.sizes(),
                "Expected matching B,H,S,D");
    TORCH_CHECK(q.scalar_type() == at::kBFloat16 && k.scalar_type() == q.scalar_type() &&
                    v.scalar_type() == q.scalar_type(),
                "Expected bf16");
    const c10::cuda::CUDAGuard guard(q.device());
    auto aligned = [](at::Tensor x) {
        x = x.contiguous();
        return reinterpret_cast<uintptr_t>(x.data_ptr()) % 16 ? x.clone() : x;
    };
    q = aligned(q);
    k = aligned(k);
    v = aligned(v);
    auto o = at::empty_like(q);
    if (!q.numel())
        return o;
    if (q.size(3) == 64)
        run<64>(q, k, v, o);
    else if (q.size(3) == 128)
        run<128>(q, k, v, o);
    else
        TORCH_CHECK(false, "Expected head dimension 64 or 128");
    return o;
}
"""


@lru_cache(maxsize=1)
def _extension():
    return load_inline(
        name="nsa_block_routed_sm120",
        cpp_sources="at::Tensor nsa(at::Tensor q, at::Tensor k, at::Tensor v);",
        cuda_sources=_CUDA,
        functions=["nsa"],
        extra_cflags=["-O3"],
        extra_cuda_cflags=["-O3", "--use_fast_math", "-gencode=arch=compute_120,code=sm_120"],
        verbose=False,
    )


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))

    def forward(self, q, k, v):
        return _extension().nsa(q, k, v)

20261117_133506_codex_gpt-6.2-astra_02_deepseek_nsa