okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
8f69f5317
main
1// tools/vision/own/vit_metal.metal - the Qwen vision tower's kernels on Metal (own-stack phase 3). The counterparts of vit_gpu.cu's kernels, one for one, 2// with the same arithmetic: float32 activations, 16-bit GEMM inputs of the weight's own type (F16 or BF16), q / k / v and the attention scores in F16, 3// float32 accumulation. Embedded into strata-vision at build time and compiled when the reader starts (vit_metal.mm); the tensor-op products are in 4// vit_metal_mpp.metal (Metal 4 only). 5// 6// Every kernel takes its buffers at [[buffer(0..)]] and its sizes in a small constant struct at [[buffer(15)]]. 7#include <metal_stdlib> 8using namespace metal; 9 10// the 16-bit kinds (vit_metal.mm's Kind): 0 float32, 1 F16, 2 BF16 11constant int K_F32 = 0; 12constant int K_F16 = 1; 13 14inline ushort f_to_bf16(float f) { // round to nearest even; NaN stays NaN 15 uint u = as_type<uint>(f); 16 if ((u & 0x7fffffffu) > 0x7f800000u) return ushort((u >> 16) | 0x40u); 17 u += 0x7fffu + ((u >> 16) & 1u); 18 return ushort(u >> 16); 19} 20inline float bf16_to_f(ushort b) { return as_type<float>(uint(b) << 16); } 21inline ushort f_to_f16bits(float f) { return as_type<ushort>(half(f)); } // float -> half rounds to nearest even 22inline float f16bits_to_f(ushort h) { return float(as_type<half>(h)); } 23 24inline void store_kind(device void* out, ulong i, float v, int kind) { 25 if (kind == K_F32) ((device float*) out)[i] = v; 26 else if (kind == K_F16) ((device ushort*) out)[i] = f_to_f16bits(v); 27 else ((device ushort*) out)[i] = f_to_bf16(v); 28} 29 30// threadgroup-wide sum / max of one float per thread (threads a multiple of 32, at most 1024) 31inline float tg_sum(float v, threadgroup float* red, ushort tid, ushort nt) { 32 v = simd_sum(v); 33 threadgroup_barrier(mem_flags::mem_threadgroup); 34 if ((tid & 31) == 0) red[tid >> 5] = v; 35 threadgroup_barrier(mem_flags::mem_threadgroup); 36 const ushort nw = (nt + 31) / 32; 37 v = (tid & 31) < nw ? red[tid & 31] : 0.0f; 38 return simd_sum(v); 39} 40inline float tg_max(float v, threadgroup float* red, ushort tid, ushort nt) { 41 v = simd_max(v); 42 threadgroup_barrier(mem_flags::mem_threadgroup); 43 if ((tid & 31) == 0) red[tid >> 5] = v; 44 threadgroup_barrier(mem_flags::mem_threadgroup); 45 const ushort nw = (nt + 31) / 32; 46 v = (tid & 31) < nw ? red[tid & 31] : -FLT_MAX; 47 return simd_max(v); 48} 49 50struct PatchPostArgs { int G, pw, ph, nbx, D; }; 51// x[t] += patch bias + the position table resized (bilinear, align corners: ggml's maths, in float) to the token's grid position. One group a token. 52kernel void vk_patch_post(device float* x [[buffer(0)]], device const float* bias [[buffer(1)]], device const float* pos [[buffer(2)]], 53 constant PatchPostArgs& a [[buffer(15)]], uint t [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], 54 ushort nt [[threads_per_threadgroup]]) { 55 const int G = a.G, pw = a.pw, ph = a.ph, D = a.D; 56 const int b = int(t) / 4, r = int(t) % 4; 57 const int ty = 2 * (b / a.nbx) + r / 2, tx = 2 * (b % a.nbx) + r % 2; 58 float sfx = (float) pw / G, sfy = (float) ph / G; 59 if (pw > 1 && G > 1) sfx = (float) (pw - 1) / (G - 1); 60 if (ph > 1 && G > 1) sfy = (float) (ph - 1) / (G - 1); 61 const float fy = (float) ty / sfy, fx = (float) tx / sfx; 62 int y0 = (int) floor(fy), x0 = (int) floor(fx), y1 = y0 + 1, x1 = x0 + 1; 63 y0 = max(0, min(y0, G - 1)); y1 = max(0, min(y1, G - 1)); 64 x0 = max(0, min(x0, G - 1)); x1 = max(0, min(x1, G - 1)); 65 const float dy = fmax(0.0f, fmin(fy - (float) y0, 1.0f)), dx = fmax(0.0f, fmin(fx - (float) x0, 1.0f)); 66 device const float* pa = pos + ((ulong) y0 * G + x0) * D; 67 device const float* pb = pos + ((ulong) y0 * G + x1) * D; 68 device const float* pc = pos + ((ulong) y1 * G + x0) * D; 69 device const float* pd = pos + ((ulong) y1 * G + x1) * D; 70 device float* xr = x + (ulong) t * D; 71 for (int i = tid; i < D; i += nt) 72 xr[i] += bias[i] + (pa[i] * (1 - dx) * (1 - dy) + pb[i] * dx * (1 - dy) + pc[i] * (1 - dx) * dy + pd[i] * dx * dy); 73} 74 75struct NormArgs { int D, kind; float eps; }; 76// out = LayerNorm(x) * w + b, into `kind`. One group a row. 77kernel void vk_layernorm(device const float* x [[buffer(0)]], device const float* w [[buffer(1)]], device const float* b [[buffer(2)]], 78 device void* out [[buffer(3)]], constant NormArgs& a [[buffer(15)]], uint row [[threadgroup_position_in_grid]], 79 ushort tid [[thread_index_in_threadgroup]], ushort nt [[threads_per_threadgroup]]) { 80 threadgroup float red[32]; 81 const int D = a.D; 82 device const float* xr = x + (ulong) row * D; 83 float s = 0.0f; 84 for (int i = tid; i < D; i += nt) s += xr[i]; 85 const float mean = tg_sum(s, red, tid, nt) / (float) D; 86 float v = 0.0f; 87 for (int i = tid; i < D; i += nt) { const float d = xr[i] - mean; v += d * d; } 88 const float scale = rsqrt(tg_sum(v, red, tid, nt) / (float) D + a.eps); 89 for (int i = tid; i < D; i += nt) store_kind(out, (ulong) row * D + i, (xr[i] - mean) * scale * w[i] + b[i], a.kind); 90} 91 92struct RopeArgs { int row0, nbx, heads, hd; float theta_scale, qscale; }; 93// y [rows][3D] (the fused qkv product of the tokens row0 ..) + bias -> q (scaled), k (rotary applied), v, each [N][D] in F16. Pair j of a head is 94// (j, j + hd/2); j < hd/4 turns with the token's row, the others with its column. One group a row. 95kernel void vk_qkv_rope(device const float* y [[buffer(0)]], device const float* bias [[buffer(1)]], device ushort* q [[buffer(2)]], 96 device ushort* k [[buffer(3)]], device ushort* v [[buffer(4)]], constant RopeArgs& a [[buffer(15)]], 97 uint gr [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], ushort nt [[threads_per_threadgroup]]) { 98 const int t = a.row0 + int(gr), heads = a.heads, hd = a.hd, D = heads * hd, half_ = hd / 2, quarter = hd / 4; 99 const int b = t / 4, r = t % 4; 100 const int ty = 2 * (b / a.nbx) + r / 2, tx = 2 * (b % a.nbx) + r % 2; 101 device const float* yr = y + (ulong) gr * 3 * D; 102 for (int i = tid; i < 2 * heads * half_; i += nt) { 103 const int part = i / (heads * half_), rem = i % (heads * half_), h = rem / half_, j = rem % half_; 104 const int base = part * D + h * hd; 105 const float av = yr[base + j] + bias[base + j], cv = yr[base + j + half_] + bias[base + j + half_]; 106 const float freq = precise::pow(a.theta_scale, (float) (j % quarter)); 107 float cs; 108 const float sn = precise::sincos((float) (j < quarter ? ty : tx) * freq, cs); 109 device ushort* dst = (part == 0 ? q : k) + (ulong) t * D + h * hd; 110 const float sc = part == 0 ? a.qscale : 1.0f; 111 dst[j] = f_to_f16bits((av * cs - cv * sn) * sc); 112 dst[j + half_] = f_to_f16bits((av * sn + cv * cs) * sc); 113 } 114 for (int e = tid; e < D; e += nt) v[(ulong) t * D + e] = f_to_f16bits(yr[2 * D + e] + bias[2 * D + e]); 115} 116 117struct SoftmaxArgs { int n, ld; }; 118// In place: a row of n F16 scores becomes the row of probabilities, F16. One group a row; PER scores a thread held in registers (threads * PER >= n). 119template <int PER> 120kernel void vk_softmax_rows(device ushort* S [[buffer(0)]], constant SoftmaxArgs& a [[buffer(15)]], uint row [[threadgroup_position_in_grid]], 121 ushort tid [[thread_index_in_threadgroup]], ushort nt [[threads_per_threadgroup]]) { 122 threadgroup float red[32]; 123 device ushort* s = S + (ulong) row * a.ld; 124 const int n = a.n; 125 float v[PER]; 126 float m = -FLT_MAX; 127 for (int k = 0; k < PER; ++k) { 128 const int j = int(tid) + k * int(nt); 129 v[k] = j < n ? f16bits_to_f(s[j]) : -FLT_MAX; 130 m = fmax(m, v[k]); 131 } 132 m = tg_max(m, red, tid, nt); 133 float sum = 0.0f; 134 for (int k = 0; k < PER; ++k) { 135 const int j = int(tid) + k * int(nt); 136 v[k] = j < n ? precise::exp(v[k] - m) : 0.0f; 137 sum += v[k]; 138 } 139 threadgroup_barrier(mem_flags::mem_threadgroup); 140 const float inv = 1.0f / tg_sum(sum, red, tid, nt); 141 for (int k = 0; k < PER; ++k) { 142 const int j = int(tid) + k * int(nt); 143 if (j < n) s[j] = f_to_f16bits(v[k] * inv); 144 } 145} 146template [[host_name("vk_softmax_rows_2")]] kernel decltype(vk_softmax_rows<2>) vk_softmax_rows<2>; 147template [[host_name("vk_softmax_rows_8")]] kernel decltype(vk_softmax_rows<8>) vk_softmax_rows<8>; 148template [[host_name("vk_softmax_rows_16")]] kernel decltype(vk_softmax_rows<16>) vk_softmax_rows<16>; 149template [[host_name("vk_softmax_rows_64")]] kernel decltype(vk_softmax_rows<64>) vk_softmax_rows<64>; 150 151// The same for a row too long to hold in registers: three passes over the row in memory. 152kernel void vk_softmax_rows_long(device ushort* S [[buffer(0)]], constant SoftmaxArgs& a [[buffer(15)]], uint row [[threadgroup_position_in_grid]], 153 ushort tid [[thread_index_in_threadgroup]], ushort nt [[threads_per_threadgroup]]) { 154 threadgroup float red[32]; 155 device ushort* s = S + (ulong) row * a.ld; 156 const int n = a.n; 157 float m = -FLT_MAX; 158 for (int j = tid; j < n; j += nt) m = fmax(m, f16bits_to_f(s[j])); 159 m = tg_max(m, red, tid, nt); 160 float sum = 0.0f; 161 for (int j = tid; j < n; j += nt) sum += precise::exp(f16bits_to_f(s[j]) - m); 162 threadgroup_barrier(mem_flags::mem_threadgroup); 163 const float inv = 1.0f / tg_sum(sum, red, tid, nt); 164 for (int j = tid; j < n; j += nt) s[j] = f_to_f16bits(precise::exp(f16bits_to_f(s[j]) - m) * inv); 165} 166 167struct EltArgs { ulong n; int kind; int D; }; 168// n floats to the 16-bit kind (grid-stride) 169kernel void vk_cast(device const float* in [[buffer(0)]], device void* out [[buffer(1)]], constant EltArgs& a [[buffer(15)]], 170 uint gid [[thread_position_in_grid]], uint gsz [[threads_per_grid]]) { 171 for (ulong i = gid; i < a.n; i += gsz) store_kind(out, i, in[i], a.kind); 172} 173// y[i] rounded to the 16-bit kind and back (STRATA_VIT_REF_ROUND, a diagnostic) 174kernel void vk_round(device float* y [[buffer(0)]], constant EltArgs& a [[buffer(15)]], uint gid [[thread_position_in_grid]], uint gsz [[threads_per_grid]]) { 175 for (ulong i = gid; i < a.n; i += gsz) { 176 const float v = y[i]; 177 y[i] = a.kind == K_F16 ? float(half(v)) : bf16_to_f(f_to_bf16(v)); 178 } 179} 180// x[r] += y[r] + bias. One group a row. 181kernel void vk_add_bias_res(device float* x [[buffer(0)]], device const float* y [[buffer(1)]], device const float* bias [[buffer(2)]], 182 constant EltArgs& a [[buffer(15)]], uint row [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], 183 ushort nt [[threads_per_threadgroup]]) { 184 const ulong base = (ulong) row * a.D; 185 for (int i = tid; i < a.D; i += nt) x[base + i] += y[base + i] + bias[i]; 186} 187// out = gelu_tanh(y + bias) into `kind`. One group a row of D. 188kernel void vk_bias_gelu_cast(device const float* y [[buffer(0)]], device const float* bias [[buffer(1)]], device void* out [[buffer(2)]], 189 constant EltArgs& a [[buffer(15)]], uint row [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], 190 ushort nt [[threads_per_threadgroup]]) { 191 const ulong base = (ulong) row * a.D; 192 for (int i = tid; i < a.D; i += nt) { 193 const float x = y[base + i] + bias[i]; 194 const float g = 0.5f * x * (1.0f + precise::tanh(0.79788456080286535587989211986876f * x * (1.0f + 0.044715f * x * x))); 195 store_kind(out, base + i, g, a.kind); 196 } 197} 198// y[r] += bias. One group a row of D. 199kernel void vk_add_bias(device float* y [[buffer(0)]], device const float* bias [[buffer(1)]], constant EltArgs& a [[buffer(15)]], 200 uint row [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], ushort nt [[threads_per_threadgroup]]) { 201 const ulong base = (ulong) row * a.D; 202 for (int i = tid; i < a.D; i += nt) y[base + i] += bias[i]; 203} 204 205// ---- the plain GEMM (any Apple GPU): Y[z][r][o] = sum_k X[z][r][k] * W[z](o, k), float32 accumulation. 206// X: [rows][in], row stride ldx. W: WN false: [out][in], row stride ldw (k contiguous); WN true: [in][out], row stride ldw (o contiguous). 207// Y: [rows][out], row stride ldy. Batch z (grid z): the bases move by sx, sw, sy elements. 208// A 64 x 64 tile a group (4 simdgroups of 32 x 32), k in steps of 32, operands staged as float in threadgroup memory (exact for 16-bit inputs). 209struct GemmArgs { uint rows, in, out, ldx, ldw, ldy; ulong sx, sw, sy; }; 210 211template <typename T> inline float ld_e(device const T* p, ulong i); 212template <> inline float ld_e<float>(device const float* p, ulong i) { return p[i]; } 213template <> inline float ld_e<half>(device const half* p, ulong i) { return float(p[i]); } 214template <> inline float ld_e<ushort>(device const ushort* p, ulong i) { return bf16_to_f(p[i]); } // ushort = BF16 here 215template <typename T> inline void st_e(device T* p, ulong i, float v); 216template <> inline void st_e<float>(device float* p, ulong i, float v) { p[i] = v; } 217template <> inline void st_e<half>(device half* p, ulong i, float v) { p[i] = half(v); } 218 219template <typename TI, typename TO, bool WN> 220kernel void vk_gemm(device const TI* X0 [[buffer(0)]], device const TI* W0 [[buffer(1)]], device TO* Y0 [[buffer(2)]], constant GemmArgs& a [[buffer(15)]], 221 uint3 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], ushort sg [[simdgroup_index_in_threadgroup]]) { 222 threadgroup float smem[4096]; // As [64][32] then Bs [32][64]; reused for the result tile [64][64] 223 threadgroup float* As = smem; 224 threadgroup float* Bs = smem + 2048; 225 device const TI* X = X0 + a.sx * tgp.z; 226 device const TI* W = W0 + a.sw * tgp.z; 227 device TO* Y = Y0 + a.sy * tgp.z; 228 const uint o0 = tgp.x * 64u, r0 = tgp.y * 64u; 229 const uint sr = (uint(sg) >> 1) * 32u, so = (uint(sg) & 1u) * 32u; 230 simdgroup_float8x8 acc[4][4]; 231 for (int i = 0; i < 4; ++i) 232 for (int j = 0; j < 4; ++j) acc[i][j] = make_filled_simdgroup_matrix<float, 8, 8>(0.0f); 233 for (uint k0 = 0; k0 < a.in; k0 += 32u) { 234 for (uint idx = tid; idx < 2048u; idx += 128u) { 235 const uint r = idx >> 5, kk = idx & 31u; 236 const uint gr = r0 + r, gk = k0 + kk; 237 As[idx] = (gr < a.rows && gk < a.in) ? ld_e<TI>(X, ulong(gr) * a.ldx + gk) : 0.0f; 238 } 239 if (!WN) { 240 for (uint idx = tid; idx < 2048u; idx += 128u) { 241 const uint o = idx >> 5, kk = idx & 31u; 242 const uint go = o0 + o, gk = k0 + kk; 243 Bs[kk * 64u + o] = (go < a.out && gk < a.in) ? ld_e<TI>(W, ulong(go) * a.ldw + gk) : 0.0f; 244 } 245 } else { 246 for (uint idx = tid; idx < 2048u; idx += 128u) { 247 const uint kk = idx >> 6, o = idx & 63u; 248 const uint go = o0 + o, gk = k0 + kk; 249 Bs[idx] = (go < a.out && gk < a.in) ? ld_e<TI>(W, ulong(gk) * a.ldw + go) : 0.0f; 250 } 251 } 252 threadgroup_barrier(mem_flags::mem_threadgroup); 253 for (uint k8 = 0; k8 < 4u; ++k8) { 254 simdgroup_float8x8 fa[4], fb[4]; 255 for (uint i = 0; i < 4u; ++i) simdgroup_load(fa[i], As + (sr + i * 8u) * 32u + k8 * 8u, 32); 256 for (uint j = 0; j < 4u; ++j) simdgroup_load(fb[j], Bs + k8 * 8u * 64u + so + j * 8u, 64); 257 for (uint i = 0; i < 4u; ++i) 258 for (uint j = 0; j < 4u; ++j) simdgroup_multiply_accumulate(acc[i][j], fa[i], fb[j], acc[i][j]); 259 } 260 threadgroup_barrier(mem_flags::mem_threadgroup); 261 } 262 for (uint i = 0; i < 4u; ++i) 263 for (uint j = 0; j < 4u; ++j) simdgroup_store(acc[i][j], smem + (sr + i * 8u) * 64u + so + j * 8u, 64); 264 threadgroup_barrier(mem_flags::mem_threadgroup); 265 for (uint idx = tid; idx < 4096u; idx += 128u) { 266 const uint r = idx >> 6, o = idx & 63u; 267 const uint gr = r0 + r, go = o0 + o; 268 if (gr >= a.rows || go >= a.out) continue; 269 st_e<TO>(Y, ulong(gr) * a.ldy + go, smem[idx]); 270 } 271} 272// The float32 patch product (7 GFLOP for a 1,024-token picture): one output a thread, a plain sequential FMA chain over k. Not the tiled kernel above: 273// the first run of vk_gemm costs the process about 136 MB of GPU-owned memory on an M5 Max (RESULTS-OWN-3V.md D5), which a Mac with the tensor-op 274// products then never needs to pay. Grid (ceil(out / 64), rows), 64 threads. 275kernel void vk_gemm_seq_f32(device const float* X [[buffer(0)]], device const float* W [[buffer(1)]], device float* Y [[buffer(2)]], 276 constant GemmArgs& a [[buffer(15)]], uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) { 277 const uint o = tgp.x * 64u + uint(tid), r = tgp.y; 278 if (o >= a.out || r >= a.rows) return; 279 device const float* x = X + ulong(r) * a.ldx; 280 device const float* w = W + ulong(o) * a.ldw; 281 float s = 0.0f; 282 for (uint k = 0; k < a.in; ++k) s = fma(x[k], w[k], s); 283 Y[ulong(r) * a.ldy + o] = s; 284} 285 286// weight products: 16-bit (or float32) X and W, float32 Y 287template [[host_name("vk_gemm_f32")]] kernel decltype(vk_gemm<float, float, false>) vk_gemm<float, float, false>; 288template [[host_name("vk_gemm_f16")]] kernel decltype(vk_gemm<half, float, false>) vk_gemm<half, float, false>; 289template [[host_name("vk_gemm_bf16")]] kernel decltype(vk_gemm<ushort, float, false>) vk_gemm<ushort, float, false>; 290// attention: S = Q K^T (F16 in, F16 out) and context = P V (F16 in, V o-contiguous, float32 out) 291template [[host_name("vk_gemm_s")]] kernel decltype(vk_gemm<half, half, false>) vk_gemm<half, half, false>; 292template [[host_name("vk_gemm_pv")]] kernel decltype(vk_gemm<half, float, true>) vk_gemm<half, float, true>;