okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
aff3a132f
main
1// metal/src/gpu/runtime.cpp - include/strata/gpu/runtime.hpp on Metal (metal-cpp). Skeleton of MAC-PLAN Phase 1. 2// 3// Memory model (measured on the M5 Max, phaseA-tests/mac-design.md): 4// - every allocation is one MTLBuffer, storageModeShared, hazard tracking untracked (the engine orders its own work 5// on streams, as on CUDA); the "device pointer" handed to the host code is the buffer's gpuAddress, which differs 6// from contents() on Apple GPUs, so host code that wrongly dereferences a device pointer faults instead of 7// silently working. host_view() is the sanctioned CPU view. 8// - all buffers sit in one MTLResidencySet attached to every queue, so kernels may take raw gpuAddress pointers. 9// Streams: a command queue + the open command buffer + the open compute encoder + a shared-event timeline. Work is 10// committed at event records, synchronizations, host functions and every kFlushEvery dispatches. 11// Graphs: begin_capture switches the stream to recording; dispatch/copy/memset/event ops are kept as data and 12// re-encoded by graph_launch (encoding measured at ~0.17 us per dispatch on the M5 Max). 13#define NS_PRIVATE_IMPLEMENTATION 14#define MTL_PRIVATE_IMPLEMENTATION 15#include <execinfo.h> 16#include <Foundation/Foundation.hpp> 17#include <Metal/Metal.hpp> 18 19#include "strata/gpu/metal.hpp" 20#include "strata/gpu/runtime.hpp" 21 22#include <sys/sysctl.h> 23 24#include <atomic> 25#include <chrono> 26#include <cstdio> 27#include <cstring> 28#include <iterator> 29#include <map> 30#include <mutex> 31#include <thread> 32#include <vector> 33 34namespace strata::gpu { 35 36namespace { 37 38constexpr int kFlushEvery = 4096 ;// dispatches per command buffer before an automatic commit 39 40struct Alloc { 41MTL ::Buffer * buf = nullptr ; 42uint64_t gpu = 0 ; 43uint8_t * cpu = nullptr ; 44size_t bytes = 0 ; 45bool host = false;// from host_alloc (the host code holds the CPU address) 46bool purged = false;// purge_device_allocations: its memory given back (any later copy is an error) 47}; 48 49struct Op { 50enum Kind {Dispatch ,Copy ,Fill ,Record ,Wait }kind = Dispatch ; 51MTL ::ComputePipelineState * pipe = nullptr ; 52uint8_t args [256 ]; 53size_t arg_bytes = 0 ; 54 std::vector < uint8_t > big_args ; 55 metal::Grid groups ,threads ; 56size_t tg_bytes = 0 ; 57void * dst = nullptr ; 58const void * src = nullptr ; 59size_t bytes = 0 ; 60int value = 0 ; 61Event ev = nullptr ; 62}; 63 64}// namespace 65 66struct EventImpl { 67MTL ::SharedEvent * ev = nullptr ;// the recording stream's timeline 68uint64_t value = 0 ;// 0: never recorded (complete, as a fresh CUDA event) 69}; 70 71struct GraphImpl { 72 std::vector < Op > ops ; 73}; 74struct GraphExecImpl { 75 std::vector < Op > ops ; 76}; 77 78struct StreamImpl { 79MTL ::CommandQueue * q = nullptr ; 80MTL ::CommandBuffer * cb = nullptr ; 81MTL ::ComputeCommandEncoder * enc = nullptr ; 82MTL ::SharedEvent * tl = nullptr ; 83uint64_t submitted = 0 ;// the timeline value the last committed command buffer signals 84int pending = 0 ;// dispatches in the open command buffer 85GraphImpl * rec = nullptr ; 86}; 87 88namespace { 89 90struct Runtime { 91MTL ::Device * dev = nullptr ; 92MTL ::ResidencySet * rs = nullptr ; 93 std::mutex mu ; 94 std::map < uint64_t ,Alloc > by_gpu ;// gpuAddress -> allocation 95 std::map < uintptr_t ,uint64_t > by_cpu ;// contents() -> gpuAddress 96StreamImpl * legacy = nullptr ; 97 std::map < std::string ,MTL ::ComputePipelineState *> pipes ; 98 std::map < std::string ,MTL ::Library *> libs ; 99 metal::Stats stats ; 100}; 101 102Runtime & rt () { 103static Runtime * r = [] { 104auto * x = new Runtime ; 105x -> dev = MTL ::CreateSystemDefaultDevice (); 106NS ::Error * e = nullptr ; 107MTL ::ResidencySetDescriptor * d = MTL ::ResidencySetDescriptor ::alloc ()-> init (); 108x -> rs = x -> dev -> newResidencySet (d ,& e ); 109d -> release (); 110return x ; 111 }(); 112return * r ; 113} 114 115thread_localError t_last = kSuccess ; 116Error fail (Error e ) { 117if (e != kSuccess && e != kNotReady )t_last = e ; 118return e ; 119} 120 121StreamImpl * make_stream () { 122auto * s = new StreamImpl ; 123s -> q = rt ().dev -> newCommandQueue (); 124s -> q -> addResidencySet (rt ().rs ); 125s -> tl = rt ().dev -> newSharedEvent (); 126s -> tl -> setSignaledValue (0 ); 127return s ; 128} 129 130StreamImpl * S (Stream s ) { 131if (s )return s ; 132Runtime & r = rt (); 133 std::lock_guard < std::mutex > lk (r .mu ); 134if (!r .legacy )r .legacy = make_stream (); 135return r .legacy ; 136} 137 138/// The allocation that holds GPU address `p` (or CPU address `p` of a host allocation), with the offset into it. 139const Alloc * find (const void * p ,size_t * off ) { 140Runtime & r = rt (); 141 std::lock_guard < std::mutex > lk (r .mu ); 142const uint64_t a = (uint64_t ) (uintptr_t )p ; 143auto it = r .by_gpu .upper_bound (a ); 144if (it != r .by_gpu .begin ()) { 145-- it ; 146if (a < it -> first + it -> second .bytes ) {* off = a - it -> first ;return & it -> second ; } 147 } 148auto ic = r .by_cpu .upper_bound ((uintptr_t )p ); 149if (ic != r .by_cpu .begin ()) { 150-- ic ; 151const Alloc & al = r .by_gpu [ic -> second ]; 152if ((uintptr_t )p < ic -> first + al .bytes ) {* off = (uintptr_t )p - ic -> first ;return & al ; } 153 } 154return nullptr ; 155} 156 157MTL ::CommandBuffer * open_cb (StreamImpl * s ) { 158if (!s -> cb ) { 159s -> cb = s -> q -> commandBufferWithUnretainedReferences (); 160s -> cb -> retain (); 161++ rt ().stats .command_buffers ; 162 } 163return s -> cb ; 164} 165void end_encoder (StreamImpl * s ) { 166if (s -> enc ) {s -> enc -> endEncoding ();s -> enc = nullptr ; } 167} 168MTL ::ComputeCommandEncoder * encoder (StreamImpl * s ) { 169if (!s -> enc )s -> enc = open_cb (s )-> computeCommandEncoder ();// serial dispatch: each dispatch sees the last 170return s -> enc ; 171} 172void flush (StreamImpl * s ) { 173if (!s -> cb )return ; 174end_encoder (s ); 175s -> cb -> encodeSignalEvent (s -> tl ,++ s -> submitted ); 176s -> cb -> commit (); 177s -> cb -> release (); 178s -> cb = nullptr ; 179s -> pending = 0 ; 180} 181Error wait_value (MTL ::SharedEvent * ev ,uint64_t v ) { 182while (ev -> signaledValue ()< v ) std::this_thread::yield (); 183++ rt ().stats .host_syncs ; 184return kSuccess ; 185} 186 187void check_purged (const Alloc * a ,const char * what ) { 188if (a && a -> purged ) { 189 std::fprintf (stderr ,"strata metal runtime: a %s touches a device allocation of %.1f MB that was given back " 190"(STRATA_METAL_KEEP_HOST_WEIGHTS=1 keeps it)\n" ,what ,a -> bytes /1e6 ); 191void * fr [48 ]; 192backtrace_symbols_fd (fr ,backtrace (fr ,48 ),2 );// which host code still reads it 193 std::abort (); 194 } 195} 196 197Error encode_copy (StreamImpl * s ,void * dst ,const void * src ,size_t n ) { 198size_t od = 0 ,os = 0 ; 199const Alloc * ad = find (dst ,& od ); 200const Alloc * as = find (src ,& os ); 201check_purged (ad ,"copy" ); 202check_purged (as ,"copy" ); 203if (ad && as ) {// buffer to buffer: a blit, in stream order 204end_encoder (s ); 205MTL ::BlitCommandEncoder * b = open_cb (s )-> blitCommandEncoder (); 206b -> copyFromBuffer (as -> buf ,os ,ad -> buf ,od ,n ); 207b -> endEncoding (); 208++ rt ().stats .blits ; 209return kSuccess ; 210 } 211// ordinary host memory on one side: the stream's earlier work must be complete first (the conservative CUDA 212// pageable-memory semantics: the call returns when the copy is done) 213flush (s ); 214wait_value (s -> tl ,s -> submitted ); 215uint8_t * d = ad ?ad -> cpu + od : (uint8_t * )dst ; 216const uint8_t * sp = as ?as -> cpu + os : (const uint8_t * )src ; 217 std::memcpy (d ,sp ,n ); 218return kSuccess ; 219} 220 221Error encode_fill (StreamImpl * s ,void * p ,int value ,size_t n ) { 222size_t off = 0 ; 223const Alloc * a = find (p ,& off ); 224if (!a )return fail (kErrorInvalidValue ); 225check_purged (a ,"fill" ); 226end_encoder (s ); 227MTL ::BlitCommandEncoder * b = open_cb (s )-> blitCommandEncoder (); 228b -> fillBuffer (a -> buf ,NS ::Range ::Make (off ,n ), (uint8_t )value ); 229b -> endEncoding (); 230++ rt ().stats .blits ; 231return kSuccess ; 232} 233 234Error encode_dispatch (StreamImpl * s ,const Op & o ) { 235MTL ::ComputeCommandEncoder * e = encoder (s ); 236e -> setComputePipelineState (o .pipe ); 237if (o .big_args .empty ())e -> setBytes (o .args ,o .arg_bytes ,0 ); 238else e -> setBytes (o .big_args .data (),o .big_args .size (),0 ); 239if (o .tg_bytes )e -> setThreadgroupMemoryLength (o .tg_bytes ,0 ); 240e -> dispatchThreadgroups (MTL ::Size (o .groups .x ,o .groups .y ,o .groups .z ),MTL ::Size (o .threads .x ,o .threads .y ,o .threads .z )); 241++ rt ().stats .dispatches ; 242if (++ s -> pending >=kFlushEvery )flush (s ); 243return kSuccess ; 244} 245 246Error record_event (EventImpl * e ,StreamImpl * s ) { 247flush (s );// CUDA submits on launch: a recorded event must become complete without a further call 248e -> ev = s -> tl ; 249e -> value = s -> submitted ; 250return kSuccess ; 251} 252Error wait_event (StreamImpl * s ,EventImpl * e ) { 253if (!e || e -> value == 0 )return kSuccess ; 254end_encoder (s ); 255open_cb (s )-> encodeWait (e -> ev ,e -> value ); 256return kSuccess ; 257} 258 259Error run_op (StreamImpl * s ,const Op & o ) { 260switch (o .kind ) { 261case Op ::Dispatch :return encode_dispatch (s ,o ); 262case Op ::Copy :return encode_copy (s ,o .dst ,o .src ,o .bytes ); 263case Op ::Fill :return encode_fill (s ,o .dst ,o .value ,o .bytes ); 264case Op ::Record :return record_event (o .ev ,s ); 265case Op ::Wait :return wait_event (s ,o .ev ); 266 } 267return kSuccess ; 268} 269 270// STRATA_METAL_ALLOC_LOG=1: every allocation of 16 MB or more, with the running total (memory budgets on small Macs) 271void alloc_log (const char * what ,size_t n ) { 272static const bool on = std::getenv ("STRATA_METAL_ALLOC_LOG" )!= nullptr ; 273static std::atomic < uint64_t > tot {0 }; 274const uint64_t t = tot += n ; 275if (on && n >= (16u <<20 )) std::fprintf (stderr ,"strata metal runtime: %s %.1f MB (total %.2f GB)\n" ,what ,n /1e6 ,t /1e9 ); 276} 277 278Error new_alloc (void ** p ,size_t bytes ,bool host ) { 279Runtime & r = rt (); 280const size_t n = bytes ?bytes :1 ; 281MTL ::Buffer * b = r .dev -> newBuffer (n ,MTL ::ResourceStorageModeShared |MTL ::ResourceHazardTrackingModeUntracked ); 282if (!b )return fail (kErrorMemoryAllocation ); 283Alloc a {b ,b -> gpuAddress (), (uint8_t * )b -> contents (),n ,host }; 284alloc_log (host ?"host alloc" :"device alloc" ,n ); 285 { 286 std::lock_guard < std::mutex > lk (r .mu ); 287r .by_gpu [a .gpu ]= a ; 288r .by_cpu [(uintptr_t )a .cpu ]= a .gpu ; 289r .rs -> addAllocation (b ); 290r .rs -> commit (); 291 } 292* p = host ? (void * )a .cpu : (void * ) (uintptr_t )a .gpu ; 293return kSuccess ; 294} 295 296Error free_alloc (void * p ) { 297if (!p )return kSuccess ; 298Runtime & r = rt (); 299size_t off = 0 ; 300const Alloc * a = find (p ,& off ); 301if (!a || off != 0 )return fail (kErrorInvalidValue ); 302device_synchronize ();// as cudaFree: the GPU is done with it 303 std::lock_guard < std::mutex > lk (r .mu ); 304MTL ::Buffer * b = a -> buf ; 305const uint64_t g = a -> gpu ; 306r .by_cpu .erase ((uintptr_t )a -> cpu ); 307r .by_gpu .erase (g ); 308r .rs -> removeAllocation (b ); 309r .rs -> commit (); 310b -> release (); 311return kSuccess ; 312} 313 314}// namespace 315 316// ---------------------------------------------------------------------------------------------------- runtime.hpp 317void * host_view (const void * p ) { 318size_t off = 0 ; 319const Alloc * a = find (p ,& off ); 320return a ?a -> cpu + off :nullptr ; 321} 322 323// The Metal decode window reads the model itself; the device copies of the weights the shared host code uploads for 324// the CUDA-shaped kernels (the pack's dense pool, the native head, ...) are never read on Metal. On a small Mac their 325// memory is worth more as expert arena: every device (not host) allocation of min_bytes or more is made purgeable-empty 326// and dropped from the residency set. Returns the bytes given back. 327uint64_t purge_device_allocations (size_t min_bytes ) { 328Runtime & r = rt (); 329device_synchronize (); 330 std::lock_guard < std::mutex > lk (r .mu ); 331uint64_t n = 0 ; 332for (auto & [gpu ,a ] :r .by_gpu ) { 333if (a .host || a .purged || a .bytes < min_bytes )continue ; 334r .rs -> removeAllocation (a .buf ); 335a .buf -> setPurgeableState (MTL ::PurgeableStateEmpty ); 336a .purged = true; 337n += a .bytes ; 338 } 339r .rs -> commit (); 340return n ; 341} 342 343Error get_last_error () {const Error e = t_last ;t_last = kSuccess ;return e ; } 344Error peek_last_error () {return t_last ; } 345const char * error_string (Error e ) { 346switch (e ) { 347case kSuccess :return "no error" ; 348case kNotReady :return "device not ready" ; 349case kErrorInvalidValue :return "invalid argument" ; 350case kErrorMemoryAllocation :return "out of memory" ; 351case kErrorUnsupported :return "operation not supported on Metal" ; 352case kErrorLaunchFailure :return "command buffer failed" ; 353 } 354return "unknown Metal runtime error" ; 355} 356 357Error get_device (int * dev ) {* dev = 0 ;return kSuccess ; } 358Error set_device (int dev ) {return dev == 0 ?kSuccess :fail (kErrorInvalidValue ); } 359Error device_count (int * n ) {* n = rt ().dev ?1 :0 ;return kSuccess ; } 360Error device_synchronize () { 361Runtime & r = rt (); 362StreamImpl * s = S (nullptr ); 363flush (s ); 364return wait_value (s -> tl ,s -> submitted ); 365 (void )r ; 366} 367Error mem_get_info (size_t * free_b ,size_t * total_b ) { 368// the GPU's budget is the working set the OS grants this process; what is free is that minus what is allocated 369MTL ::Device * d = rt ().dev ; 370const uint64_t budget = d -> recommendedMaxWorkingSetSize (); 371const uint64_t used = d -> currentAllocatedSize (); 372* total_b = (size_t )budget ; 373* free_b = (size_t ) (used < budget ?budget - used :0 ); 374return kSuccess ; 375} 376Error device_integrated (int * v ,int ) {* v = 1 ;return kSuccess ; } 377Error device_sm_count (int * v ,int ) {* v = 0 ;return fail (kErrorUnsupported ); }// Apple reports no core count 378Error device_clock_khz (int * v ,int ) {* v = 0 ;return fail (kErrorUnsupported ); } 379Error runtime_version (int * v ) {* v = 0 ;return kSuccess ; } 380Error device_can_access_peer (int * v ,int ,int ) {* v = 0 ;return kSuccess ; } 381Error device_enable_peer_access (int ,unsigned ) {return fail (kErrorUnsupported ); } 382Error get_device_properties (DeviceProp * p ,int dev ) { 383if (dev != 0 )return fail (kErrorInvalidValue ); 384* p = DeviceProp {}; 385MTL ::Device * d = rt ().dev ; 386 std::snprintf (p -> name ,sizeof p -> name ,"%s" ,d -> name ()-> utf8String ()); 387 std::snprintf (p -> gcnArchName ,sizeof p -> gcnArchName ,"%s" ,d -> supportsFamily (MTL ::GPUFamilyApple10 ) ?"apple10" :"apple9-or-older" ); 388p -> warpSize = 32 ;// the SIMD-group width of every Apple GPU 389p -> totalGlobalMem = (size_t )d -> recommendedMaxWorkingSetSize (); 390return kSuccess ; 391} 392 393Error malloc_device_raw (void ** p ,size_t bytes ) {return new_alloc (p ,bytes , false); } 394Error free_device (void * p ) {return free_alloc (p ); } 395Error host_alloc_raw (void ** p ,size_t bytes ,unsigned ) {return new_alloc (p ,bytes , true); } 396Error free_host (void * p ) { 397 { 398Runtime & r = rt (); 399 std::lock_guard < std::mutex > lk (r .mu ); 400auto it = r .by_cpu .find ((uintptr_t )p ); 401if (it == r .by_cpu .end ())return fail (kErrorInvalidValue ); 402 } 403return free_alloc (p ); 404} 405Error host_register (void * p ,size_t bytes ,unsigned ) { 406// existing host memory (an mmapped file, an arena) as a NoCopy buffer: page-aligned start and length required 407const uintptr_t pg = 16384 ; 408if (((uintptr_t )p %pg )!= 0 )return fail (kErrorInvalidValue ); 409Runtime & r = rt (); 410const size_t n = (bytes + pg - 1 ) /pg * pg ; 411MTL ::Buffer * b = r .dev -> newBuffer (p ,n ,MTL ::ResourceStorageModeShared |MTL ::ResourceHazardTrackingModeUntracked ,nullptr ); 412if (!b )return fail (kErrorMemoryAllocation ); 413Alloc a {b ,b -> gpuAddress (), (uint8_t * )b -> contents (),n , true}; 414alloc_log ("host register" ,n ); 415 std::lock_guard < std::mutex > lk (r .mu ); 416r .by_gpu [a .gpu ]= a ; 417r .by_cpu [(uintptr_t )a .cpu ]= a .gpu ; 418r .rs -> addAllocation (b ); 419r .rs -> commit (); 420return kSuccess ; 421} 422Error host_unregister (void * p ) {return free_alloc (p ); } 423Error host_device_pointer_raw (void ** dev ,void * host ) { 424size_t off = 0 ; 425const Alloc * a = find (host ,& off ); 426if (!a )return fail (kErrorInvalidValue ); 427* dev = (void * ) (uintptr_t ) (a -> gpu + off ); 428return kSuccess ; 429} 430Error memset_device (void * p ,int value ,size_t bytes ) { 431StreamImpl * s = S (nullptr ); 432const Error e = encode_fill (s ,p ,value ,bytes ); 433flush (s ); 434wait_value (s -> tl ,s -> submitted ); 435return e ; 436} 437Error memset_async (void * p ,int value ,size_t bytes ,Stream st ) { 438StreamImpl * s = S (st ); 439if (s -> rec ) { 440Op o ; 441o .kind = Op ::Fill ;o .dst = p ;o .value = value ;o .bytes = bytes ; 442s -> rec -> ops .push_back (std::move (o )); 443return kSuccess ; 444 } 445return encode_fill (s ,p ,value ,bytes ); 446} 447 448Error memcpy_sync (void * dst ,const void * src ,size_t bytes ,CopyKind ) { 449StreamImpl * s = S (nullptr ); 450const Error e = encode_copy (s ,dst ,src ,bytes ); 451flush (s ); 452wait_value (s -> tl ,s -> submitted ); 453return e ; 454} 455Error memcpy_2d_async (void * dst ,size_t dpitch ,const void * src ,size_t spitch ,size_t width ,size_t height ,CopyKind k ,Stream st ) { 456for (size_t r = 0 ;r < height ;++ r ) {// skeleton: one copy per row (rare in the engine) 457const Error e = memcpy_async ((uint8_t * )dst + r * dpitch , (const uint8_t * )src + r * spitch ,width ,k ,st ); 458if (e != kSuccess )return e ; 459 } 460return kSuccess ; 461} 462Error memcpy_peer_async (void * dst ,int dst_dev ,const void * src ,int src_dev ,size_t bytes ,Stream st ) { 463if (dst_dev != 0 || src_dev != 0 )return fail (kErrorInvalidValue );// one GPU 464return memcpy_async (dst ,src ,bytes ,kDeviceToDevice ,st ); 465} 466Error memcpy_async (void * dst ,const void * src ,size_t bytes ,CopyKind ,Stream st ) { 467StreamImpl * s = S (st ); 468if (s -> rec ) { 469Op o ; 470o .kind = Op ::Copy ;o .dst = dst ;o .src = src ;o .bytes = bytes ; 471s -> rec -> ops .push_back (std::move (o )); 472return kSuccess ; 473 } 474return encode_copy (s ,dst ,src ,bytes ); 475} 476 477Error stream_create (Stream * s ,unsigned ) {* s = make_stream ();return kSuccess ; } 478Error stream_destroy (Stream s ) { 479if (!s )return kSuccess ; 480flush (s ); 481wait_value (s -> tl ,s -> submitted ); 482s -> tl -> release (); 483s -> q -> release (); 484delete s ; 485return kSuccess ; 486} 487Error stream_synchronize (Stream st ) { 488StreamImpl * s = S (st ); 489flush (s ); 490return wait_value (s -> tl ,s -> submitted ); 491} 492Error stream_query (Stream st ) { 493StreamImpl * s = S (st ); 494flush (s ); 495return s -> tl -> signaledValue () >=s -> submitted ?kSuccess :kNotReady ; 496} 497Error stream_wait_event (Stream st ,Event e ,unsigned ) { 498StreamImpl * s = S (st ); 499if (s -> rec ) { 500Op o ; 501o .kind = Op ::Wait ;o .ev = e ; 502s -> rec -> ops .push_back (std::move (o )); 503return kSuccess ; 504 } 505return wait_event (s ,e ); 506} 507Error launch_host_func (Stream st ,HostFn fn ,void * arg ) { 508// skeleton: in stream order by completing the stream first (the engine's uses are rare; Phase 2 replaces this by a 509// completion handler + a shared-event wait so the host thread does not block) 510StreamImpl * s = S (st ); 511if (s -> rec )return fail (kErrorUnsupported ); 512flush (s ); 513wait_value (s -> tl ,s -> submitted ); 514fn (arg ); 515return kSuccess ; 516} 517 518Error event_create (Event * e ,unsigned ) {* e = new EventImpl ;return kSuccess ; } 519Error event_destroy (Event e ) { 520delete e ; 521return kSuccess ; 522} 523Error event_record (Event e ,Stream st ) { 524StreamImpl * s = S (st ); 525if (s -> rec ) { 526Op o ; 527o .kind = Op ::Record ;o .ev = e ; 528s -> rec -> ops .push_back (std::move (o )); 529return kSuccess ; 530 } 531return record_event (e ,s ); 532} 533Error event_query (Event e ) {return !e -> ev || e -> ev -> signaledValue () >=e -> value ?kSuccess :kNotReady ; } 534Error event_synchronize (Event e ) {return e -> ev ?wait_value (e -> ev ,e -> value ) :kSuccess ; } 535Error event_elapsed_ms (float * ms ,Event ,Event ) {* ms = 0.0f ;return fail (kErrorUnsupported ); } 536 537Error begin_capture (Stream st ) { 538StreamImpl * s = S (st ); 539if (s -> rec )return fail (kErrorInvalidValue ); 540flush (s ); 541s -> rec = new GraphImpl ; 542return kSuccess ; 543} 544Error end_capture (Stream st ,Graph * g ) { 545StreamImpl * s = S (st ); 546if (!s -> rec ) {* g = nullptr ;return fail (kErrorInvalidValue ); } 547* g = s -> rec ; 548s -> rec = nullptr ; 549return kSuccess ; 550} 551Error graph_node_count (Graph g ,size_t * n ) {* n = g ?g -> ops .size () :0 ;return kSuccess ; } 552Error graph_instantiate (GraphExec * x ,Graph g ) { 553* x = new GraphExecImpl {g -> ops }; 554return kSuccess ; 555} 556Error graph_launch (GraphExec x ,Stream st ) { 557StreamImpl * s = S (st ); 558if (s -> rec ) {// a graph launched into a capture becomes part of it (CUDA: a child graph) 559s -> rec -> ops .insert (s -> rec -> ops .end (),x -> ops .begin (),x -> ops .end ()); 560return kSuccess ; 561 } 562for (const Op & o :x -> ops ) { 563const Error e = run_op (s ,o ); 564if (e != kSuccess )return e ; 565 } 566return kSuccess ; 567} 568Error graph_upload (GraphExec ,Stream ) {return kSuccess ; } 569Error graph_destroy (Graph g ) {delete g ;return kSuccess ; } 570Error graph_exec_destroy (GraphExec x ) {delete x ;return kSuccess ; } 571 572// ---------------------------------------------------------------------------------------------------- metal.hpp 573namespace metal { 574 575MTL ::Device * device () {return rt ().dev ; } 576 577MTL ::ComputePipelineState * pipeline (const char * source_name ,const char * source ,const char * function , std::string & err ) { 578Runtime & r = rt (); 579const std::string key = std::string (source_name )+ "::" + function ; 580 std::lock_guard < std::mutex > lk (r .mu ); 581if (auto it = r .pipes .find (key );it != r .pipes .end ())return it -> second ; 582MTL ::Library *& lib = r .libs [source_name ]; 583NS ::Error * e = nullptr ; 584if (!lib ) { 585MTL ::CompileOptions * co = MTL ::CompileOptions ::alloc ()-> init (); 586co -> setMathMode (MTL ::MathModeSafe );// no fast-math reassociation: parity with the CUDA reference first 587lib = r .dev -> newLibrary (NS ::String ::string (source ,NS ::UTF8StringEncoding ),co ,& e ); 588co -> release (); 589if (!lib ) { 590err = std::string ("MSL compile of " )+ source_name + ": " + (e ?e -> localizedDescription ()-> utf8String () :"?" ); 591return nullptr ; 592 } 593 } 594MTL ::Function * f = lib -> newFunction (NS ::String ::string (function ,NS ::UTF8StringEncoding )); 595if (!f ) {err = std::string ("no MSL function " )+ function ;return nullptr ; } 596MTL ::ComputePipelineState * p = r .dev -> newComputePipelineState (f ,& e ); 597f -> release (); 598if (!p ) {err = std::string ("pipeline " )+ function + ": " + (e ?e -> localizedDescription ()-> utf8String () :"?" );return nullptr ; } 599r .pipes [key ]= p ; 600return p ; 601} 602 603Error dispatch (Stream st ,MTL ::ComputePipelineState * p ,const void * args ,size_t arg_bytes ,Grid groups ,Grid threads , 604size_t tg_bytes ) { 605if (arg_bytes > 4096 )return fail (kErrorInvalidValue );// setBytes limit 606 {// Metal skips a dispatch above the pipeline's maxTotalThreadsPerThreadgroup without any error (#2323): stop instead 607const uint64_t want = (uint64_t )threads .x * threads .y * threads .z ; 608if (p && want > (uint64_t )p -> maxTotalThreadsPerThreadgroup ()) { 609Runtime & r = rt (); 610 std::string name = "?" ; 611 { 612 std::lock_guard < std::mutex > lk (r .mu ); 613for (const auto & kv :r .pipes ) 614if (kv .second == p ) {name = kv .first ;break ; } 615 } 616 std::fprintf (stderr , 617"strata metal: the kernel %s can run at most %lu threads per threadgroup on this GPU (%s), but the " 618"launch asks for %lu.\nMetal skips such a dispatch without any error, so every answer would be " 619"wrong; stopping here instead. Please report this (the GPU, macOS version and this line) at " 620"https://github.com/Niko1221/Strata/issues . (#2323)\n" , 621name .c_str (), (unsigned long )p -> maxTotalThreadsPerThreadgroup (), 622r .dev -> name ()-> utf8String (), (unsigned long )want ); 623 std::fflush (stderr ); 624 std::exit (6 ); 625 } 626 } 627StreamImpl * s = S (st ); 628Op o ; 629o .kind = Op ::Dispatch ; 630o .pipe = p ; 631if (arg_bytes <=sizeof o .args ) { std::memcpy (o .args ,args ,arg_bytes );o .arg_bytes = arg_bytes ; } 632else o .big_args .assign ((const uint8_t * )args , (const uint8_t * )args + arg_bytes ); 633o .groups = groups ; 634o .threads = threads ; 635o .tg_bytes = tg_bytes ; 636if (s -> rec ) {s -> rec -> ops .push_back (std::move (o ));return kSuccess ; } 637return encode_dispatch (s ,o ); 638} 639 640Stats stats () {return rt ().stats ; } 641 642}// namespace metal 643}// namespace strata::gpu