Skip to content

GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold

Python
33.2 KB
Raw Blame
# A prompt chunk's sparse latent attention (latent._sparse_onepass) as a CUDA kernel (sparse_onepass.cu) that computes
# every output with the Triton kernel's own instruction sequence, read from its PTX: the mma chains and their K order,
# the online softmax's roundings and ex2.approx, the p-sum's reduction tree, div.full. Keys as the mma's M side (the
# GB10's mma.sync is operand-symmetric bit for bit), q in registers, softmax inside a warp, producer warps gathering and
# converting the FP8 rows two tiles ahead, five P.V warps balancing the SM's four schedulers. Every output is the Triton
# kernel's bit for bit. FP8 caches and 17-24 heads a rank only (TP=3's 22 / 21: the kernel holds 24 heads in three QK
# warps); TP=2's 32 heads keep Triton. Built / loaded by decode.Engine's constructor like patch 0105's, and like it
# not used (logged once; the Triton kernel serves) under another Triton release than sparse.TRITON_PTX (3.7) or when
# the build fails. TF_GLM_ONEPASS_CUDA=0: the Triton kernel. Applies after patch 0105 (decode.py's start-up loads, and
# sparse.TRITON_PTX). tools/sparse_onepass_check.py.

diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py
--- tensorfold/families/glm5_next/cuda/decode.py
+++ tensorfold/families/glm5_next/cuda/decode.py
@@ -202,6 +202,10 @@ class Engine:
 
             if sparse.prompt_scores_cuda():
                 sparse._scores_ext()
+            from . import latent
+
+            if latent.onepass_cuda():                   # patch 0106: the prompt chunks' sparse attention, likewise
+                latent._onepass_ext()
         self.slots = Slots(w, streams, max_rows)
         self.home = self.st = State(w, capacity, max_rows, caches=self.caches, slots=self.slots)
         self.last_hidden: torch.Tensor | None = None
diff --git tensorfold/families/glm5_next/cuda/latent.py tensorfold/families/glm5_next/cuda/latent.py
--- tensorfold/families/glm5_next/cuda/latent.py
+++ tensorfold/families/glm5_next/cuda/latent.py
@@ -706,6 +706,46 @@ ONEPASS_TILE = (32, 32, 1)          # heads per program (a rank's 32), keys per
 ONEPASS_LAUNCH = (8, 1, True)
 
 
+def onepass_cuda() -> bool:
+    """TF_GLM_ONEPASS_CUDA (default on): sparse_onepass on an FP8 cache with the default tile and launch
+    (ONEPASS_TILE, ONEPASS_LAUNCH) and 17-24 heads (TP=3's 22 / 21) runs sparse_onepass.cu, which computes every
+    output with _sparse_onepass' own instruction sequence (its PTX: the mma chains and their K order, the online
+    softmax's roundings, ex2.approx, the p-sum's reduction tree, div.full), so the same bits, with no repeated score
+    blocks, the cache rows gathered and converted by producer warps and the P.V work split over five warps so each
+    of the SM's four schedulers carries about the same tensor-core work; 0: the Triton kernel. Off as well when the
+    extension is not used (another Triton release than sparse.TRITON_PTX, or a failed build or load:
+    ``_onepass_ext``). tools/sparse_onepass_check.py."""
+    return __import__("os").environ.get("TF_GLM_ONEPASS_CUDA", "1") != "0" and _ONEPASS_FAILED is None
+
+
+_ONEPASS_EXT = None
+_ONEPASS_FAILED = None     # why sparse_onepass.cu is not used (then _sparse_onepass serves)
+
+
+def _onepass_ext():
+    """The extension, built / loaded once; None when it is not used (as patch 0105's ``sparse._scores_ext``)."""
+    global _ONEPASS_EXT, _ONEPASS_FAILED
+    if _ONEPASS_EXT is None and _ONEPASS_FAILED is None:
+        from pathlib import Path
+
+        from tensorfold.cuda.build import load
+
+        from . import sparse
+
+        try:
+            if not sparse.triton_matches_ptx():
+                raise RuntimeError(f"Triton {triton.__version__}: the kernel reproduces Triton "
+                                   f"{sparse.TRITON_PTX}'s PTX")
+            _ONEPASS_EXT = load(name="tensorfold_glm_onepass_v1",
+                                sources=[str(Path(__file__).parent / "sparse_onepass.cu")],
+                                extra_cuda_cflags=["-O3"], verbose=False)
+        except Exception as exc:
+            _ONEPASS_FAILED = f"{type(exc).__name__}: {(str(exc).strip().splitlines() or [''])[-1][:200]}"
+            print(f"[tensorfold] sparse_onepass.cu is not used ({_ONEPASS_FAILED}); prompt chunks' sparse attention "
+                  "runs the Triton kernel", flush=True)
+    return _ONEPASS_EXT
+
+
 def sparse_onepass(qa: torch.Tensor, cache: torch.Tensor, tokens: torch.Tensor, counts: torch.Tensor,
                    out: torch.Tensor, scale: float, *, tile: tuple | None = None, launch: tuple | None = None) -> None:
     """sparse_attention for a prompt chunk's rows: one program a row (and head group) walks every selected token in
@@ -721,6 +761,12 @@ def sparse_onepass(qa: torch.Tensor, cache: torch.Tensor, tokens: torch.Tensor,
     hbt, kt, split = tile or ONEPASS_TILE
     warps, stages, prefetch = launch or ONEPASS_LAUNCH
     hbt = max(16, min(hbt, triton.next_power_of_2(H)))            # tensor-core tiles need 16 rows
+    ext = (_onepass_ext() if fp8 and LW == 512 and 16 < H <= 24 and (hbt, kt, split) == (32, 32, 1)
+           and (warps, stages, bool(prefetch)) == (8, 1, True) and tokens.dtype == torch.int32
+           and counts.dtype == torch.int32 and onepass_cuda() else None)
+    if ext is not None:
+        ext.onepass(qa, cache, rs, tokens, counts, out, scale)              # patch 0106: the same bits
+        return
     _sparse_onepass[(R, triton.cdiv(H, hbt), split)](qa, vals, scl, tokens, counts, out, W=tokens.shape[1], H=H,
                                                      LW=LW, SCALE=scale, HBT=hbt, KTT=kt, SPLIT=split, STAGES=stages,
                                                      PREFETCH=bool(prefetch), RS=rs, FP8=fp8, num_warps=warps,
diff --git tensorfold/families/glm5_next/cuda/sparse_onepass.cu tensorfold/families/glm5_next/cuda/sparse_onepass.cu
new file mode 100644
--- /dev/null
+++ tensorfold/families/glm5_next/cuda/sparse_onepass.cu
@@ -0,0 +1,523 @@
+// Patch 0106: a prompt chunk's sparse latent attention (latent._sparse_onepass as sparse_onepass launches it by
+// default: an FP8 latent cache, 512-wide rows, one program a row for TP=3's 22 / 21 heads, 32-key tiles, 8 warps,
+// register prefetch) as a CUDA kernel that computes every output with the Triton kernel's own instruction sequence,
+// read from its PTX / GPU IR, so every bit is the same. tools/sparse_onepass_check.py.
+//
+// The layout below was profiled (ncu PC sampling, a 113k 2,048-row chunk) and tuned with the same bits at every
+// step. Against a first version with four P.V warps of 8 latent tiles (2,048-row chunks, "recent" selections at
+// 113k and 590k: 0.926 of its time, 3.81 -> 3.53 ms; "spread", DRAM-bound, unchanged), each part measured as a
+// paired ratio at 113k: the swizzle (swz: the producers' stores free of bank conflicts) alone 0.994; plus the P.V
+// loop bounded by a per-warp tile count the compiler cannot see (pv_tiles) 0.956: then ptxas keeps the loop in
+// source order (each m16 tile's ldmatrix one tile ahead, at most 6 mma at a time) instead of front-loading the
+// ldmatrix and ending each tile in 21 back-to-back mma on a tensor pipe the QK warp's dependent score chains share
+// (cuobjdump; the likely cause, not isolated further); plus five P.V warps sharing the 32 latent tiles
+// 6 / 6 / 6 / 7 / 7, 0.927 (8 / 8 / 8 / 8 on the same twelve warps: 0.949).
+//
+// The Triton kernel, read from its PTX / GPU IR on a GB10 (Triton 3.7, mma layout warpsPerCTA [1, 8], kWidth 2):
+//   - the tile's 32 cache rows: e4m3 codes -> bf16 (cvt.rn.f16x2.e4m3x2, then cvt.bf16.f16 each), keys past the
+//     row's count zeros, their scales 1;
+//   - scores[heads, keys] = mma.sync m16n8k16 bf16 -> fp32 of q (heads past H zero) and the keys, each output one
+//     chain over the 32 k16 steps in ascending order from +0, k = 16 s .. 16 s + 15 in step s;
+//   - per element (dot * ks[key]) * SCALE, keys past the count -> -inf;
+//   - tile_m = max over the keys (any order: max is exact), active = tile_m != -inf, next_m = active ? max(m, tile_m)
+//     : m, alpha = active ? (m == -inf ? 0 : ex2.approx((m - next_m) * log2e)) : 1 (exp is mul.f32 by 0f3FB8AA3B,
+//     then ex2.approx.f32, no ftz);
+//   - p = (key valid and active) ? ex2.approx((score - next_m) * log2e) : 0;
+//   - o = the mma chain over the two 16-key steps (in order) of bf16(p * ks) and the keys, from o * alpha (Triton
+//     folds the + into the mma's accumulator);
+//   - l = fma(l, alpha, sum_k p), the sum in the layout's reduction tree: a lane's keys 2 u, 2 u + 1, then the lanes
+//     ^ 2, then ^ 1 over a warp's 8 keys, then the four 8-key partials (s0 + s2) + (s1 + s3);
+//   - out = bf16(div.full.f32(o, l)) for heads below H.
+// Every operation below is that one in that order (explicit _rn intrinsics and inline PTX: no contraction or
+// reassociation). Two measured facts of the GB10's mma.sync m16n8k16 bf16 let the work be laid out otherwise: it is
+// symmetric in its operands bit for bit (keys x q^T gives the transpose of q x keys^T: 0 of 1.2e8 outputs differed)
+// and the order of k inside a k16 step does not matter, so the keys are the M side here:
+//   - 3 QK warps hold q^T (8 heads each) in registers and run both 16-key halves' chains; a warp has its 8 heads'
+//     whole tile, so the max and the p-sums (the tree above, as lane shuffles ^ 4, ^ 16, ^ 8) never leave it, and
+//     tile t + 1's chains are issued between tile t's softmax stages;
+//   - 5 PV warps (o^T = keys^T . P^T over their share of the 32 latent m16 tiles) run a tile behind, from P and
+//     alpha in shared memory;
+//   - 4 producer warps gather the cache rows two tiles ahead and convert them into one of three bf16 key-tile buffers:
+//     exactly, on the integer and bf16 pipes (a code's sign-extended byte, shifted and masked, times 2^120), or by
+//     Triton's own sequence for a tile holding a NaN code;
+//   - named barriers hand the tiles and P along; Triton's 768 mma a tile (warps 4-7 repeated 0-3's scores and q's
+//     fragments were read from shared memory every tile) are 384 (heads padded to 24, not 32).
+#include <ATen/cuda/CUDAContext.h>
+#include <c10/cuda/CUDAGuard.h>
+#include <cuda_bf16.h>
+#include <stdint.h>
+#include <torch/extension.h>
+
+namespace {
+
+constexpr int HQ = 24, LW = 512, KT = 32, NB = 3;    // heads kept, latent width, keys a tile, key-tile buffers
+constexpr int NV = 5, NQ = 3, NPW = 4;               // PV, QK, producer warps (warp roles: see the kernel)
+// PV warp v's share of the 32 latent m16 tiles (6 mma a tile each). A warp's scheduler is warp & 3; the QK warps
+// (64 mma a tile, latency-bound score chains: ncu put 15% of their time in math-pipe stalls) sit on schedulers 0-2, so
+// PV 0-2 take 6 tiles there and PV 3 / 4 (warps 3 and 7, both on scheduler 3) 7 each: 100 / 100 / 100 / 84 mma a
+// tile a scheduler, where four PV warps of 8 tiles gave 112 / 112 / 112 / 48
+__device__ __forceinline__ constexpr int pv_tiles(int v) { return v < 3 ? 6 : 7; }
+constexpr int PV_MAX = 7;                            // the most tiles a PV warp takes
+constexpr int NT = (NV + NQ + NPW) * 32;
+constexpr int CH = LW * 2 / 16;                      // 16-byte chunks of a bf16 latent row (64)
+constexpr int BAR_FULL = 1, BAR_EMPTY = 4, BAR_PREADY = 7, BAR_PFREE = 8, BAR_FIN = 9;
+constexpr int N_FULL = (NPW + NQ) * 32, N_EMPTY = (NV + NPW) * 32, N_QV = (NQ + NV) * 32;
+
+__device__ __forceinline__ void mma16816(float (&d)[4], const uint32_t (&a)[4], uint32_t b0, uint32_t 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};\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"(b0), "r"(b1));
+}
+
+__device__ __forceinline__ void ldsm_x4(uint32_t (&r)[4], unsigned s) {
+    asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];\n"
+                 : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3])
+                 : "r"(s));
+}
+
+__device__ __forceinline__ void ldsm_x4_t(uint32_t (&r)[4], unsigned s) {
+    asm volatile("ldmatrix.sync.aligned.m8n8.x4.trans.shared.b16 {%0,%1,%2,%3}, [%4];\n"
+                 : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3])
+                 : "r"(s));
+}
+
+__device__ __forceinline__ void bar_sync(int id, int n) { asm volatile("bar.sync %0, %1;" ::"r"(id), "r"(n) : "memory"); }
+__device__ __forceinline__ void bar_arrive(int id, int n) {
+    asm volatile("bar.arrive %0, %1;" ::"r"(id), "r"(n) : "memory");
+}
+
+__device__ __forceinline__ float ex2(float x) {
+    float y;
+    asm("ex2.approx.f32 %0, %1;" : "=f"(y) : "f"(x));
+    return y;
+}
+
+__device__ __forceinline__ float div_full(float a, float b) {
+    float y;
+    asm("div.full.f32 %0, %1, %2;" : "=f"(y) : "f"(a), "f"(b));
+    return y;
+}
+
+__device__ __forceinline__ uint16_t bf16(float x) {
+    uint16_t r;
+    asm("cvt.rn.bf16.f32 %0, %1;" : "=h"(r) : "f"(x));
+    return r;
+}
+
+// Two e4m3 codes (low byte first) -> bf16x2 (low first) by Triton's own instruction sequence (its PTX: the codes to
+// f16x2, then cvt.bf16.f16 each): used only for a tile holding a NaN code, whose NaN bits this keeps.
+__device__ __forceinline__ uint32_t e4m3x2_bf16x2_tri(uint32_t two) {
+    uint32_t r;
+    const unsigned short v = (unsigned short)two;
+    asm("{\n .reg .b32 a;\n .reg .f16 a<2>;\n .reg .b16 b<2>;\n cvt.rn.f16x2.e4m3x2 a, %1;\n mov.b32 {a0, a1}, a;\n"
+        " cvt.bf16.f16 b0, a0;\n cvt.bf16.f16 b1, a1;\n mov.b32 %0, {b0, b1};\n}" : "=r"(r) : "h"(v));
+    return r;
+}
+
+// Four e4m3 codes -> two bf16x2 (codes 0, 1 and 2, 3) on the integer and bf16 pipes, exactly for every code but NaN:
+// a code's sign-extended 16 bits, shifted left 4 and masked, are the bf16 with its sign, the 4 exponent bits and
+// the 3 mantissa bits in place and 2^-120 of the value (a subnormal code a subnormal bf16), then times 2^120 (exact).
+__device__ __forceinline__ void e4m3x4_bf16(uint32_t w, uint32_t& lo, uint32_t& hi) {
+    uint32_t a, b;
+    asm("prmt.b32 %0, %1, %2, %3;" : "=r"(a) : "r"(w), "r"(0u), "r"(0x9180u));   // [sext b1 | sext b0]
+    asm("prmt.b32 %0, %1, %2, %3;" : "=r"(b) : "r"(w), "r"(0u), "r"(0xB3A2u));   // [sext b3 | sext b2]
+    a = (a << 4) & 0x87F087F0u;
+    b = (b << 4) & 0x87F087F0u;
+    asm("mul.rn.bf16x2 %0, %1, %2;" : "=r"(lo) : "r"(a), "r"(0x7B807B80u));   // 2^120
+    asm("mul.rn.bf16x2 %0, %1, %2;" : "=r"(hi) : "r"(b), "r"(0x7B807B80u));
+}
+
+// a key tile's 16-byte chunk c of key r: c ^ ((r ^ (c >> 3)) & 7). Eight consecutive keys of one chunk (an ldmatrix's
+// 8 rows, QK and PV) still fall in eight bank groups; a producer lane stores chunks 2 l and 2 l + 1 of one key, and
+// with the (c >> 3) term lanes 0-3 and 4-7 of every quarter-warp land in different bank groups (a plain c ^ (r & 7):
+// 2-way conflicts, 37 M of a 113k chunk's 243 M shared-memory wavefronts, ncu)
+__device__ __forceinline__ int swz(int r, int c) { return c ^ ((r ^ (c >> 3)) & 7); }
+__device__ __forceinline__ int pswz(int r, int c) { return c ^ ((r >> 1) & 3); }
+
+constexpr float LOG2E = 1.44269502162933349609375f;   // 0f3FB8AA3B
+
+struct Smem {
+    uint4 kt[NB][KT * CH];      // 96 KB: key tiles, bf16 [key][64 chunks], swizzled
+    uint16_t ps[HQ * KT];       // P [head][key] bf16, 4 chunks a row, chunk-swizzled
+    float ks[NB][KT];
+    float alpha[HQ];
+    float lsum[HQ];
+};
+
+struct Raw {
+    uint4 v[8];
+    float s[8];
+};
+
+__device__ __forceinline__ void ids_load(const int32_t* __restrict__ row, int n, int tile, int pw, int (&id)[8]) {
+#pragma unroll
+    for (int i = 0; i < 8; ++i) {
+        const int k = tile * KT + pw + 4 * i;
+        id[i] = k < n ? row[k] : -1;
+    }
+}
+
+__device__ __forceinline__ void raw_load(const uint8_t* __restrict__ LC, int RS, const int (&id)[8], int lane, Raw& r) {
+#pragma unroll
+    for (int i = 0; i < 8; ++i) {
+        const uint8_t* src = LC + (size_t)(id[i] < 0 ? 0 : id[i]) * RS;
+        r.v[i] = id[i] < 0 ? make_uint4(0, 0, 0, 0) : *reinterpret_cast<const uint4*>(src + 16 * lane);
+        r.s[i] = id[i] < 0 || lane ? 1.0f : *reinterpret_cast<const float*>(src + LW);
+    }
+}
+
+__device__ __forceinline__ void convert(const Raw& r, uint4* kt, float* ks, int pw, int lane) {
+    uint32_t nan = 0;                                     // bit 7 of a byte: some code of it was 0x7F / 0xFF
+#pragma unroll
+    for (int i = 0; i < 8; ++i) {
+        const uint32_t in[4] = {r.v[i].x, r.v[i].y, r.v[i].z, r.v[i].w};
+#pragma unroll
+        for (int q = 0; q < 4; ++q) nan |= (in[q] & 0x7F7F7F7Fu) + 0x01010101u;
+    }
+    if (__any_sync(0xffffffffu, nan & 0x80808080u)) {
+#pragma unroll
+        for (int i = 0; i < 8; ++i) {
+            const int key = pw + 4 * i;
+            const uint32_t in[4] = {r.v[i].x, r.v[i].y, r.v[i].z, r.v[i].w};
+            uint32_t w[8];
+#pragma unroll
+            for (int m = 0; m < 8; ++m) w[m] = e4m3x2_bf16x2_tri(in[m >> 1] >> (16 * (m & 1)));
+            kt[key * CH + swz(key, 2 * lane)] = make_uint4(w[0], w[1], w[2], w[3]);
+            kt[key * CH + swz(key, 2 * lane + 1)] = make_uint4(w[4], w[5], w[6], w[7]);
+            if (lane == 0) ks[key] = r.s[i];
+        }
+        return;
+    }
+#pragma unroll
+    for (int i = 0; i < 8; ++i) {
+        const int key = pw + 4 * i;
+        const uint32_t in[4] = {r.v[i].x, r.v[i].y, r.v[i].z, r.v[i].w};
+        uint32_t w[8];
+#pragma unroll
+        for (int q = 0; q < 4; ++q) e4m3x4_bf16(in[q], w[2 * q], w[2 * q + 1]);
+        kt[key * CH + swz(key, 2 * lane)] = make_uint4(w[0], w[1], w[2], w[3]);
+        kt[key * CH + swz(key, 2 * lane + 1)] = make_uint4(w[4], w[5], w[6], w[7]);
+        if (lane == 0) ks[key] = r.s[i];
+    }
+}
+
+__global__ void __launch_bounds__(NT, 1) onepass_kernel(const __nv_bfloat16* __restrict__ QA,
+                                                        const uint8_t* __restrict__ LC, int RS,
+                                                        const int32_t* __restrict__ TOK, int W,
+                                                        const int32_t* __restrict__ CNT,
+                                                        __nv_bfloat16* __restrict__ OUT, int H, float scale) {
+    extern __shared__ __align__(16) uint8_t smem_raw[];
+    Smem& S = *reinterpret_cast<Smem*>(smem_raw);
+    const int r = blockIdx.x;
+    const int n = CNT[r];
+    if (n <= 0) return;
+    const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31, g = lane >> 2, t4 = lane & 3;
+    const int ntile = (n + KT - 1) / KT;
+    const int32_t* row = TOK + (size_t)r * W;
+
+    // warps 0-3 PV 0-3, 4-6 QK, 7 PV 4, 8-11 producers
+    if (warp >= 8) {
+        // ---------------------------------------------------- producers: keys pw + 4 i, 16 B a lane, two tiles ahead
+        const int pw = warp - 8;
+        Raw A, B;
+        int ia[8], ib[8];
+        ids_load(row, n, 0, pw, ia);
+        ids_load(row, n, 1, pw, ib);
+        raw_load(LC, RS, ia, lane, A);
+        raw_load(LC, RS, ib, lane, B);
+        ids_load(row, n, 2, pw, ia);
+        ids_load(row, n, 3, pw, ib);
+        int b = 0;
+        for (int t = 0; t < ntile; t += 2) {
+            if (t >= NB) bar_sync(BAR_EMPTY + b, N_EMPTY);
+            convert(A, S.kt[b], S.ks[b], pw, lane);
+            bar_arrive(BAR_FULL + b, N_FULL);
+            b = b + 1 == NB ? 0 : b + 1;
+            if (t + 2 < ntile) {
+                raw_load(LC, RS, ia, lane, A);
+                ids_load(row, n, t + 4, pw, ia);
+            }
+            if (t + 1 >= ntile) break;
+            if (t + 1 >= NB) bar_sync(BAR_EMPTY + b, N_EMPTY);
+            convert(B, S.kt[b], S.ks[b], pw, lane);
+            bar_arrive(BAR_FULL + b, N_FULL);
+            b = b + 1 == NB ? 0 : b + 1;
+            if (t + 3 < ntile) {
+                raw_load(LC, RS, ib, lane, B);
+                ids_load(row, n, t + 5, pw, ib);
+            }
+        }
+        return;
+    }
+
+    if (warp >= 4 && warp < 7) {
+        // ------------------------------------------------- QK warps: heads 8 j .. 8 j + 7 (an n8 tile), all 32 keys
+        const int j = warp - 4;
+        const int hq = 8 * j + g;                         // this lane's B column (head)
+        uint32_t qf[32][2];                               // q^T B fragments: step s, k = 16 s + 2 t (+ 8)
+#pragma unroll
+        for (int s = 0; s < 32; ++s) {
+            const __nv_bfloat16* q = QA + ((size_t)r * H + (hq < H ? hq : 0)) * LW + 16 * s + 2 * t4;
+            qf[s][0] = hq < H ? *reinterpret_cast<const uint32_t*>(q) : 0u;
+            qf[s][1] = hq < H ? *reinterpret_cast<const uint32_t*>(q + 8) : 0u;
+        }
+        float m[2] = {-INFINITY, -INFINITY}, l[2] = {0.0f, 0.0f};   // heads 8 j + 2 t, + 1
+        const int ar = lane & 15, ac = lane >> 4;
+        // QK(t + 1)'s 32 steps are issued between softmax(t)'s stages, so the in-order warp has the score chains'
+        // mma in flight while it waits on the softmax's shuffles and ex2 (and the other way round)
+        uint32_t a[3][2][4];
+        unsigned ktn;
+        float acc[2][4], accn[2][4];
+#define LOADA(slot, s)                                                                                   \
+    {                                                                                                    \
+        ldsm_x4(a[slot][0], ktn + 16 * (ar * CH + swz(ar, 2 * (s) + ac)));                              \
+        ldsm_x4(a[slot][1], ktn + 16 * ((16 + ar) * CH + swz(16 + ar, 2 * (s) + ac)));                   \
+    }
+#define QKSTEP(s)                                                                                        \
+    {                                                                                                    \
+        if ((s) + 2 < 32) LOADA(((s) + 2) % 3, (s) + 2)                                                  \
+        mma16816(accn[0], a[(s) % 3][0], qf[s][0], qf[s][1]);                                            \
+        mma16816(accn[1], a[(s) % 3][1], qf[s][0], qf[s][1]);                                            \
+    }
+#define QKBEGIN()                                                                                        \
+    {                                                                                                    \
+        for (int i_ = 0; i_ < 2; ++i_)                                                                   \
+            for (int e_ = 0; e_ < 4; ++e_) accn[i_][e_] = 0.0f;                                          \
+        LOADA(0, 0)                                                                                      \
+        LOADA(1, 1)                                                                                      \
+    }
+        bar_sync(BAR_FULL + 0, N_FULL);
+        ktn = (unsigned)__cvta_generic_to_shared(S.kt[0]);
+        QKBEGIN()
+#pragma unroll
+        for (int s = 0; s < 32; ++s) QKSTEP(s)
+#pragma unroll
+        for (int i = 0; i < 2; ++i)
+#pragma unroll
+            for (int e = 0; e < 4; ++e) acc[i][e] = accn[i][e];
+        int b = 0;
+        for (int t = 0; t < ntile; ++t) {
+            const int t0 = t * KT, bn = b + 1 == NB ? 0 : b + 1;
+            if (t + 1 < ntile) bar_sync(BAR_FULL + bn, N_FULL);
+            // the last tile's "next" scores run on its own buffer and are dropped (no branch in the block below)
+            ktn = (unsigned)__cvta_generic_to_shared(S.kt[t + 1 < ntile ? bn : b]);
+            QKBEGIN()
+#pragma unroll
+            for (int s = 0; s < 8; ++s) QKSTEP(s)
+            // acc[i][e]: key 16 i + g (e < 2) or 16 i + 8 + g (e >= 2), head 8 j + 2 t + (e & 1)
+            float sc[2][4], kk[2][2];
+            bool val[2][2];
+#pragma unroll
+            for (int i = 0; i < 2; ++i)
+#pragma unroll
+                for (int hi = 0; hi < 2; ++hi) {
+                    const int key = 16 * i + 8 * hi + g;
+                    kk[i][hi] = S.ks[b][key];
+                    val[i][hi] = t0 + key < n;
+#pragma unroll
+                    for (int e = 0; e < 2; ++e)
+                        sc[i][2 * hi + e] =
+                            val[i][hi] ? __fmul_rn(__fmul_rn(acc[i][2 * hi + e], kk[i][hi]), scale) : -INFINITY;
+                }
+            float nm[2], alpha[2];
+            bool act[2];
+#pragma unroll
+            for (int e = 0; e < 2; ++e) {
+                float x = fmaxf(fmaxf(sc[0][e], sc[0][2 + e]), fmaxf(sc[1][e], sc[1][2 + e]));
+                x = fmaxf(x, __shfl_xor_sync(0xffffffffu, x, 4));
+                x = fmaxf(x, __shfl_xor_sync(0xffffffffu, x, 8));
+                x = fmaxf(x, __shfl_xor_sync(0xffffffffu, x, 16));
+                act[e] = x != -INFINITY;
+                nm[e] = act[e] ? fmaxf(m[e], x) : m[e];
+                const float a_ = m[e] == -INFINITY ? 0.0f : ex2(__fmul_rn(__fsub_rn(m[e], nm[e]), LOG2E));
+                alpha[e] = act[e] ? a_ : 1.0f;
+            }
+#pragma unroll
+            for (int s = 8; s < 16; ++s) QKSTEP(s)
+            float p[2][4];
+#pragma unroll
+            for (int i = 0; i < 2; ++i)
+#pragma unroll
+                for (int x = 0; x < 4; ++x) {
+                    const int e = x & 1;
+                    p[i][x] = val[i][x >> 1] && act[e] ? ex2(__fmul_rn(__fsub_rn(sc[i][x], nm[e]), LOG2E)) : 0.0f;
+                }
+#pragma unroll
+            for (int s = 16; s < 24; ++s) QKSTEP(s)
+            // the p sums in Triton's tree: key group w = 2 i + hi (keys 8 w .. 8 w + 7, this lane's key 8 w + g):
+            // (p[2u] + p[2u + 1]) over u, then u ^ 2, then u ^ 1 (lanes ^ 4, ^ 16, ^ 8), then (s0 + s2) + (s1 + s3)
+            float sw[4][2];
+#pragma unroll
+            for (int i = 0; i < 2; ++i)
+#pragma unroll
+                for (int hi = 0; hi < 2; ++hi)
+#pragma unroll
+                    for (int e = 0; e < 2; ++e) {
+                        float y = p[i][2 * hi + e];
+                        y = __fadd_rn(y, __shfl_xor_sync(0xffffffffu, y, 4));
+                        y = __fadd_rn(y, __shfl_xor_sync(0xffffffffu, y, 16));
+                        y = __fadd_rn(y, __shfl_xor_sync(0xffffffffu, y, 8));
+                        sw[2 * i + hi][e] = y;
+                    }
+#pragma unroll
+            for (int e = 0; e < 2; ++e) {
+                const float tot = __fadd_rn(__fadd_rn(sw[0][e], sw[2][e]), __fadd_rn(sw[1][e], sw[3][e]));
+                l[e] = __fmaf_rn(l[e], alpha[e], tot);
+                m[e] = nm[e];
+            }
+#pragma unroll
+            for (int s = 24; s < 32; ++s) QKSTEP(s)
+            if (t > 0) bar_sync(BAR_PFREE, N_QV);         // the PV warps have read the previous P and alphas
+#pragma unroll
+            for (int i = 0; i < 2; ++i)
+#pragma unroll
+                for (int x = 0; x < 4; ++x) {
+                    const int h = 8 * j + 2 * t4 + (x & 1), key = 16 * i + 8 * (x >> 1) + g;
+                    S.ps[h * KT + 8 * pswz(h, key >> 3) + (key & 7)] = bf16(__fmul_rn(p[i][x], kk[i][x >> 1]));
+                }
+            if (g == 0) {
+                S.alpha[8 * j + 2 * t4] = alpha[0];
+                S.alpha[8 * j + 2 * t4 + 1] = alpha[1];
+            }
+            bar_arrive(BAR_PREADY, N_QV);
+#pragma unroll
+            for (int i = 0; i < 2; ++i)
+#pragma unroll
+                for (int e = 0; e < 4; ++e) acc[i][e] = accn[i][e];
+            b = bn;
+        }
+#undef QKSTEP
+#undef QKBEGIN
+#undef LOADA
+        if (g == 0) {
+            S.lsum[8 * j + 2 * t4] = l[0];
+            S.lsum[8 * j + 2 * t4 + 1] = l[1];
+        }
+        bar_arrive(BAR_FIN, N_QV);
+        return;
+    }
+
+    // ------------------------------------------------- PV warps: latent rows 16 tb .. 16 (tb + nt) - 1 (nt m16 tiles)
+    const int v = warp < 4 ? warp : 4;
+    const int nt = pv_tiles(v);
+    int tb = 0;
+#pragma unroll
+    for (int k = 0; k < NV - 1; ++k) tb += k < v ? pv_tiles(k) : 0;
+    float o[PV_MAX][3][4];
+#pragma unroll
+    for (int i = 0; i < PV_MAX; ++i)
+#pragma unroll
+        for (int nh = 0; nh < 3; ++nh)
+#pragma unroll
+            for (int e = 0; e < 4; ++e) o[i][nh][e] = 0.0f;
+    const unsigned psb = (unsigned)__cvta_generic_to_shared(S.ps);
+    const int vk = (lane & 7) + 8 * (lane >> 4), vc = (lane >> 3) & 1;
+    int b = 0;
+    for (int t = 0; t < ntile; ++t) {
+        const unsigned ktb = (unsigned)__cvta_generic_to_shared(S.kt[b]);
+        bar_sync(BAR_PREADY, N_QV);
+        uint32_t pb[3][4];                                // P^T B fragments: heads 8 nh .., keys 0-15 (0, 1), 16-31
+#pragma unroll
+        for (int nh = 0; nh < 3; ++nh) {
+            const int h = 8 * nh + (lane & 7), c = lane >> 3;
+            ldsm_x4(pb[nh], psb + 2 * (h * KT + 8 * pswz(h, c)));
+        }
+        float al[3][2];
+#pragma unroll
+        for (int nh = 0; nh < 3; ++nh) {
+            al[nh][0] = S.alpha[8 * nh + 2 * t4];
+            al[nh][1] = S.alpha[8 * nh + 2 * t4 + 1];
+        }
+        if (t + 1 < ntile) bar_arrive(BAR_PFREE, N_QV);   // the QK warps write the next P only after this
+        bool one = true;
+#pragma unroll
+        for (int nh = 0; nh < 3; ++nh) one = one && al[nh][0] == 1.0f && al[nh][1] == 1.0f;
+        if (!__all_sync(0xffffffffu, one)) {
+#pragma unroll
+            for (int i = 0; i < PV_MAX; ++i)
+                if (i < nt)
+#pragma unroll
+                    for (int nh = 0; nh < 3; ++nh)
+#pragma unroll
+                        for (int e = 0; e < 4; ++e) o[i][nh][e] = __fmul_rn(o[i][nh][e], al[nh][e & 1]);
+        }
+        uint32_t a[2][2][4];                              // K^T A fragments, two m16 tiles in flight
+#define LOADV(slot, i)                                                                                    \
+    {                                                                                                     \
+        ldsm_x4_t(a[slot][0], ktb + 16 * (vk * CH + swz(vk, 2 * (tb + (i)) + vc)));                       \
+        ldsm_x4_t(a[slot][1], ktb + 16 * ((16 + vk) * CH + swz(16 + vk, 2 * (tb + (i)) + vc)));           \
+    }
+        LOADV(0, 0)
+#pragma unroll
+        for (int i = 0; i < PV_MAX; ++i) {
+            if (i < nt) {
+                if (i + 1 < nt) LOADV((i + 1) & 1, i + 1)
+#pragma unroll
+                for (int nh = 0; nh < 3; ++nh) mma16816(o[i][nh], a[i & 1][0], pb[nh][0], pb[nh][1]);
+#pragma unroll
+                for (int nh = 0; nh < 3; ++nh) mma16816(o[i][nh], a[i & 1][1], pb[nh][2], pb[nh][3]);
+            }
+        }
+#undef LOADV
+        if (t + NB < ntile) bar_arrive(BAR_EMPTY + b, N_EMPTY);
+        b = b + 1 == NB ? 0 : b + 1;
+    }
+    bar_sync(BAR_FIN, N_QV);
+    float lv[3][2];
+#pragma unroll
+    for (int nh = 0; nh < 3; ++nh) {
+        lv[nh][0] = S.lsum[8 * nh + 2 * t4];
+        lv[nh][1] = S.lsum[8 * nh + 2 * t4 + 1];
+    }
+    // out[r, h, 16 tb ..] = bf16(o / l): staged as [head][512] in the key-tile buffer no warp reads any more
+    uint16_t* st = reinterpret_cast<uint16_t*>(S.kt[ntile % NB]);
+#pragma unroll
+    for (int i = 0; i < PV_MAX; ++i)
+        if (i < nt)
+#pragma unroll
+            for (int nh = 0; nh < 3; ++nh)
+#pragma unroll
+                for (int e = 0; e < 4; ++e) {
+                    const int h = 8 * nh + 2 * t4 + (e & 1), lat = 16 * (tb + i) + g + 8 * (e >> 1);
+                    st[h * LW + lat] = bf16(div_full(o[i][nh][e], lv[nh][e & 1]));
+                }
+    __syncwarp();
+    for (int c = lane; c < H * 2 * nt; c += 32) {
+        const int h = c / (2 * nt), q = c - h * 2 * nt;
+        *reinterpret_cast<uint4*>(OUT + ((size_t)r * H + h) * LW + 16 * tb + 8 * q) =
+            *reinterpret_cast<const uint4*>(st + h * LW + 16 * tb + 8 * q);
+    }
+}
+
+}  // namespace
+
+// latent.sparse_onepass on an FP8 cache: QA [R, H, 512] bf16 (H <= 24), LC the cache's rows (512 e4m3 codes, then
+// the row's fp32 scale; RS bytes apart), TOK [R, W] int32 token ids (the first CNT[r] of row r read), CNT [R] int32,
+// OUT [R, H, 512] bf16 (rows with CNT 0 left alone), scale the softmax scale. One CTA a row.
+void onepass(const at::Tensor& QA, const at::Tensor& LC, int64_t RS, const at::Tensor& TOK, const at::Tensor& CNT,
+             at::Tensor OUT, double scale) {
+    TORCH_CHECK(QA.is_cuda() && QA.scalar_type() == at::kBFloat16 && OUT.scalar_type() == at::kBFloat16 &&
+                LC.element_size() == 1 && TOK.scalar_type() == at::kInt && CNT.scalar_type() == at::kInt,
+                "sparse onepass: dtypes");
+    TORCH_CHECK(QA.dim() == 3 && QA.size(2) == LW && QA.size(1) <= HQ && QA.is_contiguous() && OUT.is_contiguous() &&
+                OUT.sizes() == QA.sizes() && TOK.is_contiguous() && TOK.dim() == 2 && TOK.size(0) == QA.size(0) &&
+                CNT.numel() >= QA.size(0) && LC.is_contiguous(), "sparse onepass: shapes");
+    TORCH_CHECK(RS % 16 == 0 && RS >= LW + 4, "sparse onepass: an FP8 cache of 16-byte aligned rows");
+    const int R = (int)QA.size(0);
+    if (R == 0) return;
+    const c10::cuda::CUDAGuard guard(QA.device());
+    static bool attr = false;
+    if (!attr) {
+        C10_CUDA_CHECK(cudaFuncSetAttribute(onepass_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize,
+                                            (int)sizeof(Smem)));
+        attr = true;
+    }
+    onepass_kernel<<<R, NT, sizeof(Smem), at::cuda::getCurrentCUDAStream()>>>(
+        reinterpret_cast<const __nv_bfloat16*>(QA.data_ptr()), reinterpret_cast<const uint8_t*>(LC.data_ptr()),
+        (int)RS, TOK.data_ptr<int32_t>(), (int)TOK.size(1), CNT.data_ptr<int32_t>(),
+        reinterpret_cast<__nv_bfloat16*>(OUT.data_ptr()), (int)QA.size(1), (float)scale);
+    C10_CUDA_KERNEL_LAUNCH_CHECK();
+}
+
+PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("onepass", &onepass); }