okami.mom/strata

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

Niko1221Merge f-own-5b e93b90250 into f-own-intd4eac2ca3

main
30.2 KiB657 linesraw
1// src/image/dit/qi21_kernels.cu - see qi21_kernels.hpp.  The kernels from tools/image/sdcpp_native/qi21-native.cu
2// (k_res_ln_mod, k_qkv_post_w, k_swiglu, k_attn_causal, k_attn_mma, k_attn_wmma) with the ggml headers taken out:
3// the bodies and launch shapes are unchanged, so a step computes what the native runner's kernels computed.  New here:
4// the timestep sinusoid, SiLU, GELU and txt_in's RMSNorm, written as ggml's CUDA kernels compute them (same formulas,
5// float maths); their reductions are fixed-order, so a run gives the same bytes every time.
6#include "qi21_kernels.hpp"
7
8#if defined(__HIP__) || defined(__HIPCC__) || defined(__HIP_PLATFORM_AMD__)
9#define QI_HIP 1
10#include "strata/hip_compat/cuda_runtime.h"
11#include "strata/hip_compat/cuda_fp16.h"
12#include "strata/hip_compat/intrinsics.hpp"
13#else
14#include <cuda_fp16.h>
15#include <cuda_runtime.h>
16#endif
17
18#include "strata/kernels/f16_bits.hpp"
19
20#include <cmath>
21#include <cstdint>
22#include <cstdlib>
23#include <cstring>
24
25namespace strata::image::qi21 {
26namespace {
27
28constexpr int QI_D = 128;
29
30// an output element: float as computed, or f16 bits rounded from that float by f16_from_f32 (round to nearest even),
31// the rounding dit_gemm's conversion pass applies, so an f16 store gives the bytes the conversion gave
32__device__ __forceinline__ void qi_put(float* p, size_t i, float v) { p[i] = v; }
33__device__ __forceinline__ void qi_put(uint16_t* p, size_t i, float v) { p[i] = strata::kernels::f16_from_f32(v); }
34
35__device__ __forceinline__ float qi_block_sum(float v, float* red) {
36    // blockDim.x is a multiple of 32 and <= 1024
37    for (int off = 16; off > 0; off >>= 1) v += __shfl_xor_sync(0xffffffff, v, off, 32);
38    const int w = threadIdx.x >> 5, l = threadIdx.x & 31;
39    __syncthreads();
40    if (l == 0) red[w] = v;
41    __syncthreads();
42    const int nw = blockDim.x >> 5;
43    float s = (int) threadIdx.x < nw ? red[threadIdx.x] : 0.f;
44    if (w == 0) {
45        for (int off = 16; off > 0; off >>= 1) s += __shfl_xor_sync(0xffffffff, s, off, 32);
46        if (l == 0) red[0] = s;
47    }
48    __syncthreads();
49    return red[0];
50}
51
52template <bool RES, bool LN, typename OT>
53__global__ void __launch_bounds__(256) k_res_ln_mod(float* __restrict__ x, const float* __restrict__ h,
54                                                   const float* __restrict__ g, OT* __restrict__ out,
55                                                   const float* __restrict__ m, int C, float eps) {
56    __shared__ float red[32];
57    const size_t row = blockIdx.x;
58    float* xr = x + row * C;
59    float v[32];
60    int n = 0;
61    float s = 0.f;
62    for (int c = threadIdx.x; c < C; c += blockDim.x) {
63        float a = xr[c];
64        if (RES) {
65            a += h[row * C + c] * tanhf(g[c]);
66            xr[c] = a;
67        }
68        v[n++] = a;
69        s += a;
70    }
71    if (!LN) return;
72    const float mean = qi_block_sum(s, red) / C;
73    float q = 0.f;
74    for (int i = 0; i < n; ++i) q += (v[i] - mean) * (v[i] - mean);
75    const float inv = rsqrtf(qi_block_sum(q, red) / C + eps);
76    n = 0;
77    for (int c = threadIdx.x; c < C; c += blockDim.x) qi_put(out, row * C + c, (v[n++] - mean) * inv * (1.f + m[c]));
78}
79
80template <typename QT>
81__device__ __forceinline__ void qi_store4(QT* dst, float a, float b, float c, float d);
82template <>
83__device__ __forceinline__ void qi_store4<float>(float* dst, float a, float b, float c, float d) {
84    *reinterpret_cast<float4*>(dst) = make_float4(a, b, c, d);
85}
86template <>
87__device__ __forceinline__ void qi_store4<half>(half* dst, float a, float b, float c, float d) {
88    half2 lo = __floats2half2_rn(a, b), hi2 = __floats2half2_rn(c, d);
89    uint2 u;
90    u.x = *reinterpret_cast<uint32_t*>(&lo);
91    u.y = *reinterpret_cast<uint32_t*>(&hi2);
92    *reinterpret_cast<uint2*>(dst) = u;
93}
94
95// warp per head: grid (T, H/8), block 256; lane holds dims 4*lane..+3 (two RoPE pairs), no shared memory
96template <typename QT>
97__global__ void __launch_bounds__(256) k_qkv_post_w(const float* __restrict__ q, const float* __restrict__ k,
98                                                   const float* __restrict__ v, int ld, const float* __restrict__ wq,
99                                                   const float* __restrict__ wk, const float* __restrict__ pe,
100                                                   QT* __restrict__ qo, int q_tstride, half* __restrict__ ko,
101                                                   half* __restrict__ vo, int kv_tstride, int kv_off, float eps) {
102    const int t = blockIdx.x, lane = threadIdx.x & 31, hh = blockIdx.y * 8 + (threadIdx.x >> 5);
103    const int d = lane * 4;
104    const size_t src = (size_t) t * ld + hh * QI_D + d;
105    const float4 p0 = *reinterpret_cast<const float4*>(pe + ((size_t) t * (QI_D / 2) + lane * 2) * 4);
106    const float4 p1 = *reinterpret_cast<const float4*>(pe + ((size_t) t * (QI_D / 2) + lane * 2 + 1) * 4);
107    for (int which = 0; which < 2; ++which) {
108        const float4 x = *reinterpret_cast<const float4*>((which == 0 ? q : k) + src);
109        float ss = x.x * x.x + x.y * x.y + x.z * x.z + x.w * x.w;
110        for (int off = 16; off > 0; off >>= 1) ss += __shfl_xor_sync(0xffffffff, ss, off, 32);
111        const float inv = rsqrtf(ss / QI_D + eps);
112        const float4 w = *reinterpret_cast<const float4*>((which == 0 ? wq : wk) + d);
113        const float y0 = x.x * inv * w.x, y1 = x.y * inv * w.y, y2 = x.z * inv * w.z, y3 = x.w * inv * w.w;
114        const float r0 = p0.x * y0 + p0.y * y1, r1 = p0.z * y0 + p0.w * y1;
115        const float r2 = p1.x * y2 + p1.y * y3, r3 = p1.z * y2 + p1.w * y3;
116        if (which == 0)
117            qi_store4<QT>(qo + ((size_t) hh * q_tstride + t) * QI_D + d, r0, r1, r2, r3);
118        else
119            qi_store4<half>(ko + ((size_t) hh * kv_tstride + kv_off + t) * QI_D + d, r0, r1, r2, r3);
120    }
121    const float4 vv = *reinterpret_cast<const float4*>(v + src);
122    qi_store4<half>(vo + ((size_t) hh * kv_tstride + kv_off + t) * QI_D + d, vv.x, vv.y, vv.z, vv.w);
123}
124
125template <typename OT>
126__global__ void k_swiglu(const float* __restrict__ gu, OT* __restrict__ out, int F, int64_t n) {
127    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
128    if (i >= n) return;
129    const int64_t t = i / F, c = i % F;
130    const float g = gu[t * 2 * F + c], u = gu[t * 2 * F + F + c];
131    qi_put(out, (size_t) i, u * (g / (1.f + expf(-g))));
132}
133
134// grid (Lq, H), block 128, dynamic smem Lk floats.  causal: query i sees keys 0..i.
135template <typename OT>
136__global__ void __launch_bounds__(QI_D) k_attn_causal(const float* __restrict__ q, int q_tstride,
137                                                     const half* __restrict__ k, const half* __restrict__ v,
138                                                     int kv_tstride, OT* __restrict__ out, int H, int Lk,
139                                                     int causal, float scale) {
140    extern __shared__ float s[];
141    __shared__ float red[32];
142    __shared__ float qs[QI_D];
143    const int i = blockIdx.x, hh = blockIdx.y, d = threadIdx.x;
144    qs[d] = q[((size_t) hh * q_tstride + i) * QI_D + d];
145    __syncthreads();
146    const int n = causal ? i + 1 : Lk;
147    float mx = -INFINITY;
148    for (int j = d; j < n; j += QI_D) {
149        const half* kr = k + ((size_t) hh * kv_tstride + j) * QI_D;
150        float dot = 0.f;
151        for (int c = 0; c < QI_D; ++c) dot += qs[c] * __half2float(kr[c]);
152        s[j] = dot * scale;
153        mx = fmaxf(mx, s[j]);
154    }
155    for (int off = 16; off > 0; off >>= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffff, mx, off, 32));
156    __syncthreads();
157    if ((d & 31) == 0) red[d >> 5] = mx;
158    __syncthreads();
159    mx = red[0];
160    for (int w = 1; w < QI_D / 32; ++w) mx = fmaxf(mx, red[w]);
161    __syncthreads();
162    float sum = 0.f;
163    for (int j = d; j < n; j += QI_D) {
164        s[j] = expf(s[j] - mx);
165        sum += s[j];
166    }
167    sum = qi_block_sum(sum, red);
168    float acc = 0.f;
169    for (int j = 0; j < n; ++j) acc += s[j] * __half2float(v[((size_t) hh * kv_tstride + j) * QI_D + d]);
170    qi_put(out, (size_t) i * H * QI_D + hh * QI_D + d, acc / sum);
171}
172
173#if defined(QI_HIP)
174// WMMA fragments: gfx11 (RDNA3) lanes hold 16 k-values of their row/column (lanes 16..31 duplicate 0..15) and C row
175// 2i + (lane >> 4); gfx12 (RDNA4) lanes hold 8 k-values at offset 8 * (lane >> 4) and C row 8 * (lane >> 4) + i.
176#if defined(__gfx1200__) || defined(__gfx1201__)
177#define QI_RDNA4 1
178#define QI_KL 8
179#define QI_KOFF(hi) ((hi) * 8)
180#define QI_ROW(i, hi) ((hi) * 8 + (i))
181#define QI_WMMA __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12
182#elif defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || \
183    defined(__gfx1150__) || defined(__gfx1151__) || defined(__gfx1152__)
184#define QI_RDNA3 1
185#endif
186#if !defined(QI_KL)
187#define QI_KL 16
188#define QI_KOFF(hi) 0
189#define QI_ROW(i, hi) (2 * (i) + (hi))
190#define QI_WMMA __builtin_amdgcn_wmma_f32_16x16x16_f16_w32
191#endif
192typedef _Float16 qi_h16 __attribute__((ext_vector_type(QI_KL)));
193typedef float qi_f8 __attribute__((ext_vector_type(8)));
194constexpr int FA_BQ = 128, FA_BKV = 64, FA_NW = 8, FA_KLD = QI_D + 8, FA_VLD = FA_BKV + 8, FA_PLD = FA_BKV + 8;
195
196__device__ __forceinline__ qi_h16 qi_ld16(const _Float16* p, int hi) {
197#if QI_KL == 8
198    return __builtin_bit_cast(qi_h16, *reinterpret_cast<const uint4*>(p + QI_KOFF(hi)));
199#else
200    (void) hi;
201    const uint4 a = *reinterpret_cast<const uint4*>(p), b = *reinterpret_cast<const uint4*>(p + 8);
202    const uint32_t w[8] = {a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w};
203    return __builtin_bit_cast(qi_h16, w);
204#endif
205}
206
207template <typename OT>
208__global__ void __launch_bounds__(FA_NW * 32) k_attn_wmma(const _Float16* __restrict__ Q, int q_tstride,
209                                                         const _Float16* __restrict__ K, const _Float16* __restrict__ V,
210                                                         int kv_tstride, OT* __restrict__ O, int H, int nq, int nkv,
211                                                         float scale_log2) {
212#if defined(QI_RDNA3) || defined(QI_RDNA4)
213    __shared__ __align__(16) _Float16 sK[FA_BKV][FA_KLD];
214    __shared__ __align__(16) _Float16 sVt[QI_D][FA_VLD];
215    __shared__ __align__(16) _Float16 sP[FA_NW][16][FA_PLD];
216    const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, l16 = lane & 15, hi = lane >> 4;
217    const int head = blockIdx.y, q0 = blockIdx.x * FA_BQ + wave * 16;
218    const _Float16* Qh = Q + (size_t) head * q_tstride * QI_D;
219    const _Float16* Kh = K + (size_t) head * kv_tstride * QI_D;
220    const _Float16* Vh = V + (size_t) head * kv_tstride * QI_D;
221    qi_h16 qa[QI_D / 16];
222    {
223        const int qr = min(q0 + l16, nq - 1);
224        for (int c = 0; c < QI_D / 16; ++c) qa[c] = qi_ld16(Qh + (size_t) qr * QI_D + c * 16, hi);
225    }
226    qi_f8 o[QI_D / 16];
227    for (int c = 0; c < QI_D / 16; ++c) o[c] = qi_f8{};
228    float m[8], l[8];
229    for (int i = 0; i < 8; ++i) { m[i] = -INFINITY; l[i] = 0.f; }
230    for (int k0 = 0; k0 < nkv; k0 += FA_BKV) {
231        __syncthreads();
232        for (int e = tid * 8; e < FA_BKV * QI_D; e += FA_NW * 32 * 8) {
233            const int r = e / QI_D, c = e % QI_D, key = k0 + r;
234            uint4 kv = make_uint4(0, 0, 0, 0);
235            if (key < nkv) kv = *reinterpret_cast<const uint4*>(Kh + (size_t) key * QI_D + c);
236            *reinterpret_cast<uint4*>(&sK[r][c]) = kv;
237        }
238        for (int e = tid; e < (FA_BKV / 4) * (QI_D / 8); e += FA_NW * 32) {
239            const int r4 = (e / (QI_D / 8)) * 4, c = (e % (QI_D / 8)) * 8;
240            _Float16 vv[4][8];
241            for (int j = 0; j < 4; ++j) {
242                uint4 x = make_uint4(0, 0, 0, 0);
243                if (k0 + r4 + j < nkv) x = *reinterpret_cast<const uint4*>(Vh + (size_t) (k0 + r4 + j) * QI_D + c);
244                *reinterpret_cast<uint4*>(vv[j]) = x;
245            }
246            for (int dd = 0; dd < 8; ++dd) {
247                _Float16 w4[4] = {vv[0][dd], vv[1][dd], vv[2][dd], vv[3][dd]};
248                *reinterpret_cast<uint2*>(&sVt[c + dd][r4]) = *reinterpret_cast<uint2*>(w4);
249            }
250        }
251        __syncthreads();
252        qi_f8 s[FA_BKV / 16];
253        for (int t = 0; t < FA_BKV / 16; ++t) {
254            s[t] = qi_f8{};
255            for (int c = 0; c < QI_D / 16; ++c) s[t] = QI_WMMA(qa[c], qi_ld16(&sK[t * 16 + l16][c * 16], hi), s[t]);
256        }
257        float alpha[8];
258        for (int i = 0; i < 8; ++i) {
259            float mx = -INFINITY;
260            for (int t = 0; t < FA_BKV / 16; ++t) {
261                const float val = k0 + t * 16 + l16 < nkv ? s[t][i] * scale_log2 : -INFINITY;
262                s[t][i] = val;
263                mx = fmaxf(mx, val);
264            }
265            for (int off = 1; off < 16; off <<= 1) mx = fmaxf(mx, __shfl_xor(mx, off, 32));
266            const float mnew = fmaxf(m[i], mx);
267            alpha[i] = exp2f(m[i] - mnew);
268            float sum = 0.f;
269            for (int t = 0; t < FA_BKV / 16; ++t) {
270                const float pv = exp2f(s[t][i] - mnew);
271                s[t][i] = pv;
272                sum += pv;
273            }
274            for (int off = 1; off < 16; off <<= 1) sum += __shfl_xor(sum, off, 32);
275            l[i] = l[i] * alpha[i] + sum;
276            m[i] = mnew;
277        }
278        for (int c = 0; c < QI_D / 16; ++c)
279            for (int i = 0; i < 8; ++i) o[c][i] *= alpha[i];
280        for (int t = 0; t < FA_BKV / 16; ++t)
281            for (int i = 0; i < 8; ++i) sP[wave][QI_ROW(i, hi)][t * 16 + l16] = (_Float16) s[t][i];
282        __builtin_amdgcn_s_waitcnt(0);
283        __builtin_amdgcn_wave_barrier();
284        for (int kc = 0; kc < FA_BKV / 16; ++kc) {
285            const qi_h16 pa = qi_ld16(&sP[wave][l16][kc * 16], hi);
286            for (int c = 0; c < QI_D / 16; ++c) o[c] = QI_WMMA(pa, qi_ld16(&sVt[c * 16 + l16][kc * 16], hi), o[c]);
287        }
288    }
289    for (int c = 0; c < QI_D / 16; ++c)
290        for (int i = 0; i < 8; ++i) {
291            const int row = q0 + QI_ROW(i, hi);
292            if (row < nq) qi_put(O, (size_t) row * H * QI_D + head * QI_D + c * 16 + l16, o[c][i] / l[i]);
293        }
294#else
295    __builtin_trap();
296#endif
297}
298#else   // NVIDIA
299// sm_80+: mma.sync m16n8k16 f16 -> f32 flash attention.  8 warps x 16 queries per block, 64-key tiles of K and V
300// (row-major) double-buffered with cp.async, ldmatrix (.trans for V) fragments, fp32 online softmax, P in fp16.
301constexpr int MF_NW = 8, MF_BQ = MF_NW * 16, MF_BKV = 64, MF_LD = QI_D + 8;
302constexpr size_t MF_SMEM = (size_t) 4 * MF_BKV * MF_LD * sizeof(half);
303
304__device__ __forceinline__ void qi_mma16816(float* c, const uint32_t* a, const uint32_t* b) {
305#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800
306    asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};\n"
307                 : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3])
308                 : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b[0]), "r"(b[1]));
309#else
310    (void) c; (void) a; (void) b;
311    __trap();
312#endif
313}
314__device__ __forceinline__ uint32_t qi_pack2(float x, float y) {
315    half2 h = __floats2half2_rn(x, y);
316    return *reinterpret_cast<uint32_t*>(&h);
317}
318__device__ __forceinline__ void qi_ldsm_x4(uint32_t* r, const half* p, bool trans) {
319#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800
320    const uint32_t a = (uint32_t) __cvta_generic_to_shared(p);
321    if (trans)
322        asm volatile("ldmatrix.sync.aligned.m8n8.x4.trans.shared.b16 {%0,%1,%2,%3}, [%4];\n"
323                     : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]) : "r"(a));
324    else
325        asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];\n"
326                     : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]) : "r"(a));
327#else
328    (void) r; (void) p; (void) trans;
329#endif
330}
331__device__ __forceinline__ void qi_cp16(half* dst, const half* src, bool ok) {
332#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800
333    const uint32_t a = (uint32_t) __cvta_generic_to_shared(dst);
334    const int n = ok ? 16 : 0;
335    asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;\n" :: "r"(a), "l"(src), "r"(n));
336#else
337    (void) dst; (void) src; (void) ok;
338#endif
339}
340
341__device__ __forceinline__ void qi_put2(float* p, size_t i, float a, float b) {
342    *reinterpret_cast<float2*>(p + i) = make_float2(a, b);
343}
344// the hardware's round-to-nearest-even pair conversion (the same bits as f16_from_f32 for every finite value and
345// infinity) and one 4-byte store: f16_from_f32's integer code here doubled the kernel's time (spills in the epilogue)
346__device__ __forceinline__ void qi_put2(uint16_t* p, size_t i, float a, float b) {
347    half2 h = __floats2half2_rn(a, b);
348    *reinterpret_cast<uint32_t*>(p + i) = *reinterpret_cast<uint32_t*>(&h);
349}
350
351template <typename OT>
352__global__ void __launch_bounds__(MF_NW * 32) k_attn_mma(const half* __restrict__ Q, int q_tstride,
353                                                        const half* __restrict__ K, const half* __restrict__ V,
354                                                        int kv_tstride, OT* __restrict__ O, int H, int nq, int nkv,
355                                                        float scale_log2) {
356#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800
357    extern __shared__ __align__(16) half qi_smem[];
358    const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
359    const int r = lane >> 2, c2 = (lane & 3) * 2, lr = lane & 7, lq = lane >> 3;
360    const int head = blockIdx.y, q0 = blockIdx.x * MF_BQ + warp * 16;
361    const half* Qh = Q + (size_t) head * q_tstride * QI_D;
362    const half* Kh = K + (size_t) head * kv_tstride * QI_D;
363    const half* Vh = V + (size_t) head * kv_tstride * QI_D;
364    auto tile = [&](int st, int kv) { return qi_smem + ((st * 2 + kv) * MF_BKV) * MF_LD; };
365    auto load = [&](int st, int k0) {
366        for (int e = tid * 8; e < MF_BKV * QI_D; e += MF_NW * 32 * 8) {
367            const int rr = e / QI_D, cc = e % QI_D, key = k0 + rr;
368            const bool ok = key < nkv;
369            const size_t off = (size_t) (ok ? key : 0) * QI_D + cc;
370            qi_cp16(tile(st, 0) + rr * MF_LD + cc, Kh + off, ok);
371            qi_cp16(tile(st, 1) + rr * MF_LD + cc, Vh + off, ok);
372        }
373        asm volatile("cp.async.commit_group;\n");
374    };
375    uint32_t qa[QI_D / 16][4];
376    {
377        const int r0 = min(q0 + r, nq - 1), r1 = min(q0 + r + 8, nq - 1);
378        for (int kc = 0; kc < QI_D / 16; ++kc) {
379            qa[kc][0] = *reinterpret_cast<const uint32_t*>(Qh + (size_t) r0 * QI_D + kc * 16 + c2);
380            qa[kc][1] = *reinterpret_cast<const uint32_t*>(Qh + (size_t) r1 * QI_D + kc * 16 + c2);
381            qa[kc][2] = *reinterpret_cast<const uint32_t*>(Qh + (size_t) r0 * QI_D + kc * 16 + c2 + 8);
382            qa[kc][3] = *reinterpret_cast<const uint32_t*>(Qh + (size_t) r1 * QI_D + kc * 16 + c2 + 8);
383        }
384    }
385    float o[QI_D / 8][4];
386    for (int n = 0; n < QI_D / 8; ++n) o[n][0] = o[n][1] = o[n][2] = o[n][3] = 0.f;
387    float m0 = -INFINITY, m1 = -INFINITY, l0 = 0.f, l1 = 0.f;
388    const int ntiles = (nkv + MF_BKV - 1) / MF_BKV;
389    load(0, 0);
390    for (int it = 0; it < ntiles; ++it) {
391        const int st = it & 1, k0 = it * MF_BKV;
392        if (it + 1 < ntiles) {
393            load(st ^ 1, k0 + MF_BKV);
394            asm volatile("cp.async.wait_group 1;\n");
395        } else {
396            asm volatile("cp.async.wait_group 0;\n");
397        }
398        __syncthreads();
399        const half* sK = tile(st, 0);
400        const half* sV = tile(st, 1);
401        float s[MF_BKV / 8][4];
402        for (int t = 0; t < MF_BKV / 8; ++t) {
403            s[t][0] = s[t][1] = s[t][2] = s[t][3] = 0.f;
404            for (int kc = 0; kc < QI_D / 16; kc += 2) {
405                uint32_t b[4];
406                qi_ldsm_x4(b, sK + (t * 8 + lr) * MF_LD + kc * 16 + lq * 8, false);
407                qi_mma16816(s[t], qa[kc], b);
408                qi_mma16816(s[t], qa[kc + 1], b + 2);
409            }
410        }
411        float mx0 = -INFINITY, mx1 = -INFINITY;
412        for (int t = 0; t < MF_BKV / 8; ++t)
413            for (int j = 0; j < 2; ++j) {
414                const bool ok = k0 + t * 8 + c2 + j < nkv;
415                s[t][j] = ok ? s[t][j] * scale_log2 : -INFINITY;
416                s[t][2 + j] = ok ? s[t][2 + j] * scale_log2 : -INFINITY;
417                mx0 = fmaxf(mx0, s[t][j]);
418                mx1 = fmaxf(mx1, s[t][2 + j]);
419            }
420        for (int off = 1; off < 4; off <<= 1) {
421            mx0 = fmaxf(mx0, __shfl_xor_sync(0xffffffff, mx0, off));
422            mx1 = fmaxf(mx1, __shfl_xor_sync(0xffffffff, mx1, off));
423        }
424        const float mn0 = fmaxf(m0, mx0), mn1 = fmaxf(m1, mx1);
425        const float a0 = exp2f(m0 - mn0), a1 = exp2f(m1 - mn1);
426        float sum0 = 0.f, sum1 = 0.f;
427        for (int t = 0; t < MF_BKV / 8; ++t)
428            for (int j = 0; j < 2; ++j) {
429                s[t][j] = exp2f(s[t][j] - mn0);
430                s[t][2 + j] = exp2f(s[t][2 + j] - mn1);
431                sum0 += s[t][j];
432                sum1 += s[t][2 + j];
433            }
434        for (int off = 1; off < 4; off <<= 1) {
435            sum0 += __shfl_xor_sync(0xffffffff, sum0, off);
436            sum1 += __shfl_xor_sync(0xffffffff, sum1, off);
437        }
438        l0 = l0 * a0 + sum0;
439        l1 = l1 * a1 + sum1;
440        m0 = mn0;
441        m1 = mn1;
442        for (int n = 0; n < QI_D / 8; ++n) {
443            o[n][0] *= a0; o[n][1] *= a0; o[n][2] *= a1; o[n][3] *= a1;
444        }
445        for (int kc = 0; kc < MF_BKV / 16; ++kc) {
446            uint32_t pa[4];
447            pa[0] = qi_pack2(s[2 * kc][0], s[2 * kc][1]);
448            pa[1] = qi_pack2(s[2 * kc][2], s[2 * kc][3]);
449            pa[2] = qi_pack2(s[2 * kc + 1][0], s[2 * kc + 1][1]);
450            pa[3] = qi_pack2(s[2 * kc + 1][2], s[2 * kc + 1][3]);
451            for (int n = 0; n < QI_D / 8; n += 2) {
452                uint32_t b[4];
453                qi_ldsm_x4(b, sV + (kc * 16 + (lq & 1) * 8 + lr) * MF_LD + n * 8 + (lq >> 1) * 8, true);
454                qi_mma16816(o[n], pa, b);
455                qi_mma16816(o[n + 1], pa, b + 2);
456            }
457        }
458        __syncthreads();
459    }
460    const int row0 = q0 + r, row1 = q0 + r + 8;
461    for (int n = 0; n < QI_D / 8; ++n) {
462        if (row0 < nq) qi_put2(O, (size_t) row0 * H * QI_D + head * QI_D + n * 8 + c2, o[n][0] / l0, o[n][1] / l0);
463        if (row1 < nq) qi_put2(O, (size_t) row1 * H * QI_D + head * QI_D + n * 8 + c2, o[n][2] / l1, o[n][3] / l1);
464    }
465#else
466    __trap();
467#endif
468}
469#endif  // QI_HIP
470
471// ---- the steps ggml did for the native runner (ggml-cuda's formulas, float maths)
472__global__ void k_timestep(const float* __restrict__ t, float* __restrict__ emb, int dim, float max_period) {
473    const int i = blockIdx.y, j = blockIdx.x * blockDim.x + threadIdx.x, half_dim = dim / 2;
474    if (j >= half_dim) return;
475    const float freq = expf(-logf(max_period) * j / half_dim);
476    const float arg = t[i] * freq;
477    emb[(size_t) i * dim + j] = cosf(arg);
478    emb[(size_t) i * dim + j + half_dim] = sinf(arg);
479}
480
481__global__ void k_silu(float* __restrict__ x, int64_t n) {
482    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
483    if (i < n) x[i] = x[i] / (1.f + expf(-x[i]));
484}
485
486__global__ void k_gelu(float* __restrict__ x, int64_t n) {
487    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
488    if (i >= n) return;
489    const float GELU_COEF_A = 0.044715f, SQRT_2_OVER_PI = 0.79788456080286535587989211986876f;
490    const float v = x[i];
491    x[i] = 0.5f * v * (1.f + tanhf(SQRT_2_OVER_PI * v * (1.f + GELU_COEF_A * v * v)));
492}
493
494__global__ void __launch_bounds__(256) k_rms_w1(const float* __restrict__ x, const float* __restrict__ w,
495                                               float* __restrict__ out, int C, float eps) {
496    __shared__ float red[32];
497    const size_t row = blockIdx.x;
498    float s = 0.f;
499    for (int c = threadIdx.x; c < C; c += blockDim.x) s += x[row * C + c] * x[row * C + c];
500    const float inv = rsqrtf(qi_block_sum(s, red) / C + eps);
501    for (int c = threadIdx.x; c < C; c += blockDim.x) out[row * C + c] = x[row * C + c] * inv * (w[c] + 1.f);
502}
503
504inline cudaStream_t qs(void* s) { return static_cast<cudaStream_t>(s); }
505inline int launched() { return cudaGetLastError() == cudaSuccess ? 0 : 2; }
506inline unsigned blocks(int64_t n) { return (unsigned) ((n + 255) / 256); }
507
508}  // namespace
509
510namespace {
511template <typename OT>
512int res_ln_mod_t(void* stream, float* x, const float* h, const float* g, OT* out, const float* m, int T, int C, float eps) {
513    if (C > 32 * 256 || T <= 0) return T <= 0 ? 0 : 1;
514    if (h != nullptr && out != nullptr)
515        k_res_ln_mod<true, true, OT><<<T, 256, 0, qs(stream)>>>(x, h, g, out, m, C, eps);
516    else if (h != nullptr)
517        k_res_ln_mod<true, false, OT><<<T, 256, 0, qs(stream)>>>(x, h, g, out, m, C, eps);
518    else
519        k_res_ln_mod<false, true, OT><<<T, 256, 0, qs(stream)>>>(x, h, g, out, m, C, eps);
520    return launched();
521}
522}  // namespace
523
524int res_ln_mod(void* stream, float* x, const float* h, const float* g, float* out, const float* m, int T, int C, float eps) {
525    return res_ln_mod_t<float>(stream, x, h, g, out, m, T, C, eps);
526}
527
528int res_ln_mod_f16(void* stream, float* x, const float* h, const float* g, uint16_t* out, const float* m, int T, int C,
529                   float eps) {
530    return res_ln_mod_t<uint16_t>(stream, x, h, g, out, m, T, C, eps);
531}
532
533int qkv_post(void* stream, const float* q, const float* k, const float* v, int ld, const float* wq, const float* wk,
534             const float* pe, void* qo, int q_f16, int q_tstride, void* ko, void* vo, int kv_tstride, int kv_off, int T,
535             int H, float eps) {
536    if (H % 8 != 0 || ld % 4 != 0) return 1;
537    const dim3 gw(T, H / 8);
538    if (q_f16)
539        k_qkv_post_w<half><<<gw, 256, 0, qs(stream)>>>(q, k, v, ld, wq, wk, pe, static_cast<half*>(qo), q_tstride,
540                                                       static_cast<half*>(ko), static_cast<half*>(vo), kv_tstride, kv_off,
541                                                       eps);
542    else
543        k_qkv_post_w<float><<<gw, 256, 0, qs(stream)>>>(q, k, v, ld, wq, wk, pe, static_cast<float*>(qo), q_tstride,
544                                                        static_cast<half*>(ko), static_cast<half*>(vo), kv_tstride, kv_off,
545                                                        eps);
546    return launched();
547}
548
549int swiglu(void* stream, const float* gu, float* out, int T, int F) {
550    const int64_t n = (int64_t) T * F;
551    k_swiglu<float><<<blocks(n), 256, 0, qs(stream)>>>(gu, out, F, n);
552    return launched();
553}
554
555int swiglu_f16(void* stream, const float* gu, uint16_t* out, int T, int F) {
556    const int64_t n = (int64_t) T * F;
557    k_swiglu<uint16_t><<<blocks(n), 256, 0, qs(stream)>>>(gu, out, F, n);
558    return launched();
559}
560
561namespace {
562template <typename OT>
563int attn_exact_t(void* stream, const float* q, int q_tstride, const void* k, const void* v, int kv_tstride, OT* out, int H,
564                 int Lq, int Lk, int causal) {
565    const size_t smem = (size_t) Lk * sizeof(float);
566    if (smem > 48 * 1024) return 1;
567    k_attn_causal<OT><<<dim3(Lq, H), QI_D, smem, qs(stream)>>>(q, q_tstride, static_cast<const half*>(k),
568                                                               static_cast<const half*>(v), kv_tstride, out, H, Lk, causal,
569                                                               1.f / sqrtf((float) QI_D));
570    return launched();
571}
572}  // namespace
573
574int attn_exact(void* stream, const float* q, int q_tstride, const void* k, const void* v, int kv_tstride, float* out,
575               int H, int Lq, int Lk, int causal) {
576    return attn_exact_t<float>(stream, q, q_tstride, k, v, kv_tstride, out, H, Lq, Lk, causal);
577}
578
579int attn_exact_f16(void* stream, const float* q, int q_tstride, const void* k, const void* v, int kv_tstride,
580                   uint16_t* out, int H, int Lq, int Lk, int causal) {
581    return attn_exact_t<uint16_t>(stream, q, q_tstride, k, v, kv_tstride, out, H, Lq, Lk, causal);
582}
583
584int has_fast_attn(int device) {
585    cudaDeviceProp prop{};
586    if (cudaGetDeviceProperties(&prop, device) != cudaSuccess) return 0;
587#if defined(QI_HIP)
588    const char* arch = prop.gcnArchName;
589    for (const char* p : {"gfx1100", "gfx1101", "gfx1102", "gfx1103", "gfx1150", "gfx1151", "gfx1152"})
590        if (std::strncmp(arch, p, 7) == 0) return 1;
591    const char* g12 = std::getenv("STRATA_QI_GFX12_ATTN");
592    const bool rdna4 = std::strncmp(arch, "gfx1200", 7) == 0 || std::strncmp(arch, "gfx1201", 7) == 0;
593    // gfx1200 / gfx1201: on by default (R9700: 8 steps 27.75 s -> 6.93 s at 1024, pictures 54 dB from the exact-attention ones);
594    // STRATA_QI_GFX12_ATTN=0 turns it off
595    return rdna4 && !(g12 && g12[0] == '0') ? 1 : 0;
596#else
597    return prop.major >= 8 ? 1 : 0;
598#endif
599}
600
601namespace {
602template <typename OT>
603int attn_fast_t(void* stream, const void* q, int q_tstride, const void* k, const void* v, int kv_tstride, OT* out, int H,
604                int nq, int nkv) {
605    const float sl = (float) (1.0 / std::sqrt((double) QI_D) * 1.4426950408889634);
606#if defined(QI_HIP)
607    k_attn_wmma<OT><<<dim3((nq + FA_BQ - 1) / FA_BQ, H), FA_NW * 32, 0, qs(stream)>>>(
608        static_cast<const _Float16*>(q), q_tstride, static_cast<const _Float16*>(k), static_cast<const _Float16*>(v),
609        kv_tstride, out, H, nq, nkv, sl);
610#else
611    static bool attr = false;
612    if (!attr) {
613        if (cudaFuncSetAttribute(k_attn_mma<OT>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) MF_SMEM) != cudaSuccess)
614            return 2;
615        attr = true;
616    }
617    k_attn_mma<OT><<<dim3((nq + MF_BQ - 1) / MF_BQ, H), MF_NW * 32, MF_SMEM, qs(stream)>>>(
618        static_cast<const half*>(q), q_tstride, static_cast<const half*>(k), static_cast<const half*>(v), kv_tstride, out,
619        H, nq, nkv, sl);
620#endif
621    return launched();
622}
623}  // namespace
624
625int attn_fast(void* stream, const void* q, int q_tstride, const void* k, const void* v, int kv_tstride, float* out, int H,
626              int nq, int nkv) {
627    return attn_fast_t<float>(stream, q, q_tstride, k, v, kv_tstride, out, H, nq, nkv);
628}
629
630int attn_fast_f16(void* stream, const void* q, int q_tstride, const void* k, const void* v, int kv_tstride, uint16_t* out,
631                  int H, int nq, int nkv) {
632    return attn_fast_t<uint16_t>(stream, q, q_tstride, k, v, kv_tstride, out, H, nq, nkv);
633}
634
635int timestep_embedding(void* stream, const float* t, float* emb, int n, int dim, float max_period) {
636    if (dim % 2 != 0) return 1;
637    k_timestep<<<dim3((dim / 2 + 255) / 256, n), 256, 0, qs(stream)>>>(t, emb, dim, max_period);
638    return launched();
639}
640
641int silu(void* stream, float* x, int64_t n) {
642    k_silu<<<blocks(n), 256, 0, qs(stream)>>>(x, n);
643    return launched();
644}
645
646int gelu_tanh(void* stream, float* x, int64_t n) {
647    k_gelu<<<blocks(n), 256, 0, qs(stream)>>>(x, n);
648    return launched();
649}
650
651int rms_norm_w1(void* stream, const float* x, const float* w, float* out, int T, int C, float eps) {
652    if (T <= 0) return 0;
653    k_rms_w1<<<T, 256, 0, qs(stream)>>>(x, w, out, C, eps);
654    return launched();
655}
656
657}  // namespace strata::image::qi21