okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
c7ea3ac6a
main
1// tools/vision/own/vit_metal.mm - see vit_gpu.h: the Qwen vision tower on a Mac's GPU (Metal), the counterpart of vit_gpu.cu (CUDA / HIP) and 2// vit_sycl.cpp (Intel). The same host flow and the same numbers: weights stay as the file stores them (BF16 or F16; F32 matrices become BF16, Q8_0 3// becomes F16), float32 activations, each matrix product with a 16-bit input of the weight's type and float32 accumulation, q / k / v and the scores 4// in F16, the same chunk rules. Its own small Metal host (one device, one queue, shared buffers, one command buffer per layer); the kernels 5// (vit_metal.metal, and the tensor-op products in vit_metal_mpp.metal) are embedded in the program and compiled when the reader starts. 6// 7// The products: the Metal 4 tensor ops (MetalPerformancePrimitives matmul2d) where they compile and a self-test against the plain simdgroup kernel 8// passes, decided per product at load and logged once; else the plain kernel. STRATA_VIT_NO_MPP=1 (a diagnostic) asks for the plain kernel everywhere. 9#import <Foundation/Foundation.h> 10#import <Metal/Metal.h> 11 12#include "vit_gpu.h" 13#include "vit_metal_src.h" // generated at build time: kVitMetalSrc, kVitMetalMppSrc 14 15#include <algorithm> 16#include <chrono> 17#include <cmath> 18#include <cstdio> 19#include <cstdint> 20#include <cstdlib> 21#include <cstring> 22#include <map> 23#include <set> 24 25#include <mach/mach.h> 26#include <malloc/malloc.h> 27 28namespace strata_vit { 29 30namespace { 31 32enum Kind {K_F32 = 0 ,K_F16 = 1 ,K_BF16 = 2 }; 33 34struct DevW {// a weight matrix [rows = out][cols = in] on the device 35id < MTLBuffer > b = nil ; 36Kind kind = K_BF16 ; 37int rows = 0 ,cols = 0 ; 38}; 39 40struct DevLayer { 41id < MTLBuffer > ln1_w = nil ,ln1_b = nil ,ln2_w = nil ,ln2_b = nil ,qkv_b = nil ,o_b = nil ,up_b = nil ,down_b = nil ; 42DevW qkv ,o ,up ,down ; 43}; 44 45// a buffer and a byte offset into it 46struct BO { 47id < MTLBuffer > b ; 48size_t off ; 49BO (id < MTLBuffer > buf ,size_t o = 0 ) :b (buf ),off (o ) {} 50}; 51 52// the argument structs of vit_metal.metal (same layout) 53struct PatchPostArgs {int32_t G ,pw ,ph ,nbx ,D ; }; 54struct NormArgs {int32_t D ,kind ;float eps ; }; 55struct RopeArgs {int32_t row0 ,nbx ,heads ,hd ;float theta_scale ,qscale ; }; 56struct SoftmaxArgs {int32_t n ,ld ; }; 57struct EltArgs {uint64_t n ;int32_t kind ;int32_t D ; }; 58struct GemmArgs {uint32_t rows ,in ,out ,ldx ,ldw ,ldy ;uint64_t sx ,sw ,sy ; }; 59 60uint16_t host_f32_to_bf16 (float f ) { 61uint32_t u ; 62std ::memcpy (& u ,& f ,4 ); 63if ((u & 0x7fffffffu )> 0x7f800000u )return (uint16_t ) ((u >> 16 ) |0x40 ); 64u += 0x7fffu + ((u >> 16 )& 1u ); 65return (uint16_t ) (u >> 16 ); 66} 67uint16_t host_f32_to_f16 (float f ) { 68const __fp16 h = (__fp16 )f ;// round to nearest even (clang on arm64) 69uint16_t u ; 70std ::memcpy (& u ,& h ,2 ); 71return u ; 72} 73// STRATA_VIT_MEM=1 (a diagnostic, stderr only): the process's physical footprint (what the gate reads with `footprint`) at a point of the load 74void footprint_note (const char * where ) { 75static const bool on = std ::getenv ("STRATA_VIT_MEM" )!= nullptr ; 76if (!on )return ; 77task_vm_info_data_t vi ; 78mach_msg_type_number_t n = TASK_VM_INFO_COUNT ; 79if (task_info (mach_task_self (),TASK_VM_INFO , (task_info_t )& vi ,& n )== KERN_SUCCESS ) 80std ::fprintf (stderr ,"vit-mem: %-34s footprint %.1f MiB\n" ,where , (double )vi .phys_footprint /1048576.0 ); 81} 82 83float host_f16_to_f32 (uint16_t u ) { 84__fp16 h ; 85std ::memcpy (& h ,& u ,2 ); 86return (float )h ; 87} 88 89}// namespace 90 91struct VitGpuImpl { 92VitGeometry g ; 93id < MTLDevice > dev = nil ; 94id < MTLCommandQueue > queue = nil ; 95id < MTLLibrary > lib = nil ,lib_mpp = nil ; 96std ::map < std ::string ,id < MTLComputePipelineState >> pipes ; 97id < MTLCommandBuffer > cb = nil ; 98id < MTLComputeCommandEncoder > enc = nil ; 99std ::string fail ;// the first dispatch problem (a missing pipeline, a group too large for a pipeline): encode reports it 100size_t bytes = 0 ,work_bytes = 0 ; 101 102id < MTLBuffer > patch_w = nil ,patch_b = nil ,pos = nil ,post_w = nil ,post_b = nil ,mm0_b = nil ,mm2_b = nil ; 103DevW mm0 ,mm2 ; 104std ::vector < DevLayer > layers ; 105 106// the product kernels chosen at load (the self-test): tensor op or plain, per product 107bool mpp_bf16 = false,mpp_f16 = false,mpp_s = false,mpp_pv = false; 108 109int cap_patches = 0 ; 110// work buffers (as vit_gpu.cu): d_x residual [N][D]; d_ctx context [N][D] (also the patch matrix, and the projector's output at the end); d_y one 111// chunk's product; d_a a chunk's 16-bit GEMM input; d_f16 the activated FFN / merger hidden of a chunk; q, k, v [N][D] F16; d_S the scores of a chunk 112id < MTLBuffer > d_x = nil ,d_ctx = nil ,d_y = nil ,d_a = nil ,d_f16 = nil ,d_q16 = nil ,d_k16 = nil ,d_v16 = nil ,d_S = nil ; 113size_t sp_elems = 0 ; 114int kRows = 512 ; 115size_t kScoreElems = (size_t )8 <<20 ; 116size_t kScoreElemsLarge = (size_t )256 <<20 ;// above 16,384 patches (512 MB of F16; the SYCL tower's choice; vit_gpu.cu takes 512M on CUDA / HIP) 117bool scores_env = false; 118int n_pad = 0 ,q_align = 0 ; 119int pad_for (size_t n )const {return n_pad ?n_pad :n > 16384 ?64 :8 ; } 120int align_for (size_t n )const {return q_align ?q_align :n > 16384 ?64 :1 ; } 121size_t padded (size_t n )const {const size_t p = (size_t )pad_for (n );return (n + p - 1 ) /p * p ; } 122bool round_out = false; 123 124 ~VitGpuImpl () {finish (); } 125 126id < MTLBuffer > buf (size_t n_bytes ,bool weight ,std ::string & err ) { 127id < MTLBuffer > b = [dev newBufferWithLength :std ::max < size_t > (n_bytes ,16 )options :MTLResourceStorageModeShared ]; 128if (!b ) {err = "GPU memory: no buffer of " + std ::to_string (n_bytes )+ " bytes" ;return nil ; } 129bytes += n_bytes ; 130if (!weight )work_bytes += n_bytes ; 131return b ; 132 } 133id < MTLBuffer > buf_from (const void * src ,size_t n_bytes ,std ::string & err ) { 134id < MTLBuffer > b = buf (n_bytes , true,err ); 135if (b )std ::memcpy ([b contents ],src ,n_bytes ); 136return b ; 137 } 138bool upload_f32 (__strong id < MTLBuffer > & dst ,const Gguf & gg ,const std ::string & name ,std ::string & err ) { 139const GgufTensorInfo * t = gg .tensor (name ); 140if (!t ) {err = "the mmproj file lacks the tensor " + name ;return false; } 141std ::vector < float > h ((size_t )t -> nelem ()); 142if (!gg .read_f32 (* t ,h .data (),err ))return false; 143dst = buf_from (h .data (),h .size ()* 4 ,err ); 144return dst != nil ; 145 } 146bool upload_matrix (DevW & w ,const Gguf & gg ,const std ::string & name ,std ::string & err ) { 147const GgufTensorInfo * t = gg .tensor (name ); 148if (!t || t -> ne .size ()!= 2 ) {err = "the mmproj file lacks the matrix " + name ;return false; } 149w .cols = (int )t -> ne [0 ]; 150w .rows = (int )t -> ne [1 ]; 151const size_t n = (size_t )t -> nelem (); 152std ::vector < uint16_t > raw (n ); 153if (t -> type == GT_F16 || t -> type == GT_BF16 ) {// as stored 154if (!gg .read_raw (* t ,raw .data (),err ))return false; 155w .kind = t -> type == GT_F16 ?K_F16 :K_BF16 ; 156 }else {// F32 -> BF16, Q8_0 -> F16 157std ::vector < float > f (n ); 158if (!gg .read_f32 (* t ,f .data (),err ))return false; 159const bool bf = t -> type == GT_F32 ; 160w .kind = bf ?K_BF16 :K_F16 ; 161for (size_t i = 0 ;i < n ;++ i )raw [i ]= bf ?host_f32_to_bf16 (f [i ]) :host_f32_to_f16 (f [i ]); 162 } 163w .b = buf_from (raw .data (),n * 2 ,err ); 164return w .b != nil ; 165 } 166 167// ---- dispatching ---- 168id < MTLComputePipelineState > pipe (const std ::string & fn ) { 169 autoit = pipes. find (fn); 170if (it != pipes. end ()) return it -> second; 171id < MTLLibrary > L = fn. rfind ( "vm_" , 0 ) == 0 ? lib_mpp : lib; 172id < MTLFunction > f = L ? [L newFunctionWithName:[NSString stringWithUTF8String:fn. c_str ()]] : nil; 173NSError * e = nil; 174id < MTLComputePipelineState > p = f ? [dev newComputePipelineStateWithFunction:f error: & e] : nil; 175pipes[fn] = p; 176return p; 177} 178id < MTLComputeCommandEncoder > encoder() { 179if (!cb) cb = [queue commandBuffer]; 180if (!enc) enc = [cb computeCommandEncoder]; // serial dispatch: each dispatch sees the previous one's writes 181return enc; 182} 183void go( const std ::string & fn, std ::initializer_list < BO > bufs, const void * args, size_t args_bytes, MTLSize grid, NSUInteger threads) { 184if (!fail. empty ()) return ; 185if (grid.width == 0 || grid.height == 0 || grid.depth == 0 ) return ; 186id < MTLComputePipelineState > p = pipe(fn); 187if (!p) { fail = "no pipeline " + fn; return ; } 188// a group larger than the pipeline allows is NOT run by Metal, and no error is raised (the engine's #2323): so check every dispatch 189if ([p maxTotalThreadsPerThreadgroup] < threads) { 190fail = fn + " needs " + std::to_string(threads) + " threads a group, this GPU allows " + std::to_string(( size_t ) [p maxTotalThreadsPerThreadgroup]); 191return ; 192} 193id < MTLComputeCommandEncoder > e = encoder(); 194[e setComputePipelineState:p]; 195NSUInteger i = 0 ; 196for ( const BO & b : bufs) [e setBuffer:b.b offset:b.off atIndex:i ++ ]; 197[e setBytes:args length:args_bytes atIndex: 15 ]; 198[e dispatchThreadgroups:grid threadsPerThreadgroup:MTLSizeMake(threads, 1 , 1 )]; 199// STRATA_VIT_MEM=1: the footprint after the first run of each kernel (the GPU waited for), to see which one takes memory on first use 200static const bool mem = std::getenv( "STRATA_VIT_MEM" ) != nullptr ; 201if (mem && seen. insert (fn).second) { 202(void) finish(); 203footprint_note(( "first run of " + fn). c_str ()); 204} 205} 206std::set < std::string > seen; 207// commit what is encoded as its own command buffer, without waiting (one per layer: no long-running buffer) 208void split() { 209if (enc) { [enc endEncoding]; enc = nil; } 210if (cb) { [cb commit]; last = cb; cb = nil; } 211} 212id < MTLCommandBuffer > last = nil; 213// commit and wait for everything encoded so far; false (with the reason) on a GPU error 214bool finish(std::string * err = nullptr ) { 215split(); 216if (last) { 217[last waitUntilCompleted]; 218const bool ok = [last status] == MTLCommandBufferStatusCompleted; 219if (!ok && err) { 220NSError * e = [last error]; 221* err = std::string( "the GPU work failed: " ) + (e ? [[e localizedDescription] UTF8String] : "unknown" ); 222} 223last = nil; 224return ok; 225} 226return true; 227} 228 229// Y[z][rows][out] = X[z][rows][in] * W[z](out, in), float32 accumulation; `wn`: W is [in][out]; the product's kernel by name (plain) or tensor op 230void gemm( const char * plain, const char * mpp, BO X, BO W, BO Y, int rows, int in, int out, int ldx, int ldw, int ldy, size_t sx, size_t sw, size_t sy, 231int batch, int tm = 64 ) { 232const GemmArgs a{( uint32_t ) rows, ( uint32_t ) in, ( uint32_t ) out, ( uint32_t ) ldx, ( uint32_t ) ldw, ( uint32_t ) ldy, sx, sw, sy}; 233const bool use = mpp != nullptr ; 234const int TM = use ? tm : 64 ; 235go(use ? mpp : plain, {X, W, Y}, & a, sizeof a, MTLSizeMake((out + 63 ) / 64 , (rows + TM - 1 ) / TM, batch), 128 ); 236} 237// y[M][w.rows] (float32) = A[M][K] (w's kind) * w^T 238void wgemm( const DevW & w, BO A, int M, BO y) { 239const char * plain = w.kind == K_F16 ? "vk_gemm_f16" : "vk_gemm_bf16" ; 240const char * mpp = nullptr ; 241if (w.kind == K_F16 && mpp_f16) mpp = M >= 128 ? "vm_gemm_f16_128" : "vm_gemm_f16_64" ; 242if (w.kind == K_BF16 && mpp_bf16) mpp = M >= 128 ? "vm_gemm_bf16_128" : "vm_gemm_bf16_64" ; 243gemm(plain, mpp, A, BO(w.b), y, M, w.cols, w.rows, w.cols, w.cols, w.rows, 0 , 0 , 0 , 1 , M >= 128 ? 128 : 64 ); 244if (round_out) { 245const EltArgs e{( uint64_t ) M * w.rows, ( int32_t ) w.kind, 0 }; 246go( "vk_round" , {y}, & e, sizeof e, MTLSizeMake(blocks_for(e.n), 1 , 1 ), 256 ); 247} 248} 249static NSUInteger blocks_for( size_t n, int per = 256 ) { return (NSUInteger) std::min < size_t > ((n + per - 1 ) / per, 65535 ); } 250 251bool size_buffers( int patches, std ::string & err) { 252if (patches <= cap_patches) return true; 253if (!finish( & err)) return false; 254bytes -= work_bytes; 255work_bytes = 0 ; 256d_x = d_ctx = d_y = d_a = d_f16 = d_q16 = d_k16 = d_v16 = d_S = nil; 257const size_t N = ( size_t ) patches, D = ( size_t ) g.width, F = ( size_t ) std::max(g.ffn, g.merger_hidden); 258const size_t K0 = ( size_t ) 3 * g.patch * g.patch; 259const size_t Np = padded(N); 260const size_t budget = (N > 16384 && !scores_env) ? kScoreElemsLarge : kScoreElems; 261sp_elems = std::min < size_t > (( size_t ) g.heads * N * Np, std::max < size_t > (budget, ( size_t ) g.heads * Np * 64 )); 262const size_t R = std::min < size_t > (N, ( size_t ) kRows); 263const size_t ctx_elems = std::max({N * D, N * K0, (N / 4 ) * ( size_t ) g.out_dim}); 264d_x = buf(N * D * 4 , false, err); 265d_ctx = d_x ? buf(ctx_elems * 4 , false, err) : nil; 266d_y = d_ctx ? buf(R * std::max < size_t > ( 3 * D, F) * 4 , false, err) : nil; 267d_a = d_y ? buf(R * D * 2 , false, err) : nil; 268d_f16 = d_a ? buf(R * F * 2 , false, err) : nil; 269d_q16 = d_f16 ? buf(N * D * 2 , false, err) : nil; 270d_k16 = d_q16 ? buf(N * D * 2 , false, err) : nil; 271d_v16 = d_k16 ? buf(N * D * 2 , false, err) : nil; 272if (!d_v16) { cap_patches = 0 ; return false; } 273d_S = buf(sp_elems * 2 , false, err); 274if (!d_S && budget != kScoreElems) { // no room for the large chunk: the default chunk instead, slower, never an error 275err. clear (); 276sp_elems = std::min < size_t > (( size_t ) g.heads * N * Np, std::max < size_t > (kScoreElems, ( size_t ) g.heads * Np * 64 )); 277d_S = buf(sp_elems * 2 , false, err); 278} 279if (!d_S) { cap_patches = 0 ; return false; } 280cap_patches = patches; 281return true; 282} 283 284// The tensor-op products against the plain kernel on small odd sizes (a batch of 2, strides wider than the rows): true when every value agrees within 285// float32 rounding of a different summation order. One check per product kind. 286bool mpp_check( const char * plain, const char * mpp, int ti /* 1 F16, 2 BF16 */ , bool wn, bool out_half, std ::string & why) { 287const int M = 70 , N = 90 , K = 100 , LDX = 104 , LDW = wn ? 136 : 104 , LDY = 96 , B = 2 ; 288const size_t sx = ( size_t ) M * LDX, sw = ( size_t ) (wn ? K : N) * LDW, sy = ( size_t ) M * LDY; 289std :: string e; 290id < MTLBuffer > bx = buf(sx * B * 2 , false, e), bw = buf(sw * B * 2 , false, e), y0 = buf(sy * B * 4 , false, e), y1 = buf(sy * B * 4 , false, e); 291if (!bx || !bw || !y0 || !y1) { why = "no memory for the self-test" ; return false; } 292uint32_t seed = 12345u ; 293auto rnd = [ & ]() { seed = seed * 1664525u + 1013904223u ; return ( float ) ((seed >> 8 ) & 0xffffu ) / 32768.0f - 1.0f ; }; 294uint16_t * px = ( uint16_t * ) [bx contents]; 295uint16_t * pw = ( uint16_t * ) [bw contents]; 296for ( size_t i = 0 ; i < sx * B; ++ i) px[i] = ti == 1 ? host_f32_to_f16(rnd()) : host_f32_to_bf16(rnd()); 297for ( size_t i = 0 ; i < sw * B; ++ i) pw[i] = ti == 1 ? host_f32_to_f16(rnd()) : host_f32_to_bf16(rnd()); 298std ::memset([y0 contents], 0 , sy * B * 4 ); 299std ::memset([y1 contents], 0 , sy * B * 4 ); 300// the expected result on the host (double sums of the 16-bit inputs), written in the output's type into y0. Not the plain GPU kernel: its first 301// run costs the process ~136 MB of GPU-owned memory (D5), which a Mac with the tensor ops would otherwise never pay 302( void ) plain; 303{ 304auto in16 = [ & ](uint16_t u) { return ti == 1 ? ( double ) host_f16_to_f32(u) : ( double ) []( uint16_t b) { uint32_t v = (uint32_t) b << 16 ; float f; std ::memcpy( & f, & v, 4 ); return f; }(u); }; 305for ( int z = 0 ; z < B; ++ z) 306for ( int r = 0 ; r < M; ++ r) 307for ( int c = 0 ; c < N; ++ c) { 308double s = 0.0 ; 309for ( int k = 0 ; k < K; ++ k) { 310const double x = in16(px[( size_t ) z * sx + ( size_t ) r * LDX + k]); 311const double w = wn ? in16(pw[( size_t ) z * sw + ( size_t ) k * LDW + c]) : in16(pw[( size_t ) z * sw + ( size_t ) c * LDW + k]); 312s += x * w; 313} 314const size_t i = ( size_t ) z * sy + ( size_t ) r * LDY + c; 315if (out_half) (( uint16_t * ) [y0 contents])[i] = host_f32_to_f16(( float ) s); 316else (( float * ) [y0 contents])[i] = ( float ) s; 317} 318} 319gemm(plain, mpp, BO(bx), BO(bw), BO(y1), M, K, N, LDX, LDW, LDY, sx, sw, sy, B, 64 ); 320std :: string ferr; 321const bool ran = fail. empty () && finish( & ferr); 322bytes -= (sx * B * 2 + sw * B * 2 + sy * B * 8 ); 323work_bytes -= (sx * B * 2 + sw * B * 2 + sy * B * 8 ); 324if (!ran) { why = fail. empty () ? ferr : fail; fail. clear (); return false; } 325double worst = 0.0 ; 326for ( int z = 0 ; z < B; ++ z) 327for ( int r = 0 ; r < M; ++ r) 328for ( int c = 0 ; c < N; ++ c) { 329const size_t i = ( size_t ) z * sy + ( size_t ) r * LDY + c; 330float a, b; 331if (out_half) { a = host_f16_to_f32((( uint16_t * ) [y0 contents])[i]); b = host_f16_to_f32((( uint16_t * ) [y1 contents])[i]); } 332else { a = (( float * ) [y0 contents])[i]; b = (( float * ) [y1 contents])[i]; } 333const double d = std::fabs(( double ) a - ( double ) b); 334worst = std::max(worst, d); 335const double tol = out_half ? 1e-2 + 2e-3 * std::fabs(( double ) a) : 1e-3 + 1e-4 * std::fabs(( double ) a); 336if (!(d <= tol)) { 337char m[ 160 ]; 338std ::snprintf(m, sizeof m, "differs from the exact product (%g against %g at %d,%d,%d)" , ( double ) b, ( double ) a, z, r, c); 339why = m; 340return false; 341} 342} 343return true; 344} 345}; 346 347VitGpu ::VitGpu() : impl_( new VitGpuImpl ()) {} 348VitGpu ::~VitGpu() = default; 349size_t VitGpu::device_bytes() const { return impl_ -> bytes; } 350 351bool VitGpu::available( std ::string & why) { 352@autoreleasepool { 353id < MTLDevice > d = MTLCreateSystemDefaultDevice(); 354if (!d) { why = "no Metal GPU" ; return false; } 355return true; 356} 357} 358 359bool VitGpu::prefer_mtmd( bool bf16_matrices, int max_tokens, std ::string & why) { 360// the Metal tower passed its gate on the M5 Max (RESULTS-OWN-3V.md D1, D4-D8: rule 1 and 2, 0.47 to 0.79 of mtmd-Metal's time, less memory, the 16,384-token 361// picture that mtmd-Metal aborts on), so `auto` (the default) takes it on every Mac (owner 11-11: our tower the default, mtmd selectable) 362( void ) bf16_matrices; 363( void ) max_tokens; 364( void ) why; 365return false; 366} 367 368bool VitGpu::load( const Gguf & gg, const VitGeometry & g, int device, int max_patches, std ::string & err) { 369@autoreleasepool { 370VitGpuImpl & m = * impl_; 371( void ) device; // one GPU on a Mac 372std :: string why; 373if (!vit_geometry_supported(g, why)) { err = "this tower is not supported: " + why; return false; } 374m.g = g; 375footprint_note( "start of the load" ); 376m.dev = MTLCreateSystemDefaultDevice(); 377if (!m.dev) { err = "no Metal GPU" ; return false; } 378m.queue = [m.dev newCommandQueue]; 379footprint_note( "device and queue" ); 380// the kernels: safe maths (no fast-math), compiled from the embedded source 381{ 382MTLCompileOptions * o = [MTLCompileOptions new]; 383if ( @available (macOS 15.0 , * )) o.mathMode = MTLMathModeSafe; 384else { 385#pragma clang diagnostic push 386#pragma clang diagnostic ignored "-Wdeprecated-declarations" 387o.fastMathEnabled = NO; // macOS before 15: the only switch there (fast maths is the default) 388#pragma clang diagnostic pop 389} 390NSError * e = nil; 391m.lib = [m.dev newLibraryWithSource:[NSString stringWithUTF8String:kVitMetalSrc] options:o error: & e]; 392if (!m.lib) { err = std::string( "the Metal kernels do not compile: " ) + (e ? [[e localizedDescription] UTF8String] : "unknown" ); return false; } 393} 394footprint_note( "plain kernels compiled" ); 395if (std::getenv( "STRATA_VIT_MEM" )) { // diagnostic: does any first dispatch cost the ~250 MB, or only the product kernels' (D5)? 396std :: string e; 397id < MTLBuffer > t = m. buf ( 4096 , false, e), tb = m. buf ( 4096 , false, e); 398const EltArgs a{ 0 , 0 , 16 }; 399m. go ( "vk_add_bias" , {BO(t), BO(tb)}, & a, sizeof a, MTLSizeMake( 4 , 1 , 1 ), 32 ); 400( void ) m. finish (); 401footprint_note( "after one tiny vk_add_bias" ); 402m.bytes -= 8192 ; m.work_bytes -= 8192 ; 403} 404// the tensor-op products: Metal 4 only, then per product a self-test against the plain kernel 405std :: string mpp_why; 406const bool no_mpp = std::getenv( "STRATA_VIT_NO_MPP" ) != nullptr ; 407bool metal4 = false; 408if ( @available (macOS 26.0 , * )) metal4 = [m.dev supportsFamily:MTLGPUFamilyMetal4]; 409if (no_mpp) mpp_why = "STRATA_VIT_NO_MPP" ; 410else if (!metal4) mpp_why = "no Metal 4 on this GPU or macOS" ; 411else { 412MTLCompileOptions * o = [MTLCompileOptions new]; 413if ( @available (macOS 15.0 , * )) o.mathMode = MTLMathModeSafe; 414NSError * e = nil; 415m.lib_mpp = [m.dev newLibraryWithSource:[NSString stringWithUTF8String:kVitMetalMppSrc] options:o error: & e]; 416if (!m.lib_mpp) mpp_why = std::string( "the tensor-op kernels do not compile (" ) + (e ? std::string([[e localizedDescription] UTF8String]). substr ( 0 , 160 ) : "unknown" ) + ")" ; 417} 418std :: string w_bf, w_f16, w_s, w_pv; 419if (m.lib_mpp) { 420m.mpp_bf16 = m. mpp_check ( "vk_gemm_bf16" , "vm_gemm_bf16_64" , 2 , false, false, w_bf); 421m.mpp_f16 = m. mpp_check ( "vk_gemm_f16" , "vm_gemm_f16_64" , 1 , false, false, w_f16); 422m.mpp_s = m. mpp_check ( "vk_gemm_s" , "vm_gemm_s" , 1 , false, true, w_s); 423m.mpp_pv = m. mpp_check ( "vk_gemm_pv" , "vm_gemm_pv" , 1 , true, false, w_pv); 424} 425// diagnostics: the plain kernel for one product only (STRATA_VIT_NO_MPP_W: the weight products, _S: the scores, _PV: the context) 426if (std::getenv( "STRATA_VIT_NO_MPP_W" )) { m.mpp_bf16 = m.mpp_f16 = false; w_bf = w_f16 = "STRATA_VIT_NO_MPP_W" ; } 427if (std::getenv( "STRATA_VIT_NO_MPP_S" )) { m.mpp_s = false; w_s = "STRATA_VIT_NO_MPP_S" ; } 428if (std::getenv( "STRATA_VIT_NO_MPP_PV" )) { m.mpp_pv = false; w_pv = "STRATA_VIT_NO_MPP_PV" ; } 429auto say = [ & ](bool on, const std::string & w) { return on ? std::string( "tensor op" ) : "plain " + (w.empty() ? (mpp_why.empty() ? std::string() : " ( " + mpp_why + " ) ") : " ( " + w + " )"); }; 430std::fprintf(stderr, "strata-vision: Metal tower on %s; products: BF16 weights %s, F16 weights %s, attention S %s, P*V %s; patch matrix float32, one output a thread\n" , 431[[m.dev name] UTF8String], say(m.mpp_bf16, w_bf). c_str (), say(m.mpp_f16, w_f16). c_str (), say(m.mpp_s, w_s). c_str (), say(m.mpp_pv, w_pv). c_str ()); 432m.bytes = m.work_bytes = 0 ; 433footprint_note( "kernels compiled, self-test done" ); 434// the patch embedding: the two temporal taps summed, kept in float32 (a small matrix) 435{ 436const GgufTensorInfo * t0 = gg. tensor ( "v.patch_embd.weight" ); 437if (!t0) { err = "the mmproj file lacks v.patch_embd.weight" ; return false; } 438std ::vector < float > w0(( size_t ) t0 -> nelem ()), w1; 439if (!gg. read_f32 ( * t0, w0. data (), err)) return false; 440if (g.patch_taps == 2 ) { 441const GgufTensorInfo * t1 = gg. tensor ( "v.patch_embd.weight.1" ); 442w1. resize (w0. size ()); 443if (!t1 || !gg. read_f32 ( * t1, w1. data (), err)) { if (err. empty ()) err = "the mmproj file lacks v.patch_embd.weight.1" ; return false; } 444for ( size_t i = 0 ; i < w0. size (); ++ i) w0[i] += w1[i]; 445} 446m.patch_w = m. buf_from (w0. data (), w0. size () * 4 , err); 447if (!m.patch_w) return false; 448} 449if (!m. upload_f32 (m.patch_b, gg, "v.patch_embd.bias" , err) || !m. upload_f32 (m.pos, gg, "v.position_embd.weight" , err) || 450!m. upload_f32 (m.post_w, gg, "v.post_ln.weight" , err) || !m. upload_f32 (m.post_b, gg, "v.post_ln.bias" , err) || 451!m. upload_matrix (m.mm0, gg, "mm.0.weight" , err) || !m. upload_f32 (m.mm0_b, gg, "mm.0.bias" , err) || 452!m. upload_matrix (m.mm2, gg, "mm.2.weight" , err) || !m. upload_f32 (m.mm2_b, gg, "mm.2.bias" , err)) 453return false; 454m.layers. assign (( size_t ) g.layers, DevLayer{}); 455for ( int il = 0 ; il < g.layers; ++ il) { 456DevLayer & L = m.layers[( size_t ) il]; 457const std ::string p = "v.blk." + std::to_string(il) + "." ; 458if (!m. upload_f32 (L.ln1_w, gg, p + "ln1.weight" , err) || !m. upload_f32 (L.ln1_b, gg, p + "ln1.bias" , err) || 459!m. upload_f32 (L.ln2_w, gg, p + "ln2.weight" , err) || !m. upload_f32 (L.ln2_b, gg, p + "ln2.bias" , err) || 460!m. upload_matrix (L.qkv, gg, p + "attn_qkv.weight" , err) || !m. upload_f32 (L.qkv_b, gg, p + "attn_qkv.bias" , err) || 461!m. upload_matrix (L.o, gg, p + "attn_out.weight" , err) || !m. upload_f32 (L.o_b, gg, p + "attn_out.bias" , err) || 462!m. upload_matrix (L.up, gg, p + "ffn_up.weight" , err) || !m. upload_f32 (L.up_b, gg, p + "ffn_up.bias" , err) || 463!m. upload_matrix (L.down, gg, p + "ffn_down.weight" , err) || !m. upload_f32 (L.down_b, gg, p + "ffn_down.bias" , err)) 464return false; 465} 466if (const char * e = std::getenv( "STRATA_VIT_REF_ROUND" )) m.round_out = std::atoi(e) != 0 ; 467if (const char * e = std::getenv( "STRATA_VIT_ROWS" )) { const int v = std::atoi(e); if (v >= 16 ) m.kRows = v; } 468if (const char * e = std::getenv( "STRATA_VIT_SCORES" )) { const int v = std::atoi(e); if (v >= 1 ) { m.kScoreElems = ( size_t ) v << 20 ; m.scores_env = true; } } 469if (const char * e = std::getenv( "STRATA_VIT_SCORES_LARGE" )) { const long v = std::atol(e); if (v >= 1 ) m.kScoreElemsLarge = ( size_t ) v << 20 ; } 470if (const char * e = std::getenv( "STRATA_VIT_NPAD" )) { const int v = std::atoi(e); if (v >= 8 && v % 8 == 0 ) m.n_pad = v; } 471if (const char * e = std::getenv( "STRATA_VIT_QALIGN" )) { const int v = std::atoi(e); if (v >= 1 ) m.q_align = v; } 472footprint_note( "weights uploaded" ); 473const bool ok = m. size_buffers (std::max(max_patches, 16 ), err); 474footprint_note( "work buffers" ); 475// the host copies of the weights (one matrix at a time, up to ~10 MB each) are freed by now, but macOS's allocator keeps freed large blocks in its 476// cache, where they count in the reader's footprint (87 MB at READY, RESULTS-OWN-3V.md D5): hand them back 477malloc_zone_pressure_relief( nullptr , 0 ); 478return ok; 479} 480} 481 482bool VitGpu::encode( const PreparedImage & img, std ::vector < float > & rows, int & nx, int & ny, std ::string & err) { 483@autoreleasepool { 484VitGpuImpl & m = * impl_; 485const VitGeometry & g = m.g; 486if (m.layers. empty ()) { err = "the tower is not loaded" ; return false; } 487if (img.w <= 0 || img.h <= 0 || img.w % g. align () != 0 || img.h % g. align () != 0 ) { err = "the picture size is not a multiple of patch * merge" ; return false; } 488if (g.head_dim > 96 || g.head_dim % 4 != 0 ) { err = "this head size is not handled by the GPU attention kernel" ; return false; } 489const int P = g.patch, D = g.width, H = g.heads, HD = g.head_dim, F = g.ffn; 490const int pw = img.w / P, ph = img.h / P, N = pw * ph, nbx = pw / 2 ; 491nx = pw / 2 ; 492ny = ph / 2 ; 493if (!m. size_buffers (N, err)) return false; 494m.fail. clear (); 495// STRATA_VIT_PROF=1 (a diagnostic, stderr only, off by default): the time of each stage, the GPU waited for after every stage 496static const bool prof = std::getenv( "STRATA_VIT_PROF" ) != nullptr ; 497double pt[ 10 ] = { 0 }; 498auto pclock = [] { return std::chrono::duration < double, std::milli > (std::chrono::steady_clock::now(). time_since_epoch ()). count (); }; 499double pmark = prof ? pclock() : 0.0 ; 500auto stage = [ & ](int i) { 501if (!prof) return ; 502( void ) m. finish (); 503const double now = pclock(); 504pt[i] += now - pmark; 505pmark = now; 506}; 507const int K0 = 3 * P * P; 508{ // the patch matrix [N][K0], channel-major per patch, tokens in 2x2-merge order, written by the host into the context buffer (the GPU is idle here) 509float * pm = ( float * ) [m.d_ctx contents]; 510const size_t plane = ( size_t ) img.w * img.h; 511for ( int t = 0 ; t < N; ++ t) { 512const int b = t / 4 , r = t % 4 , py = 2 * (b / nbx) + r / 2 , px = 2 * (b % nbx) + r % 2 ; 513float * a = pm + ( size_t ) t * K0; 514for ( int c = 0 ; c < 3 ; ++ c) 515for ( int ky = 0 ; ky < P; ++ ky) 516std ::memcpy(a + ( size_t ) c * P * P + ( size_t ) ky * P, & img.chw[c * plane + ( size_t ) (py * P + ky) * img.w + ( size_t ) px * P], ( size_t ) P * sizeof ( float )); 517} 518} 519stage( 0 ); 520{ 521const GemmArgs a{( uint32_t ) N, ( uint32_t ) K0, ( uint32_t ) D, ( uint32_t ) K0, ( uint32_t ) K0, ( uint32_t ) D, 0 , 0 , 0 }; 522m. go ( "vk_gemm_seq_f32" , {BO(m.d_ctx), BO(m.patch_w), BO(m.d_x)}, & a, sizeof a, MTLSizeMake((D + 63 ) / 64 , N, 1 ), 64 ); 523} 524{ 525const PatchPostArgs a{g.pos_grid, pw, ph, nbx, D}; 526m. go ( "vk_patch_post" , {BO(m.d_x), BO(m.patch_b), BO(m.pos)}, & a, sizeof a, MTLSizeMake(N, 1 , 1 ), 256 ); 527} 528stage( 1 ); 529const float theta_scale = std::pow(g.rope_theta, -2.0f / ( float ) (HD / 2 )); 530const float kq_scale = 1.0f / std::sqrt(( float ) HD); 531const int R = m.kRows; 532for ( const DevLayer & L : m.layers) { 533for ( int r0 = 0 ; r0 < N; r0 += R) { 534const int rows_c = std::min(R, N - r0); 535const NormArgs na{D, ( int32_t ) L.qkv.kind, g.eps}; 536m. go ( "vk_layernorm" , {BO(m.d_x, ( size_t ) r0 * D * 4 ), BO(L.ln1_w), BO(L.ln1_b), BO(m.d_a)}, & na, sizeof na, MTLSizeMake(rows_c, 1 , 1 ), 256 ); 537m. wgemm (L.qkv, BO(m.d_a), rows_c, BO(m.d_y)); 538const RopeArgs ra{r0, nbx, H, HD, theta_scale, kq_scale}; 539m. go ( "vk_qkv_rope" , {BO(m.d_y), BO(L.qkv_b), BO(m.d_q16), BO(m.d_k16), BO(m.d_v16)}, & ra, sizeof ra, MTLSizeMake(rows_c, 1 , 1 ), 256 ); 540} 541stage( 2 ); 542const int Np = ( int ) m. padded (( size_t ) N); 543int QC = ( int ) std::max < size_t > ( 1 , std::min < size_t > (( size_t ) N, m.sp_elems / (( size_t ) H * Np))); 544const int qa = m. align_for (( size_t ) N); 545if (qa > 1 && QC < N && QC >= qa) QC -= QC % qa; 546for ( int q0 = 0 ; q0 < N; q0 += QC) { 547const int qc = std::min(QC, N - q0); 548// S [head][query][key] = q k^T (q carries the scale), F16 549m. gemm ( "vk_gemm_s" , m.mpp_s ? "vm_gemm_s" : nullptr , BO(m.d_q16, ( size_t ) q0 * D * 2 ), BO(m.d_k16), BO(m.d_S), qc, HD, N, D, D, Np, 550( size_t ) HD, ( size_t ) HD, ( size_t ) qc * Np, H); 551stage( 8 ); 552const SoftmaxArgs sa{N, Np}; 553const char * sm = nullptr ; 554NSUInteger st = 256 ; 555if (N <= 128 ) { sm = "vk_softmax_rows_2" ; st = 64 ; } 556else if (N <= 512 ) { sm = "vk_softmax_rows_8" ; st = 64 ; } 557else if (N <= 1024 ) { sm = "vk_softmax_rows_8" ; st = 128 ; } 558else if (N <= 4096 ) { sm = "vk_softmax_rows_16" ; st = 256 ; } 559else if (N <= 16384 ) { sm = "vk_softmax_rows_64" ; st = 256 ; } 560if (sm && [m. pipe (sm) maxTotalThreadsPerThreadgroup] < st) sm = nullptr ; // registers too few for that group here: the long-row kernel 561if (sm) m. go (sm, {BO(m.d_S)}, & sa, sizeof sa, MTLSizeMake(( size_t ) H * qc, 1 , 1 ), st); 562else m. go ( "vk_softmax_rows_long" , {BO(m.d_S)}, & sa, sizeof sa, MTLSizeMake(( size_t ) H * qc, 1 , 1 ), 256 ); 563stage( 9 ); 564// context [query][head * HD + d] = P V, float32 565m. gemm ( "vk_gemm_pv" , m.mpp_pv ? "vm_gemm_pv" : nullptr , BO(m.d_S), BO(m.d_v16), BO(m.d_ctx, ( size_t ) q0 * D * 4 ), qc, N, HD, Np, D, D, 566( size_t ) qc * Np, ( size_t ) HD, ( size_t ) HD, H); 567} 568stage( 3 ); 569for ( int r0 = 0 ; r0 < N; r0 += R) { 570const int rows_c = std::min(R, N - r0); 571const EltArgs ca{( uint64_t ) rows_c * D, ( int32_t ) L.o.kind, D}; 572m.go( "vk_cast" , {BO(m.d_ctx, ( size_t ) r0 * D * 4 ), BO(m.d_a)}, & ca, sizeof ca, MTLSizeMake(VitGpuImpl::blocks_for(ca.n), 1 , 1 ), 256 ); 573m. wgemm (L.o, BO(m.d_a), rows_c, BO(m.d_y)); 574const EltArgs ra{ 0 , 0 , D}; 575m. go ( "vk_add_bias_res" , {BO(m.d_x, ( size_t ) r0 * D * 4 ), BO(m.d_y), BO(L.o_b)}, & ra, sizeof ra, MTLSizeMake(rows_c, 1 , 1 ), 256 ); 576} 577stage( 4 ); 578for ( int r0 = 0 ; r0 < N; r0 += R) { 579const int rows_c = std::min(R, N - r0); 580const NormArgs na{D, ( int32_t ) L.up.kind, g.eps}; 581m. go ( "vk_layernorm" , {BO(m.d_x, ( size_t ) r0 * D * 4 ), BO(L.ln2_w), BO(L.ln2_b), BO(m.d_a)}, & na, sizeof na, MTLSizeMake(rows_c, 1 , 1 ), 256 ); 582m. wgemm (L.up, BO(m.d_a), rows_c, BO(m.d_y)); 583const EltArgs ga{ 0 , ( int32_t ) L.down.kind, F}; 584m. go ( "vk_bias_gelu_cast" , {BO(m.d_y), BO(L.up_b), BO(m.d_f16)}, & ga, sizeof ga, MTLSizeMake(rows_c, 1 , 1 ), 256 ); 585m. wgemm (L.down, BO(m.d_f16), rows_c, BO(m.d_y)); 586const EltArgs ra{ 0 , 0 , D}; 587m. go ( "vk_add_bias_res" , {BO(m.d_x, ( size_t ) r0 * D * 4 ), BO(m.d_y), BO(L.down_b)}, & ra, sizeof ra, MTLSizeMake(rows_c, 1 , 1 ), 256 ); 588} 589stage( 5 ); 590m. split (); // each layer is its own command buffer: none runs long enough for the system to cut it short 591} 592// post norm (into the merger's input kind), then the merger on 4-patch rows, in chunks; the output rows go to the context buffer 593const int M = N / 4 , RM = std::max( 1 , R / 4 ); 594for ( int r0 = 0 ; r0 < M; r0 += RM) { 595const int rows_c = std::min(RM, M - r0); 596const NormArgs na{D, ( int32_t ) m.mm0.kind, g.eps}; 597m. go ( "vk_layernorm" , {BO(m.d_x, ( size_t ) r0 * 4 * D * 4 ), BO(m.post_w), BO(m.post_b), BO(m.d_a)}, & na, sizeof na, MTLSizeMake(( size_t ) rows_c * 4 , 1 , 1 ), 256 ); 598m. wgemm (m.mm0, BO(m.d_a), rows_c, BO(m.d_y)); 599const EltArgs ga{ 0 , ( int32_t ) m.mm2.kind, g.merger_hidden}; 600m. go ( "vk_bias_gelu_cast" , {BO(m.d_y), BO(m.mm0_b), BO(m.d_f16)}, & ga, sizeof ga, MTLSizeMake(rows_c, 1 , 1 ), 256 ); 601m. wgemm (m.mm2, BO(m.d_f16), rows_c, BO(m.d_ctx, ( size_t ) r0 * g.out_dim * 4 )); 602const EltArgs ba{ 0 , 0 , g.out_dim}; 603m. go ( "vk_add_bias" , {BO(m.d_ctx, ( size_t ) r0 * g.out_dim * 4 ), BO(m.mm2_b)}, & ba, sizeof ba, MTLSizeMake(rows_c, 1 , 1 ), 256 ); 604} 605std :: string ferr; 606const bool ok = m. finish ( & ferr); 607if (!m.fail. empty ()) { err = m.fail; return false; } 608if (!ok) { err = ferr; return false; } 609stage( 6 ); 610rows. resize (( size_t ) M * g.out_dim); 611std ::memcpy(rows. data (), [m.d_ctx contents], rows. size () * 4 ); 612footprint_note( "after a picture" ); 613malloc_zone_pressure_relief( nullptr , 0 ); // the picture's decode and preparation buffers, freed by the caller before this one: see load() 614stage( 7 ); 615if (prof) 616std ::fprintf(stderr, "vit-prof N=%d: patch-matrix %.2f, patch-embed %.2f, ln+qkv %.2f, attention %.2f (S product %.2f, softmax %.2f), o-proj %.2f, ffn %.2f, merger %.2f, copy-out %.2f ms\n" , 617N, pt[ 0 ], pt[ 1 ], pt[ 2 ], pt[ 3 ] + pt[ 8 ] + pt[ 9 ], pt[ 8 ], pt[ 9 ], pt[ 4 ], pt[ 5 ], pt[ 6 ], pt[ 7 ]); 618return true; 619} 620} 621 622} // namespace strata_vit