okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

waveringanaRestore the DeepSeek V4.1 engine and CPU tests removed upstream8ac8ce32e

main
9.7 KiB206 linesraw
1// Split-KV sparse attention: Strata (dsv41 CUDA lab), used with the DeepSeek attention of Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17).
2// (the surrounding types, AttnRows and the packed-row formats, are theirs; see third_party/project-maya/NOTICE.md).
3// src/dsv41/ds4_attn_split.cuh - split-KV ("flash-decoding") version of DeepSeek's sparse attention for a few queries
4// (decode T = 1, DSpark verify T = 2..5): 64 heads x d 512, MQA (K = V), window rows (BF16) + selected compressed rows (kKvFp4:
5// E2M1 codes + E4M3 scales per 16) + a learned sink logit per head.  Same inputs and outputs as strata::ds4::sparse_attn
6// (AttnRows gen 0, ckv kKvFp4); the shipped kernel runs one 256-thread block per (head, query) = 64 blocks on 48 SMs and takes
7// ~125 us per query; this one splits the keys over R-row chunks and groups G heads per block, which share the decoded rows.
8//   phase 1: block (head group, chunk, query): decode R rows to BF16 in shared memory (exact: window rows are BF16, packed
9//            rows have <= 7 significant bits), scores for G heads (warp per row, lanes 16 values, shuffle reduction), local
10//            softmax, partial output (thread = 2 output values) -> scratch {m, l, o[512]} per (query, head, chunk)
11//   phase 2: block (head, query): merge the chunks and the sink.
12// Plain C++ (no PTX), shuffles and shared memory only: the HIP port is a rename.
13#pragma once
14#include "ds4_kernels.cuh"
15#include "ds4_numerics.cuh"
16#include <cuda_fp16.h>
17
18namespace strata::ds4 {
19namespace attnsplit {
20
21
22
23__device__ __forceinline__ float bf2f_(uint16_t b) { return __uint_as_float((uint32_t) b << 16); }
24__device__ __forceinline__ uint16_t f2bf_exact(float f) { return (uint16_t) (__float_as_uint(f) >> 16); }   // exact values only
25__device__ __forceinline__ float e2m1_x2p14(uint32_t c) {
26    return __half2float(__ushort_as_half((unsigned short) (((c & 8u) << 12) | ((c & 7u) << 9))));
27}
28__device__ __forceinline__ float wsum(float v) {
29#pragma unroll
30    for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o);
31    return v;
32}
33__device__ __forceinline__ float wmax(float v) {
34#pragma unroll
35    for (int o = 16; o > 0; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, o));
36    return v;
37}
38
39// d = 512 only (a thread owns 2 output values, a lane 16 values of a row)
40template <int G, int R>
41__global__ void __launch_bounds__(256) attn_part(const float* __restrict__ q, const uint16_t* __restrict__ win,
42                                                 const uint8_t* __restrict__ ckv, size_t ckv_row_bytes, const int* __restrict__ sel,
43                                                 int sel_stride, AttnRows ar, int heads, float scale, float* __restrict__ part,
44                                                 float* __restrict__ ml, int nsplit) {
45    constexpr int D = 512;
46    __shared__ __align__(16) uint16_t rows[R][D];
47    __shared__ float sc[G][R];
48    __shared__ float4 pr[R][(G + 3) / 4];
49    __shared__ float mloc[G], lloc[G];
50    const int hg = blockIdx.x, chunk = blockIdx.y, t = blockIdx.z;
51    const int n_win = ar.nwin[t], n_sel = ar.nsel[t], total = n_win + n_sel;
52    const int j0 = chunk * R;
53    if (j0 >= total) return;
54    const int nr = min(R, total - j0);
55    const int lane = threadIdx.x & 31, wp = threadIdx.x >> 5;
56    // q of this block's heads: lane's 16 values per head in registers (issued first: its latency overlaps the row loads)
57    float qv[G][16];
58#pragma unroll
59    for (int g = 0; g < G; ++g) {
60        const float4* qp = (const float4*) (q + ((size_t) t * heads + hg * G + g) * D + lane * 16);
61#pragma unroll
62        for (int i = 0; i < 4; ++i) { const float4 v = qp[i]; qv[g][4 * i] = v.x; qv[g][4 * i + 1] = v.y; qv[g][4 * i + 2] = v.z; qv[g][4 * i + 3] = v.w; }
63    }
64    // ---- stage rows: warp per row, lane = 16 values; all of a warp's row loads are issued before any is converted
65    constexpr int RPW = (R + 7) / 8;
66    uint4 wa[RPW][2];
67    uint2 cwv[RPW];
68    uint32_t sbv[RPW];
69    int rowoff[RPW];
70#pragma unroll
71    for (int i = 0; i < RPW; ++i) {
72        const int jj = wp + 8 * i, j = j0 + jj;
73        rowoff[i] = -1;
74        if (jj < nr) {
75            if (j < n_win) {
76                const uint4* src = (const uint4*) (win + (size_t) (ar.win0[t] + j) * D + lane * 16);
77                wa[i][0] = src[0];
78                wa[i][1] = src[1];
79            } else {
80                rowoff[i] = sel[(size_t) t * sel_stride + (j - n_win)];
81            }
82        }
83    }
84#pragma unroll
85    for (int i = 0; i < RPW; ++i)
86        if (rowoff[i] >= 0) {
87            const uint8_t* r = ckv + (size_t) rowoff[i] * ckv_row_bytes;
88            cwv[i] = *(const uint2*) (r + lane * 8);
89            sbv[i] = r[D / 2 + lane];
90        }
91#pragma unroll
92    for (int i = 0; i < RPW; ++i) {
93        const int jj = wp + 8 * i;
94        if (jj >= nr) continue;
95        uint4* dst = (uint4*) &rows[jj][lane * 16];
96        if (rowoff[i] < 0) {
97            dst[0] = wa[i][0];
98            dst[1] = wa[i][1];
99        } else {
100            const float s = e4m3_value((uint8_t) sbv[i]) * 16384.0f;   // (the nibbles decode to value * 2^-14)
101            uint32_t o[8];
102#pragma unroll
103            for (int w = 0; w < 2; ++w) {
104                const uint32_t c = w ? cwv[i].y : cwv[i].x;
105#pragma unroll
106                for (int x = 0; x < 4; ++x) {
107                    const uint32_t b = c >> (8 * x);
108                    const uint16_t lo = f2bf_exact(e2m1_x2p14(b) * s), hi = f2bf_exact(e2m1_x2p14(b >> 4) * s);
109                    o[4 * w + x] = (uint32_t) lo | ((uint32_t) hi << 16);
110                }
111            }
112            dst[0] = make_uint4(o[0], o[1], o[2], o[3]);
113            dst[1] = make_uint4(o[4], o[5], o[6], o[7]);
114        }
115    }
116    __syncthreads();
117    // ---- scores
118    for (int jj = wp; jj < nr; jj += 8) {
119        const uint4 a = *(const uint4*) &rows[jj][lane * 16], b = *(const uint4*) &rows[jj][lane * 16 + 8];
120        float kv[16];
121        const uint32_t w[8] = {a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w};
122#pragma unroll
123        for (int i = 0; i < 8; ++i) { kv[2 * i] = __uint_as_float(w[i] << 16); kv[2 * i + 1] = __uint_as_float(w[i] & 0xffff0000u); }
124#pragma unroll
125        for (int g = 0; g < G; ++g) {
126            float s = 0.f;
127#pragma unroll
128            for (int i = 0; i < 16; ++i) s += qv[g][i] * kv[i];
129            s = wsum(s);
130            if (lane == 0) sc[g][jj] = s * scale;
131        }
132    }
133    __syncthreads();
134    // ---- local softmax: warp g handles head g
135    if (wp < G) {
136        float m = -INFINITY;
137        for (int j = lane; j < nr; j += 32) m = fmaxf(m, sc[wp][j]);
138        m = wmax(m);
139        float l = 0.f;
140        for (int j = lane; j < nr; j += 32) { const float p = __expf(sc[wp][j] - m); sc[wp][j] = p; l += p; }
141        l = wsum(l);
142        if (lane == 0) { mloc[wp] = m; lloc[wp] = l; }
143    }
144    __syncthreads();
145    for (int i = threadIdx.x; i < nr * G; i += 256) { const int j = i / G, g = i % G; ((float*) &pr[j][0])[g] = sc[g][j]; }
146    __syncthreads();
147    // ---- partial output: thread = values 2 tid, 2 tid + 1 of every head
148    float o0[G], o1[G];
149#pragma unroll
150    for (int g = 0; g < G; ++g) o0[g] = o1[g] = 0.f;
151    const int c = threadIdx.x * 2;
152    for (int j = 0; j < nr; ++j) {
153        const uint32_t kw = *(const uint32_t*) &rows[j][c];
154        const float k0 = __uint_as_float(kw << 16), k1 = __uint_as_float(kw & 0xffff0000u);
155        const float* p = (const float*) &pr[j][0];
156#pragma unroll
157        for (int g = 0; g < G; ++g) { o0[g] += p[g] * k0; o1[g] += p[g] * k1; }
158    }
159#pragma unroll
160    for (int g = 0; g < G; ++g) {
161        const size_t bi = ((size_t) t * heads + hg * G + g) * nsplit + chunk;
162        *(float2*) (part + bi * D + c) = make_float2(o0[g], o1[g]);
163        if (threadIdx.x == 0) { ml[bi * 2] = mloc[g]; ml[bi * 2 + 1] = lloc[g]; }
164    }
165}
166
167__global__ void __launch_bounds__(256) attn_merge(const float* __restrict__ part, const float* __restrict__ ml, const float* __restrict__ sink,
168                                                  int heads, int nsplit, int R, AttnRows ar, float* __restrict__ out) {
169    constexpr int D = 512;
170    const int h = blockIdx.x, t = blockIdx.y;
171    const int total = ar.nwin[t] + ar.nsel[t];
172    const int ns = (total + R - 1) / R;
173    const size_t base = ((size_t) t * heads + h) * nsplit;
174    float M = sink[h];
175    for (int s = 0; s < ns; ++s) M = fmaxf(M, ml[(base + s) * 2]);
176    float den = __expf(sink[h] - M);
177    for (int s = 0; s < ns; ++s) den += ml[(base + s) * 2 + 1] * __expf(ml[(base + s) * 2] - M);
178    const int c = threadIdx.x * 2;
179    float a0 = 0.f, a1 = 0.f;
180    for (int s = 0; s < ns; ++s) {
181        const float w = __expf(ml[(base + s) * 2] - M);
182        const float2 v = *(const float2*) (part + (base + s) * D + c);
183        a0 += w * v.x;
184        a1 += w * v.y;
185    }
186    *(float2*) (out + ((size_t) t * heads + h) * D + c) = make_float2(a0 / den, a1 / den);
187}
188
189struct AttnSplitScratch {
190    float* part = nullptr;   // [T][heads][nsplit][512]
191    float* ml = nullptr;     // [T][heads][nsplit][2]
192    int nsplit = 0, max_t = 0;
193};
194
195// total_max = the largest nwin + nsel of the T queries
196template <int G, int R>
197void sparse_attn_split(const float* q, const uint16_t* win, const uint8_t* ckv, size_t ckv_row_bytes, const int* sel, int sel_stride,
198                       const AttnRows& ar, const float* sink, int heads, int T, float scale, float* out, const AttnSplitScratch& sc,
199                       int total_max, cudaStream_t s) {
200    const int nsplit = (total_max + R - 1) / R;
201    attn_part<G, R><<<dim3(heads / G, nsplit, T), 256, 0, s>>>(q, win, ckv, ckv_row_bytes, sel, sel_stride, ar, heads, scale, sc.part, sc.ml, sc.nsplit);
202    attn_merge<<<dim3(heads, T), 256, 0, s>>>(sc.part, sc.ml, sink, heads, sc.nsplit, R, ar, out);
203}
204
205}  // namespace attnsplit
206}  // namespace strata::ds4