okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
c106e9629
main
1// qi21-native.cu - Strata's native kernels for the Qwen-Image-2.1 DiT inside stable-diffusion.cpp (CUDA and HIP). 2// 3// Copied into ggml/src/ggml-cuda/ by tools/image/sdcpp_native/apply.py, so ggml-cuda and ggml-hip compile it with 4// their own toolchain and vendor headers. The host side (qwen_image_2_1_native.hpp) runs the GEMMs as ggml graphs 5// on the same backend and calls these launchers on the backend's own stream, so everything stays stream-ordered. 6// 7// qi21_res_ln_mod x += h * tanh(g) (optional), then out = LayerNorm(x) * (1 + m) (no affine, eps) 8// qi21_qkv_post per head: RMSNorm(q|k) * w, 3-axis RoPE from sd.cpp's pe table, K/V to fp16, head-major 9// qi21_swiglu out = up * silu(gate) (gate = first half of the fused gate_up output) 10// qi21_attn_causal plain fp32 attention for the text prefix (causal; once per prompt) 11// qi21_attn_wmma gfx11 WMMA flash attention (fp16 in, fp32 softmax and accumulation) for the image tokens 12#include "common.cuh" 13#include "ggml-backend-impl.h" 14 15#include <cstdint> 16#include <cstdlib> 17 18namespace { 19 20constexpr int QI_D = 128; 21 22__device__ __forceinline__ float qi_block_sum(float v, float* red) { 23 // blockDim.x is a multiple of 32 and <= 1024 24 for (int off = 16; off > 0; off >>= 1) v += __shfl_xor_sync(0xffffffff, v, off, 32); 25 const int w = threadIdx.x >> 5, l = threadIdx.x & 31; 26 __syncthreads(); 27 if (l == 0) red[w] = v; 28 __syncthreads(); 29 const int nw = blockDim.x >> 5; 30 float s = threadIdx.x < nw ? red[threadIdx.x] : 0.f; 31 if (w == 0) { 32 for (int off = 16; off > 0; off >>= 1) s += __shfl_xor_sync(0xffffffff, s, off, 32); 33 if (l == 0) red[0] = s; 34 } 35 __syncthreads(); 36 return red[0]; 37} 38 39// x += h * tg (tg = tanh(gate), precomputed once per step), then out = LN(x) * (1 + m); float4, 256 threads, C % 1024 == 0 40template <bool RES, bool LN> 41__global__ void __launch_bounds__(256) k_res_ln_mod4(float* __restrict__ x, const float* __restrict__ h, 42 const float* __restrict__ tg, float* __restrict__ out, 43 const float* __restrict__ m, int C, float eps) { 44 __shared__ float red[32]; 45 const size_t row = blockIdx.x; 46 float4* xr = reinterpret_cast<float4*>(x + row * C); 47 const float4* hr = reinterpret_cast<const float4*>(h + row * C); 48 const float4* t4 = reinterpret_cast<const float4*>(tg); 49 float4 v[8]; 50 int n = 0; 51 float s = 0.f; 52 for (int c = threadIdx.x; c < C / 4; c += blockDim.x) { 53 float4 a = xr[c]; 54 if (RES) { 55 const float4 hh = hr[c], gg = t4[c]; 56 a.x += hh.x * gg.x; a.y += hh.y * gg.y; a.z += hh.z * gg.z; a.w += hh.w * gg.w; 57 xr[c] = a; 58 } 59 v[n++] = a; 60 s += (a.x + a.y) + (a.z + a.w); 61 } 62 if (!LN) return; 63 const float mean = qi_block_sum(s, red) / C; 64 float q = 0.f; 65 for (int i = 0; i < n; ++i) { 66 const float dx = v[i].x - mean, dy = v[i].y - mean, dz = v[i].z - mean, dw = v[i].w - mean; 67 q += (dx * dx + dy * dy) + (dz * dz + dw * dw); 68 } 69 const float inv = rsqrtf(qi_block_sum(q, red) / C + eps); 70 const float4* m4 = reinterpret_cast<const float4*>(m); 71 float4* o4 = reinterpret_cast<float4*>(out + row * C); 72 n = 0; 73 for (int c = threadIdx.x; c < C / 4; c += blockDim.x) { 74 const float4 mm = m4[c], a = v[n++]; 75 o4[c] = make_float4((a.x - mean) * inv * (1.f + mm.x), (a.y - mean) * inv * (1.f + mm.y), 76 (a.z - mean) * inv * (1.f + mm.z), (a.w - mean) * inv * (1.f + mm.w)); 77 } 78} 79 80__global__ void k_tanh(const float* __restrict__ in, float* __restrict__ out, int n) { 81 const int i = blockIdx.x * blockDim.x + threadIdx.x; 82 if (i < n) out[i] = tanhf(in[i]); 83} 84 85template <bool RES, bool LN> 86__global__ void __launch_bounds__(256) k_res_ln_mod(float* __restrict__ x, const float* __restrict__ h, 87 const float* __restrict__ g, float* __restrict__ out, 88 const float* __restrict__ m, int C, float eps) { 89 __shared__ float red[32]; 90 const size_t row = blockIdx.x; 91 float* xr = x + row * C; 92 float v[32]; 93 int n = 0; 94 float s = 0.f; 95 for (int c = threadIdx.x; c < C; c += blockDim.x) { 96 float a = xr[c]; 97 if (RES) { 98 a += h[row * C + c] * tanhf(g[c]); 99 xr[c] = a; 100 } 101 v[n++] = a; 102 s += a; 103 } 104 if (!LN) return; 105 const float mean = qi_block_sum(s, red) / C; 106 float q = 0.f; 107 for (int i = 0; i < n; ++i) q += (v[i] - mean) * (v[i] - mean); 108 const float inv = rsqrtf(qi_block_sum(q, red) / C + eps); 109 n = 0; 110 for (int c = threadIdx.x; c < C; c += blockDim.x) out[row * C + c] = (v[n++] - mean) * inv * (1.f + m[c]); 111} 112 113// grid (T, H), block 128: one head of one token. src rows have stride ld (floats). 114template <typename QT> 115__global__ void __launch_bounds__(QI_D) k_qkv_post(const float* __restrict__ q, const float* __restrict__ k, 116 const float* __restrict__ v, int ld, const float* __restrict__ wq, 117 const float* __restrict__ wk, const float* __restrict__ pe, 118 QT* __restrict__ qo, half* __restrict__ qlo, int q_tstride, 119 half* __restrict__ ko, 120 half* __restrict__ vo, int kv_tstride, int kv_off, float eps) { 121 __shared__ float red[32]; 122 __shared__ float buf[QI_D]; 123 const int t = blockIdx.x, hh = blockIdx.y, d = threadIdx.x; 124 const size_t src = (size_t) t * ld + hh * QI_D + d; 125 const float* p = pe + ((size_t) t * (QI_D / 2) + (d >> 1)) * 4; 126 for (int which = 0; which < 2; ++which) { 127 const float x = which == 0 ? q[src] : k[src]; 128 const float ss = qi_block_sum(x * x, red); 129 const float y = x * rsqrtf(ss / QI_D + eps) * (which == 0 ? wq[d] : wk[d]); 130 buf[d] = y; 131 __syncthreads(); 132 const float x0 = buf[d & ~1], x1 = buf[d | 1]; 133 const float r = (d & 1) ? p[2] * x0 + p[3] * x1 : p[0] * x0 + p[1] * x1; 134 __syncthreads(); 135 if (which == 0) { 136 const size_t qi = ((size_t) hh * q_tstride + t) * QI_D + d; 137 qo[qi] = (QT) r; 138 if (qlo != nullptr) qlo[qi] = __float2half(r - __half2float(__float2half(r))); 139 } else { 140 ko[((size_t) hh * kv_tstride + kv_off + t) * QI_D + d] = __float2half(r); 141 } 142 } 143 vo[((size_t) hh * kv_tstride + kv_off + t) * QI_D + d] = __float2half(v[src]); 144} 145 146// warp per head: grid (T, H/8), block 256; lane holds dims 4*lane..+3 (two RoPE pairs), no shared memory 147template <typename QT> 148__device__ __forceinline__ void qi_store4(QT* dst, float a, float b, float c, float d); 149template <> 150__device__ __forceinline__ void qi_store4<float>(float* dst, float a, float b, float c, float d) { 151 *reinterpret_cast<float4*>(dst) = make_float4(a, b, c, d); 152} 153template <> 154__device__ __forceinline__ void qi_store4<half>(half* dst, float a, float b, float c, float d) { 155 half2 lo = __floats2half2_rn(a, b), hi2 = __floats2half2_rn(c, d); 156 uint2 u; 157 u.x = *reinterpret_cast<uint32_t*>(&lo); 158 u.y = *reinterpret_cast<uint32_t*>(&hi2); 159 *reinterpret_cast<uint2*>(dst) = u; 160} 161 162template <typename QT> 163__global__ void __launch_bounds__(256) k_qkv_post_w(const float* __restrict__ q, const float* __restrict__ k, 164 const float* __restrict__ v, int ld, const float* __restrict__ wq, 165 const float* __restrict__ wk, const float* __restrict__ pe, 166 QT* __restrict__ qo, int q_tstride, half* __restrict__ ko, 167 half* __restrict__ vo, int kv_tstride, int kv_off, float eps) { 168 const int t = blockIdx.x, lane = threadIdx.x & 31, hh = blockIdx.y * 8 + (threadIdx.x >> 5); 169 const int d = lane * 4; 170 const size_t src = (size_t) t * ld + hh * QI_D + d; 171 const float4 p0 = *reinterpret_cast<const float4*>(pe + ((size_t) t * (QI_D / 2) + lane * 2) * 4); 172 const float4 p1 = *reinterpret_cast<const float4*>(pe + ((size_t) t * (QI_D / 2) + lane * 2 + 1) * 4); 173 for (int which = 0; which < 2; ++which) { 174 const float4 x = *reinterpret_cast<const float4*>((which == 0 ? q : k) + src); 175 float ss = x.x * x.x + x.y * x.y + x.z * x.z + x.w * x.w; 176 for (int off = 16; off > 0; off >>= 1) ss += __shfl_xor_sync(0xffffffff, ss, off, 32); 177 const float inv = rsqrtf(ss / QI_D + eps); 178 const float4 w = *reinterpret_cast<const float4*>((which == 0 ? wq : wk) + d); 179 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; 180 const float r0 = p0.x * y0 + p0.y * y1, r1 = p0.z * y0 + p0.w * y1; 181 const float r2 = p1.x * y2 + p1.y * y3, r3 = p1.z * y2 + p1.w * y3; 182 if (which == 0) 183 qi_store4<QT>(qo + ((size_t) hh * q_tstride + t) * QI_D + d, r0, r1, r2, r3); 184 else 185 qi_store4<half>(ko + ((size_t) hh * kv_tstride + kv_off + t) * QI_D + d, r0, r1, r2, r3); 186 } 187 const float4 vv = *reinterpret_cast<const float4*>(v + src); 188 qi_store4<half>(vo + ((size_t) hh * kv_tstride + kv_off + t) * QI_D + d, vv.x, vv.y, vv.z, vv.w); 189} 190 191__global__ void k_swiglu(const float* __restrict__ gu, float* __restrict__ out, int F, int64_t n) { 192 const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; 193 if (i >= n) return; 194 const int64_t t = i / F, c = i % F; 195 const float g = gu[t * 2 * F + c], u = gu[t * 2 * F + F + c]; 196 out[i] = u * (g / (1.f + expf(-g))); 197} 198 199// grid (Lq, H), block 128, dynamic smem Lk floats. q fp32 head-major [H][q_tstride][128], k/v fp16 [H][kv_tstride][128], 200// out token-major [Lq][H*128]. causal: query i sees keys 0..i. 201__global__ void __launch_bounds__(QI_D) k_attn_causal(const float* __restrict__ q, int q_tstride, 202 const half* __restrict__ k, const half* __restrict__ v, 203 int kv_tstride, float* __restrict__ out, int H, int Lk, 204 int causal, float scale) { 205 extern __shared__ float s[]; 206 __shared__ float red[32]; 207 __shared__ float qs[QI_D]; 208 const int i = blockIdx.x, hh = blockIdx.y, d = threadIdx.x; 209 qs[d] = q[((size_t) hh * q_tstride + i) * QI_D + d]; 210 __syncthreads(); 211 const int n = causal ? i + 1 : Lk; 212 float mx = -INFINITY; 213 for (int j = d; j < n; j += QI_D) { 214 const half* kr = k + ((size_t) hh * kv_tstride + j) * QI_D; 215 float dot = 0.f; 216 for (int c = 0; c < QI_D; ++c) dot += qs[c] * __half2float(kr[c]); 217 s[j] = dot * scale; 218 mx = fmaxf(mx, s[j]); 219 } 220 // block max 221 for (int off = 16; off > 0; off >>= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffff, mx, off, 32)); 222 __syncthreads(); 223 if ((d & 31) == 0) red[d >> 5] = mx; 224 __syncthreads(); 225 mx = red[0]; 226 for (int w = 1; w < QI_D / 32; ++w) mx = fmaxf(mx, red[w]); 227 __syncthreads(); 228 float sum = 0.f; 229 for (int j = d; j < n; j += QI_D) { 230 s[j] = expf(s[j] - mx); 231 sum += s[j]; 232 } 233 sum = qi_block_sum(sum, red); 234 float acc = 0.f; 235 for (int j = 0; j < n; ++j) acc += s[j] * __half2float(v[((size_t) hh * kv_tstride + j) * QI_D + d]); 236 out[(size_t) i * H * QI_D + hh * QI_D + d] = acc / sum; 237} 238 239#if defined(GGML_USE_HIP) 240// WMMA fragments: gfx11 (RDNA3) lanes hold 16 k-values of their row/column (lanes 16..31 duplicate 0..15) and C row 241// 2i + (lane >> 4); gfx12 (RDNA4) lanes hold 8 k-values at offset 8 * (lane >> 4) and C row 8 * (lane >> 4) + i. 242#if defined(RDNA4) 243#define QI_KL 8 244#define QI_KOFF(hi) ((hi) * 8) 245#define QI_ROW(i, hi) ((hi) * 8 + (i)) 246#define QI_WMMA __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12 247#else 248#define QI_KL 16 249#define QI_KOFF(hi) 0 250#define QI_ROW(i, hi) (2 * (i) + (hi)) 251#define QI_WMMA __builtin_amdgcn_wmma_f32_16x16x16_f16_w32 252#endif 253typedef _Float16 qi_h16 __attribute__((ext_vector_type(QI_KL))); 254typedef float qi_f8 __attribute__((ext_vector_type(8))); 255constexpr 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; 256 257// a lane's fragment of the 16 k-values starting at p (this lane's half on gfx12) 258__device__ __forceinline__ qi_h16 qi_ld16(const _Float16* p, int hi) { 259#if QI_KL == 8 260 return __builtin_bit_cast(qi_h16, *reinterpret_cast<const uint4*>(p + QI_KOFF(hi))); 261#else 262 (void) hi; 263 const uint4 a = *reinterpret_cast<const uint4*>(p), b = *reinterpret_cast<const uint4*>(p + 8); 264 const uint32_t w[8] = {a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w}; 265 return __builtin_bit_cast(qi_h16, w); 266#endif 267} 268 269// gfx11 WMMA flash attention: q fp16 head-major [H][q_tstride][128], k/v fp16 head-major [H][kv_tstride][128] 270// (no mask), out fp32 token-major [nq][H*128]. 8 waves x 16 query rows; 64-key tiles through LDS (V transposed). 271template <bool LO> 272__global__ void __launch_bounds__(FA_NW * 32) k_attn_wmma(const _Float16* __restrict__ Q, const _Float16* __restrict__ Qlo, 273 int q_tstride, 274 const _Float16* __restrict__ K, const _Float16* __restrict__ V, 275 int kv_tstride, float* __restrict__ O, int H, int nq, int nkv, 276 float scale_log2) { 277#if defined(RDNA3) || defined(RDNA4) 278 __shared__ __align__(16) _Float16 sK[FA_BKV][FA_KLD]; 279 __shared__ __align__(16) _Float16 sVt[QI_D][FA_VLD]; 280 __shared__ __align__(16) _Float16 sP[FA_NW][16][FA_PLD]; 281 const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, l16 = lane & 15, hi = lane >> 4; 282 const int head = blockIdx.y, q0 = blockIdx.x * FA_BQ + wave * 16; 283 const _Float16* Qh = Q + (size_t) head * q_tstride * QI_D; 284 const _Float16* Kh = K + (size_t) head * kv_tstride * QI_D; 285 const _Float16* Vh = V + (size_t) head * kv_tstride * QI_D; 286 qi_h16 qa[QI_D / 16], ql[LO ? QI_D / 16 : 1]; 287 { 288 const int qr = min(q0 + l16, nq - 1); 289 for (int c = 0; c < QI_D / 16; ++c) qa[c] = qi_ld16(Qh + (size_t) qr * QI_D + c * 16, hi); 290 if (LO) { 291 const _Float16* Ql = Qlo + (size_t) head * q_tstride * QI_D; 292 for (int c = 0; c < QI_D / 16; ++c) ql[c] = qi_ld16(Ql + (size_t) qr * QI_D + c * 16, hi); 293 } 294 } 295 qi_f8 o[QI_D / 16]; 296 for (int c = 0; c < QI_D / 16; ++c) o[c] = qi_f8{}; 297 float m[8], l[8]; 298 for (int i = 0; i < 8; ++i) { m[i] = -INFINITY; l[i] = 0.f; } 299 for (int k0 = 0; k0 < nkv; k0 += FA_BKV) { 300 __syncthreads(); 301 for (int e = tid * 8; e < FA_BKV * QI_D; e += FA_NW * 32 * 8) { 302 const int r = e / QI_D, c = e % QI_D, key = k0 + r; 303 uint4 kv = make_uint4(0, 0, 0, 0); 304 if (key < nkv) kv = *reinterpret_cast<const uint4*>(Kh + (size_t) key * QI_D + c); 305 *reinterpret_cast<uint4*>(&sK[r][c]) = kv; 306 } 307 for (int e = tid; e < (FA_BKV / 4) * (QI_D / 8); e += FA_NW * 32) { 308 const int r4 = (e / (QI_D / 8)) * 4, c = (e % (QI_D / 8)) * 8; 309 _Float16 vv[4][8]; 310 for (int j = 0; j < 4; ++j) { 311 uint4 x = make_uint4(0, 0, 0, 0); 312 if (k0 + r4 + j < nkv) x = *reinterpret_cast<const uint4*>(Vh + (size_t) (k0 + r4 + j) * QI_D + c); 313 *reinterpret_cast<uint4*>(vv[j]) = x; 314 } 315 for (int dd = 0; dd < 8; ++dd) { 316 _Float16 w4[4] = {vv[0][dd], vv[1][dd], vv[2][dd], vv[3][dd]}; 317 *reinterpret_cast<uint2*>(&sVt[c + dd][r4]) = *reinterpret_cast<uint2*>(w4); 318 } 319 } 320 __syncthreads(); 321 qi_f8 s[FA_BKV / 16]; 322 for (int t = 0; t < FA_BKV / 16; ++t) { 323 s[t] = qi_f8{}; 324 for (int c = 0; c < QI_D / 16; ++c) { 325 const qi_h16 kb = qi_ld16(&sK[t * 16 + l16][c * 16], hi); 326 s[t] = QI_WMMA(qa[c], kb, s[t]); 327 if (LO) s[t] = QI_WMMA(ql[LO ? c : 0], kb, s[t]); 328 } 329 } 330 float alpha[8]; 331 for (int i = 0; i < 8; ++i) { 332 float mx = -INFINITY; 333 for (int t = 0; t < FA_BKV / 16; ++t) { 334 const float val = k0 + t * 16 + l16 < nkv ? s[t][i] * scale_log2 : -INFINITY; 335 s[t][i] = val; 336 mx = fmaxf(mx, val); 337 } 338 for (int off = 1; off < 16; off <<= 1) mx = fmaxf(mx, __shfl_xor(mx, off, 32)); 339 const float mnew = fmaxf(m[i], mx); 340 alpha[i] = exp2f(m[i] - mnew); 341 float sum = 0.f; 342 for (int t = 0; t < FA_BKV / 16; ++t) { 343 const float pv = exp2f(s[t][i] - mnew); 344 s[t][i] = pv; 345 sum += pv; 346 } 347 for (int off = 1; off < 16; off <<= 1) sum += __shfl_xor(sum, off, 32); 348 l[i] = l[i] * alpha[i] + sum; 349 m[i] = mnew; 350 } 351 for (int c = 0; c < QI_D / 16; ++c) 352 for (int i = 0; i < 8; ++i) o[c][i] *= alpha[i]; 353 for (int t = 0; t < FA_BKV / 16; ++t) 354 for (int i = 0; i < 8; ++i) sP[wave][QI_ROW(i, hi)][t * 16 + l16] = (_Float16) s[t][i]; 355 __builtin_amdgcn_s_waitcnt(0); 356 __builtin_amdgcn_wave_barrier(); 357 for (int kc = 0; kc < FA_BKV / 16; ++kc) { 358 const qi_h16 pa = qi_ld16(&sP[wave][l16][kc * 16], hi); 359 for (int c = 0; c < QI_D / 16; ++c) 360 o[c] = QI_WMMA(pa, qi_ld16(&sVt[c * 16 + l16][kc * 16], hi), o[c]); 361 } 362 } 363 for (int c = 0; c < QI_D / 16; ++c) 364 for (int i = 0; i < 8; ++i) { 365 const int row = q0 + QI_ROW(i, hi); 366 if (row < nq) O[(size_t) row * H * QI_D + head * QI_D + c * 16 + l16] = o[c][i] / l[i]; 367 } 368#else 369 __builtin_trap(); 370#endif 371} 372#endif // GGML_USE_HIP 373 374#if !defined(GGML_USE_HIP) 375// NVIDIA (sm_80+): mma.sync m16n8k16 f16 -> f32 flash attention. 8 warps x 16 queries per block, 64-key tiles of K 376// and V (row-major) double-buffered with cp.async, ldmatrix (.trans for V) fragments, fp32 online softmax, P in fp16. 377// q fp16 head-major [H][q_tstride][128], k/v fp16 head-major [H][kv_tstride][128], out fp32 token-major [nq][H*128]. 378constexpr int MF_NW = 8, MF_BQ = MF_NW * 16, MF_BKV = 64, MF_LD = QI_D + 8; 379constexpr size_t MF_SMEM = (size_t) 4 * MF_BKV * MF_LD * sizeof(half); 380 381__device__ __forceinline__ void qi_mma16816(float* c, const uint32_t* a, const uint32_t* b) { 382#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 383 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" 384 : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) 385 : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b[0]), "r"(b[1])); 386#else 387 (void) c; (void) a; (void) b; 388 __trap(); 389#endif 390} 391__device__ __forceinline__ uint32_t qi_pack2(float x, float y) { 392 half2 h = __floats2half2_rn(x, y); 393 return *reinterpret_cast<uint32_t*>(&h); 394} 395__device__ __forceinline__ void qi_ldsm_x4(uint32_t* r, const half* p, bool trans) { 396#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 397 const uint32_t a = (uint32_t) __cvta_generic_to_shared(p); 398 if (trans) 399 asm volatile("ldmatrix.sync.aligned.m8n8.x4.trans.shared.b16 {%0,%1,%2,%3}, [%4];\n" 400 : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]) : "r"(a)); 401 else 402 asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];\n" 403 : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]) : "r"(a)); 404#else 405 (void) r; (void) p; (void) trans; 406#endif 407} 408__device__ __forceinline__ void qi_cp16(half* dst, const half* src, bool ok) { 409#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 410 const uint32_t a = (uint32_t) __cvta_generic_to_shared(dst); 411 const int n = ok ? 16 : 0; 412 asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;\n" :: "r"(a), "l"(src), "r"(n)); 413#else 414 (void) dst; (void) src; (void) ok; 415#endif 416} 417 418__global__ void __launch_bounds__(MF_NW * 32) k_attn_mma(const half* __restrict__ Q, int q_tstride, 419 const half* __restrict__ K, const half* __restrict__ V, 420 int kv_tstride, float* __restrict__ O, int H, int nq, int nkv, 421 float scale_log2) { 422#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 423 extern __shared__ __align__(16) half qi_smem[]; 424 const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; 425 const int r = lane >> 2, c2 = (lane & 3) * 2, lr = lane & 7, lq = lane >> 3; 426 const int head = blockIdx.y, q0 = blockIdx.x * MF_BQ + warp * 16; 427 const half* Qh = Q + (size_t) head * q_tstride * QI_D; 428 const half* Kh = K + (size_t) head * kv_tstride * QI_D; 429 const half* Vh = V + (size_t) head * kv_tstride * QI_D; 430 auto tile = [&](int st, int kv) { return qi_smem + ((st * 2 + kv) * MF_BKV) * MF_LD; }; 431 auto load = [&](int st, int k0) { 432 for (int e = tid * 8; e < MF_BKV * QI_D; e += MF_NW * 32 * 8) { 433 const int rr = e / QI_D, cc = e % QI_D, key = k0 + rr; 434 const bool ok = key < nkv; 435 const size_t off = (size_t) (ok ? key : 0) * QI_D + cc; 436 qi_cp16(tile(st, 0) + rr * MF_LD + cc, Kh + off, ok); 437 qi_cp16(tile(st, 1) + rr * MF_LD + cc, Vh + off, ok); 438 } 439 asm volatile("cp.async.commit_group;\n"); 440 }; 441 uint32_t qa[QI_D / 16][4]; 442 { 443 const int r0 = min(q0 + r, nq - 1), r1 = min(q0 + r + 8, nq - 1); 444 for (int kc = 0; kc < QI_D / 16; ++kc) { 445 qa[kc][0] = *reinterpret_cast<const uint32_t*>(Qh + (size_t) r0 * QI_D + kc * 16 + c2); 446 qa[kc][1] = *reinterpret_cast<const uint32_t*>(Qh + (size_t) r1 * QI_D + kc * 16 + c2); 447 qa[kc][2] = *reinterpret_cast<const uint32_t*>(Qh + (size_t) r0 * QI_D + kc * 16 + c2 + 8); 448 qa[kc][3] = *reinterpret_cast<const uint32_t*>(Qh + (size_t) r1 * QI_D + kc * 16 + c2 + 8); 449 } 450 } 451 float o[QI_D / 8][4]; 452 for (int n = 0; n < QI_D / 8; ++n) o[n][0] = o[n][1] = o[n][2] = o[n][3] = 0.f; 453 float m0 = -INFINITY, m1 = -INFINITY, l0 = 0.f, l1 = 0.f; 454 const int ntiles = (nkv + MF_BKV - 1) / MF_BKV; 455 load(0, 0); 456 for (int it = 0; it < ntiles; ++it) { 457 const int st = it & 1, k0 = it * MF_BKV; 458 if (it + 1 < ntiles) { 459 load(st ^ 1, k0 + MF_BKV); 460 asm volatile("cp.async.wait_group 1;\n"); 461 } else { 462 asm volatile("cp.async.wait_group 0;\n"); 463 } 464 __syncthreads(); 465 const half* sK = tile(st, 0); 466 const half* sV = tile(st, 1); 467 float s[MF_BKV / 8][4]; 468 for (int t = 0; t < MF_BKV / 8; ++t) { 469 s[t][0] = s[t][1] = s[t][2] = s[t][3] = 0.f; 470 for (int kc = 0; kc < QI_D / 16; kc += 2) { 471 uint32_t b[4]; 472 qi_ldsm_x4(b, sK + (t * 8 + lr) * MF_LD + kc * 16 + lq * 8, false); 473 qi_mma16816(s[t], qa[kc], b); 474 qi_mma16816(s[t], qa[kc + 1], b + 2); 475 } 476 } 477 float mx0 = -INFINITY, mx1 = -INFINITY; 478 for (int t = 0; t < MF_BKV / 8; ++t) 479 for (int j = 0; j < 2; ++j) { 480 const bool ok = k0 + t * 8 + c2 + j < nkv; 481 s[t][j] = ok ? s[t][j] * scale_log2 : -INFINITY; 482 s[t][2 + j] = ok ? s[t][2 + j] * scale_log2 : -INFINITY; 483 mx0 = fmaxf(mx0, s[t][j]); 484 mx1 = fmaxf(mx1, s[t][2 + j]); 485 } 486 for (int off = 1; off < 4; off <<= 1) { 487 mx0 = fmaxf(mx0, __shfl_xor_sync(0xffffffff, mx0, off)); 488 mx1 = fmaxf(mx1, __shfl_xor_sync(0xffffffff, mx1, off)); 489 } 490 const float mn0 = fmaxf(m0, mx0), mn1 = fmaxf(m1, mx1); 491 const float a0 = exp2f(m0 - mn0), a1 = exp2f(m1 - mn1); 492 float sum0 = 0.f, sum1 = 0.f; 493 for (int t = 0; t < MF_BKV / 8; ++t) 494 for (int j = 0; j < 2; ++j) { 495 s[t][j] = exp2f(s[t][j] - mn0); 496 s[t][2 + j] = exp2f(s[t][2 + j] - mn1); 497 sum0 += s[t][j]; 498 sum1 += s[t][2 + j]; 499 } 500 for (int off = 1; off < 4; off <<= 1) { 501 sum0 += __shfl_xor_sync(0xffffffff, sum0, off); 502 sum1 += __shfl_xor_sync(0xffffffff, sum1, off); 503 } 504 l0 = l0 * a0 + sum0; 505 l1 = l1 * a1 + sum1; 506 m0 = mn0; 507 m1 = mn1; 508 for (int n = 0; n < QI_D / 8; ++n) { 509 o[n][0] *= a0; o[n][1] *= a0; o[n][2] *= a1; o[n][3] *= a1; 510 } 511 for (int kc = 0; kc < MF_BKV / 16; ++kc) { 512 uint32_t pa[4]; 513 pa[0] = qi_pack2(s[2 * kc][0], s[2 * kc][1]); 514 pa[1] = qi_pack2(s[2 * kc][2], s[2 * kc][3]); 515 pa[2] = qi_pack2(s[2 * kc + 1][0], s[2 * kc + 1][1]); 516 pa[3] = qi_pack2(s[2 * kc + 1][2], s[2 * kc + 1][3]); 517 for (int n = 0; n < QI_D / 8; n += 2) { 518 uint32_t b[4]; 519 qi_ldsm_x4(b, sV + (kc * 16 + (lq & 1) * 8 + lr) * MF_LD + n * 8 + (lq >> 1) * 8, true); 520 qi_mma16816(o[n], pa, b); 521 qi_mma16816(o[n + 1], pa, b + 2); 522 } 523 } 524 __syncthreads(); 525 } 526 const int row0 = q0 + r, row1 = q0 + r + 8; 527 for (int n = 0; n < QI_D / 8; ++n) { 528 if (row0 < nq) 529 *reinterpret_cast<float2*>(O + (size_t) row0 * H * QI_D + head * QI_D + n * 8 + c2) = 530 make_float2(o[n][0] / l0, o[n][1] / l0); 531 if (row1 < nq) 532 *reinterpret_cast<float2*>(O + (size_t) row1 * H * QI_D + head * QI_D + n * 8 + c2) = 533 make_float2(o[n][2] / l1, o[n][3] / l1); 534 } 535#else 536 __trap(); 537#endif 538} 539#endif // !GGML_USE_HIP 540 541inline cudaStream_t qi_s(void* s) { return static_cast<cudaStream_t>(s); } 542 543} // namespace 544 545extern "C" { 546 547void* qi21_stream(ggml_backend_t backend) { 548 return static_cast<ggml_backend_cuda_context*>(backend->context)->stream(); 549} 550 551// 1 when this backend's GPU runs qi21_attn_wmma (an RDNA3 / gfx11 or RDNA4 / gfx12 card in a HIP build; 552// STRATA_QI_GFX12_ATTN=0 keeps ggml's attention on gfx12, where this kernel is not measured yet) 553int qi21_has_wmma_attn(ggml_backend_t backend) { 554#if defined(GGML_USE_HIP) 555 const int dev = static_cast<ggml_backend_cuda_context*>(backend->context)->device; 556 const int cc = ggml_cuda_info().devices[dev].cc; 557 if (GGML_CUDA_CC_IS_RDNA3(cc)) return 1; 558 const char* g12 = getenv("STRATA_QI_GFX12_ATTN"); 559 return GGML_CUDA_CC_IS_RDNA4(cc) && g12 != nullptr && g12[0] == '1' ? 1 : 0; 560#else 561 // NVIDIA Ampere or newer: the mma.sync kernel (STRATA_QI_GGML_ATTN=1 in the runner keeps ggml's) 562 const int dev = static_cast<ggml_backend_cuda_context*>(backend->context)->device; 563 return GGML_CUDA_CC_IS_NVIDIA(ggml_cuda_info().devices[dev].cc) && 564 ggml_cuda_info().devices[dev].cc >= GGML_CUDA_CC_AMPERE ? 1 : 0; 565#endif 566} 567 568int qi21_tanh(void* stream, const float* in, float* out, int n) { 569 k_tanh<<<(n + 255) / 256, 256, 0, qi_s(stream)>>>(in, out, n); 570 return cudaGetLastError() == cudaSuccess ? 0 : 2; 571} 572 573// g: the gate row as tanh(gate) already when tg != 0 (the float4 kernel), the raw gate otherwise 574int qi21_res_ln_mod2(void* stream, float* x, const float* h, const float* tg, float* out, const float* m, int T, int C, 575 float eps) { 576 if (C % 1024 != 0 || C > 8 * 1024) return 1; 577 if (h != nullptr && out != nullptr) 578 k_res_ln_mod4<true, true><<<T, 256, 0, qi_s(stream)>>>(x, h, tg, out, m, C, eps); 579 else if (h != nullptr) 580 k_res_ln_mod4<true, false><<<T, 256, 0, qi_s(stream)>>>(x, h, tg, out, m, C, eps); 581 else 582 k_res_ln_mod4<false, true><<<T, 256, 0, qi_s(stream)>>>(x, h, tg, out, m, C, eps); 583 return cudaGetLastError() == cudaSuccess ? 0 : 2; 584} 585 586int qi21_res_ln_mod(void* stream, float* x, const float* h, const float* g, float* out, const float* m, int T, int C, 587 float eps) { 588 if (C > 32 * 256) return 1; 589 if (h != nullptr && out != nullptr) 590 k_res_ln_mod<true, true><<<T, 256, 0, qi_s(stream)>>>(x, h, g, out, m, C, eps); 591 else if (h != nullptr) 592 k_res_ln_mod<true, false><<<T, 256, 0, qi_s(stream)>>>(x, h, g, out, m, C, eps); 593 else 594 k_res_ln_mod<false, true><<<T, 256, 0, qi_s(stream)>>>(x, h, g, out, m, C, eps); 595 return cudaGetLastError() == cudaSuccess ? 0 : 2; 596} 597 598int qi21_qkv_post(void* stream, const float* q, const float* k, const float* v, int ld, const float* wq, const float* wk, 599 const float* pe, void* qo, void* qlo, int q_f16, int q_tstride, void* ko, void* vo, int kv_tstride, 600 int kv_off, int T, int H, float eps) { 601 if (qlo == nullptr && H % 8 == 0 && ld % 4 == 0 && getenv("STRATA_QI_OLD_QKV") == nullptr) { 602 const dim3 gw(T, H / 8); 603 if (q_f16) 604 k_qkv_post_w<half><<<gw, 256, 0, qi_s(stream)>>>(q, k, v, ld, wq, wk, pe, static_cast<half*>(qo), q_tstride, 605 static_cast<half*>(ko), static_cast<half*>(vo), kv_tstride, 606 kv_off, eps); 607 else 608 k_qkv_post_w<float><<<gw, 256, 0, qi_s(stream)>>>(q, k, v, ld, wq, wk, pe, static_cast<float*>(qo), 609 q_tstride, static_cast<half*>(ko), static_cast<half*>(vo), 610 kv_tstride, kv_off, eps); 611 return cudaGetLastError() == cudaSuccess ? 0 : 2; 612 } 613 const dim3 grid(T, H); 614 if (q_f16) 615 k_qkv_post<half><<<grid, QI_D, 0, qi_s(stream)>>>(q, k, v, ld, wq, wk, pe, static_cast<half*>(qo), 616 static_cast<half*>(qlo), q_tstride, 617 static_cast<half*>(ko), static_cast<half*>(vo), kv_tstride, 618 kv_off, eps); 619 else 620 k_qkv_post<float><<<grid, QI_D, 0, qi_s(stream)>>>(q, k, v, ld, wq, wk, pe, static_cast<float*>(qo), nullptr, 621 q_tstride, 622 static_cast<half*>(ko), static_cast<half*>(vo), kv_tstride, 623 kv_off, eps); 624 return cudaGetLastError() == cudaSuccess ? 0 : 2; 625} 626 627int qi21_swiglu(void* stream, const float* gu, float* out, int T, int F) { 628 const int64_t n = (int64_t) T * F; 629 k_swiglu<<<(unsigned) ((n + 255) / 256), 256, 0, qi_s(stream)>>>(gu, out, F, n); 630 return cudaGetLastError() == cudaSuccess ? 0 : 2; 631} 632 633int qi21_attn_causal(void* stream, const float* q, int q_tstride, const void* k, const void* v, int kv_tstride, 634 float* out, int H, int Lq, int Lk, int causal) { 635 const size_t smem = (size_t) Lk * sizeof(float); 636 if (smem > 48 * 1024) return 1; 637 k_attn_causal<<<dim3(Lq, H), QI_D, smem, qi_s(stream)>>>(q, q_tstride, static_cast<const half*>(k), 638 static_cast<const half*>(v), kv_tstride, out, H, Lk, 639 causal, 1.f / sqrtf((float) QI_D)); 640 return cudaGetLastError() == cudaSuccess ? 0 : 2; 641} 642 643int qi21_attn_wmma(void* stream, const void* q, const void* qlo, int q_tstride, const void* k, const void* v, 644 int kv_tstride, float* out, int H, int nq, int nkv) { 645#if defined(GGML_USE_HIP) 646 const dim3 grid((nq + FA_BQ - 1) / FA_BQ, H); 647 const float sl = (float) (1.0 / sqrt((double) QI_D) * 1.4426950408889634); 648 if (qlo != nullptr) 649 k_attn_wmma<true><<<grid, FA_NW * 32, 0, qi_s(stream)>>>(static_cast<const _Float16*>(q), 650 static_cast<const _Float16*>(qlo), q_tstride, 651 static_cast<const _Float16*>(k), 652 static_cast<const _Float16*>(v), kv_tstride, out, H, 653 nq, nkv, sl); 654 else 655 k_attn_wmma<false><<<grid, FA_NW * 32, 0, qi_s(stream)>>>(static_cast<const _Float16*>(q), nullptr, q_tstride, 656 static_cast<const _Float16*>(k), 657 static_cast<const _Float16*>(v), kv_tstride, out, H, 658 nq, nkv, sl); 659 return cudaGetLastError() == cudaSuccess ? 0 : 2; 660#else 661 if (qlo != nullptr) return 1; // no hi/lo split on this path 662 static bool attr = false; 663 if (!attr) { 664 if (cudaFuncSetAttribute(k_attn_mma, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) MF_SMEM) != cudaSuccess) 665 return 2; 666 attr = true; 667 } 668 k_attn_mma<<<dim3((nq + MF_BQ - 1) / MF_BQ, H), MF_NW * 32, MF_SMEM, qi_s(stream)>>>( 669 static_cast<const half*>(q), q_tstride, static_cast<const half*>(k), static_cast<const half*>(v), kv_tstride, out, 670 H, nq, nkv, (float) (1.0 / sqrt((double) QI_D) * 1.4426950408889634)); 671 return cudaGetLastError() == cudaSuccess ? 0 : 2; 672#endif 673} 674 675int qi21_memcpy_d2d(void* stream, void* dst, const void* src, size_t n) { 676 return cudaMemcpyAsync(dst, src, n, cudaMemcpyDeviceToDevice, qi_s(stream)) == cudaSuccess ? 0 : 2; 677} 678 679} // extern "C"