okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
aff3a132f
main
1// metal/src/mtl_rt.h - a thin C++ face over Metal for the standalone kernel programs (parity, benches). 2// 3// The implementation (mtl_rt.mm) is the only Objective-C++ file; every program and test is plain C++ against this 4// header. Kernels are MSL source files compiled at run time (newLibraryWithSource): the Command Line Tools have no 5// offline `metal` compiler, and the runtime compiler is part of the OS. ggml-common.h (MIT, third_party/ggml) is 6// prepended for the i-quant grids and block structs. 7#pragma once 8 9#include <cstddef> 10#include <cstdint> 11#include <cstring> 12#include <memory> 13#include <string> 14#include <vector> 15 16namespace mtl { 17 18struct Buffer { 19void * handle = nullptr;// id<MTLBuffer> (retained); the first chunk of a chunked buffer 20void * ptr = nullptr;// CPU address (shared storage) 21size_t bytes = 0 ; 22// a buffer longer than maxBufferLength: overlapping chunks every `stride` bytes (see Context::wrap) 23std ::shared_ptr < std ::vector < void * >>chunks ; 24size_t stride = 0 ; 25size_t bias = 0 ;// bytes from the MTLBuffer's start to ptr (a view onto an allocation the runtime owns) 26template < class T > T * as ()const {return static_cast < T *> (ptr ); } 27}; 28 29struct Pipeline { 30void * handle = nullptr;// id<MTLComputePipelineState> 31int max_threads = 0 ;// maxTotalThreadsPerThreadgroup 32int simd_width = 0 ;// threadExecutionWidth 33int static_tg_mem = 0 ;// staticThreadgroupMemoryLength 34std ::string name ;// the function (+ its constants), for messages 35}; 36 37// A function-constant value set (index -> int / bool / uint). 38struct Constants { 39struct V {int index ;int type ;uint32_t v ; };// type 0 int, 1 bool, 2 uint, 3 short, 4 ushort 40std ::vector < V > vals ; 41Constants & i (int idx ,int v ) {vals .push_back ({idx ,0 , (uint32_t )v });return * this ; } 42Constants & b (int idx ,bool v ) {vals .push_back ({idx ,1 , (uint32_t )v });return * this ; } 43Constants & u (int idx ,uint32_t v ) {vals .push_back ({idx ,2 ,v });return * this ; } 44}; 45 46struct Arg {// one argument of a dispatch: a buffer (+ offset) or inline bytes 47const Buffer * buf = nullptr; 48size_t off = 0 ; 49std ::vector < uint8_t > bytes ; 50static Arg B (const Buffer & b ,size_t off = 0 ) {Arg a ;a .buf = & b ;a .off = off ;return a ; } 51template < class T > static Arg V (const T & v ) { 52Arg a ;a .bytes .resize (sizeof (T ));std ::memcpy (a .bytes .data (),& v ,sizeof (T ));return a ; 53 } 54}; 55 56struct Dispatch { 57const Pipeline * p = nullptr; 58std ::vector < Arg > args ; 59uint32_t grid [3 ]= {1 ,1 ,1 };// threadgroups 60uint32_t tg [3 ]= {32 ,1 ,1 };// threads per threadgroup 61uint32_t tg_mem = 0 ;// dynamic threadgroup memory at index 0 (bytes) 62const Buffer * indirect = nullptr;// grid from a GPU buffer (3 x uint32 threadgroup counts) at ind_off 63size_t ind_off = 0 ; 64bool barrier = true;// run_graph: a buffer memory barrier before this dispatch 65}; 66 67// A pipeline whose maxTotalThreadsPerThreadgroup is below the threadgroup size a dispatch asks for is NOT executed by 68// Metal and raises no error (0.1.44, #2323: gdn_step needs 512 threads, an M2 Max gave 448 for the GDN_NTOK >= 2 69// specializations - the layers silently kept their old outputs and every answer was garbage). So every dispatch is 70// checked: too few threads is fatal, with a message that names the kernel, the limit and the size needed. 71// STRATA_METAL_MAX_THREADS_CAP=N lowers every pipeline's reported limit to N (a test hook: it proves this check). 72void require_fit (const Pipeline & p ,uint32_t threads ,const char * where ); 73inline void require_fit (const Dispatch & d ,const char * where = "dispatch" ) { 74require_fit (* d .p ,d .tg [0 ]* d .tg [1 ]* d .tg [2 ],where ); 75} 76 77class Context { 78public : 79Context (); 80 ~Context (); 81std ::string device_name ()const ; 82bool has_family_apple (int n )const ;// MTLGPUFamilyApple<n> 83bool supports_metal4 ()const ; 84uint64_t recommended_working_set ()const ; 85uint64_t max_buffer_length ()const ; 86// Zero-copy weights: the GPU address of host memory [p, p + bytes) (file-backed pages of the model, RAM slots) through a 87// no-copy buffer over the pages it spans, made resident. 0: not mappable (the cap on buffers is reached, or the pages are not 88// ours). The first dispatch that reads cold pages waits for them (the buffer is wired on use). 89uint64_t zc_map (const void * p ,size_t bytes ); 90Pipeline pipeline_uncached (int lib ,const std ::string & fn ,const Constants & c ); 91size_t zc_count ()const ; 92uint64_t allocated ()const {return allocated_ ; }// bytes of alloc() + wrap() buffers so far 93 94// Compiles a library from MSL source files (paths), prepended by `prelude` (defines) and, if include_ggml, 95// ggml-common.h with GGML_COMMON_DECL_METAL/IMPL_METAL. Returns a library id (index); aborts with the 96// compiler log on error. 97// Safe math unless STRATA_METAL_MATH=fast (the argument is ignored; kept for callers). 98int compile (const std ::vector < std ::string >& files ,const std ::string & prelude = "" ,bool fast_math = false); 99// compile() that returns -1 (the compiler's message in *why) on a failure instead of ending the process 100int compile_try (const std ::vector < std ::string >& files ,const std ::string & prelude ,bool fast_math ,std ::string * why ); 101Pipeline pipeline (int lib ,const std ::string & fn ,const Constants & c = {}); 102 103Buffer alloc (size_t bytes );// shared storage, zeroed 104Buffer wrap (void * page_aligned ,size_t bytes );// no-copy wrap (page-aligned, size multiple of page) 105// the same, also when bytes > maxBufferLength: then overlapping chunks, each holding any range of up to 106// max_span bytes that starts in it (max_span = the largest tensor bound at one offset) 107Buffer wrap (void * page_aligned ,size_t bytes ,size_t max_span ); 108void free (Buffer & b ); 109 110// Encodes `ds` into ONE compute encoder (serial or concurrent dispatch type) and ONE command buffer, `reps` 111// times over; commits and waits. Returns the GPU time (GPUEndTime - GPUStartTime) in seconds. 112void * mark ();// split_runs() that returns a token for the buffer just committed (nullptr: nothing was queued) 113void wait_mark (void * token );// block until that buffer has completed, then drop the token 114void drop_mark (void * token );// drop a token without waiting (an event recorded again, or destroyed, before it was waited on) 115void split_runs ();// commit the batched dispatches as their own command buffer, without waiting 116void flush_runs ();// commit and wait for the dispatches batched since the last flush 117double run (const std ::vector < Dispatch >& ds ,int reps = 1 ,bool concurrent = false,bool barrier_between = false); 118// A dependency graph in ONE concurrent encoder: a memory barrier only before dispatches with `barrier` set, so 119// the dispatches between two barriers may overlap. Returns the GPU time in seconds. 120double run_graph (const std ::vector < Dispatch >& ds ,size_t count = (size_t )-1 );// count: only the first `count` dispatches (the step profile's prefixes) 121// run_graph on a SECOND queue, committed without waiting: the GPU may overlap it with work on the main queue (the two must touch 122// different buffers). Returns a token; wait_async(token) blocks until it has completed (returns its GPU time in seconds). 123void * run_graph_async (const std ::vector < Dispatch >& ds ); 124double wait_async (void * token ); 125// run_graph in segments: the dispatches [cuts[s-1], cuts[s]) are one concurrent encoder; after segment s (for 126// s < cuts.size()) the GPU signals a shared event and waits until the host has run at_cut(s) - the host's turn 127// between two parts of one committed command buffer (the SSD-streaming handshake: the routing is read, the 128// missing experts are put in place). Returns the GPU time in seconds. 129double run_graph_seg (const std ::vector < Dispatch >& ds ,const std ::vector < int >& cuts ,void (* at_cut )(void * ,int ), 130void * user ); 131// One command buffer per `run_cb` call, empty or not: measures commit+wait round trips. 132double run_wall (const std ::vector < Dispatch >& ds ,int reps ,double * gpu_seconds = nullptr ); 133 134// Indirect command buffer: the dispatches recorded once, executed `reps` times in one command buffer. 135// Buffers are bound per command (setKernelBuffer); inline bytes are not allowed (use buffers). 136double run_icb (const std ::vector < Dispatch >& ds ,int reps ,bool barrier_between ); 137// Runs `ds` repeatedly for about `seconds` of wall time: lifts the GPU out of its idle clocks before a timing. 138void warm (const std ::vector < Dispatch >& ds ,double seconds = 0.3 ); 139 140std ::string ggml_common_path ;// where strata-quant-common.h (formerly ggml-common.h) is read from 141std ::string kernel_dir ;// where relative kernel paths resolve 142 143private : 144struct Impl ; 145Impl * impl_; 146uint64_t allocated_ = 0 ; 147}; 148 149double now_s (); // monotonic wall clock (seconds) 150std :: string read_file( const std ::string & path); 151 152} // namespace mtl