okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
aff3a132f
main
1// metal/src/mtl_rt.mm - see mtl_rt.h. Built with ARC (-fobjc-arc). 2#import <Foundation/Foundation.h> 3#import <Metal/Metal.h> 4 5#include "mtl_rt.h" 6#include "resource_path.h" 7 8#include <chrono> 9#include <cstdio> 10#include <cstdlib> 11#include <fstream> 12#include <sstream> 13 14namespace mtl { 15 16double now_s () { 17return std ::chrono ::duration < double > (std ::chrono ::steady_clock ::now ().time_since_epoch ()).count (); 18} 19 20std ::string read_file (const std ::string & path ) { 21std ::ifstream f (path ,std ::ios::binary ); 22if (!f ) { 23std ::fprintf (stderr ,"mtl: cannot read %s\n" ,path .c_str ()); 24std ::exit (2 ); 25 } 26std ::stringstream ss ; 27ss <<f .rdbuf (); 28return ss .str (); 29} 30 31struct Context ::Impl { 32id < MTLDevice > dev ; 33id < MTLCommandQueue > q ; 34id < MTLCommandQueue > q2 = nil ;// run_graph_async's queue 35std ::vector < id < MTLLibrary >> libs ; 36id < MTLSharedEvent > ev = nil ;// run_graph_seg's handshake timeline 37uint64_t ev_v = 0 ; 38}; 39 40static inline id < MTLBuffer > B (const Buffer & b ) {return (__bridge id < MTLBuffer > )b .handle ; } 41// the MTLBuffer and offset that bind byte `off` of b (a chunked buffer: the chunk the offset selects) 42static inline id < MTLBuffer > BO (const Buffer & b ,size_t off ,size_t & o ) { 43if (!b .chunks ) {o = off + b .bias ;return B (b ); }// (bias: a view onto part of a bigger allocation; 0 otherwise) 44const size_t k = std ::min (off /b .stride ,b .chunks -> size ()- 1 ); 45o = off - k * b .stride ; 46return (__bridge id < MTLBuffer > )(* b .chunks )[k ]; 47} 48static inline id < MTLComputePipelineState > P (const Pipeline * p ) {return (__bridge id < MTLComputePipelineState > )p -> handle ; } 49static std ::string g_device_name = "unknown GPU" ; 50 51Context ::Context () :impl_ (new Impl ) { 52impl_ -> dev = MTLCreateSystemDefaultDevice (); 53if (!impl_ -> dev ) { 54std ::fprintf (stderr ,"mtl: no Metal device\n" ); 55std ::exit (2 ); 56 } 57impl_ -> q = [impl_ -> dev newCommandQueue ]; 58// env, then <exe dir>/metal/ (a component package), then the compiled-in source-tree path 59ggml_common_path = strata_metal ::resource2 ("STRATA_GGML_COMMON" ,"strata-quant-common.h" ,"ggml-common.h" ,STRATA_GGML_COMMON_DEFAULT ); 60kernel_dir = strata_metal ::resource ("STRATA_METAL_KERNELS" ,"kernels" ,STRATA_METAL_KERNELS_DEFAULT ); 61} 62 63Context ::~Context () {delete impl_ ; } 64 65std ::string Context ::device_name ()const {return [[impl_ -> dev name ]UTF8String ]; } 66bool Context ::has_family_apple (int n )const { 67return [impl_ -> dev supportsFamily :(MTLGPUFamily )(MTLGPUFamilyApple1 + (n - 1 ))]; 68} 69bool Context ::supports_metal4 ()const { 70if (@available (macOS 26.0 ,* ))return [impl_ -> dev supportsFamily :MTLGPUFamilyMetal4 ]; 71return false; 72} 73uint64_t Context ::recommended_working_set ()const {return [impl_ -> dev recommendedMaxWorkingSetSize ]; } 74uint64_t Context ::max_buffer_length ()const {return [impl_ -> dev maxBufferLength ]; } 75 76int Context ::compile (const std ::vector < std ::string > & files ,const std ::string & prelude ,bool fast_math ) { 77std ::string why ; 78const int id = compile_try (files ,prelude ,fast_math ,& why ); 79if (id < 0 ) { 80std ::fprintf (stderr ,"mtl: compile failed (%s, macOS %s; %s):\n%s\n" , [[impl_ -> dev name ]UTF8String ], 81 [[[NSProcessInfo processInfo ]operatingSystemVersionString ]UTF8String ], 82files .empty () ?"?" :files .back ().c_str (),why .c_str ()); 83std ::exit (3 ); 84 } 85return id ; 86} 87 88// The same, and a failure is returned (-1, the compiler's message in *why) instead of ending the process: for a library that has a fallback. 89int Context ::compile_try (const std ::vector < std ::string > & files ,const std ::string & prelude ,bool fast_math ,std ::string * why ) { 90std ::string src = prelude + "\n#include <metal_stdlib>\nusing namespace metal;\n" ; 91if (!ggml_common_path .empty ()&& prelude .find ("NO_GGML_COMMON" )== std ::string ::npos ) { 92src += "#define GGML_COMMON_DECL_METAL\n#define GGML_COMMON_IMPL_METAL\n" ; 93src += read_file (ggml_common_path ); 94src += "\n" ; 95 } 96for (const auto& f :files ) { 97std ::string p = (f .size ()&& f [0 ]== '/' ) ?f :kernel_dir + "/" + f ; 98src += "#line 1 \"" + f + "\"\n" + read_file (p )+ "\n" ; 99 } 100if (const char * dump = std ::getenv ("STRATA_METAL_MSL_DUMP" )) {// research: the full text of every library, as the compiler gets it 101static int ndump = 0 ; 102char name [32 ]; 103std ::snprintf (name ,sizeof name ,"/%03d.msl" ,ndump ++ ); 104if (std ::FILE * f = std ::fopen ((std ::string (dump )+ name ).c_str (),"wb" )) { 105std ::fwrite (src .data (),1 ,src .size (),f ); 106std ::fclose (f ); 107 } 108if (std ::FILE * f = std ::fopen ((std ::string (dump )+ "/index.txt" ).c_str (),"ab" )) { 109std ::fprintf (f ,"%s:" ,name + 1 ); 110for (const auto& fl :files )std ::fprintf (f , " %s ",fl .c_str ()); 111std ::fprintf (f ,"\n" ); 112std ::fclose (f ); 113 } 114 } 115MTLCompileOptions * o = [MTLCompileOptions new ]; 116// Safe math by default: no reassociation, so every token of a window is bitwise what a one-token call gives 117// (the kernels write their contractions as explicit fma). Measured free on the M5 Max. 118fast_math = false; 119if (const char * m = std ::getenv ("STRATA_METAL_MATH" ))fast_math = std ::string (m )== "fast" ; 120if (@available (macOS 15.0 ,* )) { 121o .mathMode = fast_math ?MTLMathModeFast :MTLMathModeSafe ; 122 }else { 123o .fastMathEnabled = fast_math ; 124 } 125NSError * err = nil ; 126id < MTLLibrary > lib = [impl_ -> dev newLibraryWithSource :[NSString stringWithUTF8String :src .c_str ()]options :o error :& err ]; 127if (!lib ) { 128if (why )* why = err ? [[err localizedDescription ]UTF8String ] :"unknown" ; 129return -1 ; 130 } 131impl_ -> libs .push_back (lib ); 132return (int )impl_ -> libs .size ()- 1 ; 133} 134 135Pipeline Context ::pipeline (int lib ,const std ::string & fn ,const Constants & c ) { 136NSError * err = nil ; 137id < MTLFunction > f ; 138NSString * name = [NSString stringWithUTF8String :fn .c_str ()]; 139if (c .vals .empty ()) { 140f = [impl_ -> libs [lib ]newFunctionWithName :name ]; 141// a function with (optional) function constants needs a specialization even when none is set 142if (f && f .functionConstantsDictionary .count > 0 ) 143f = [impl_ -> libs [lib ]newFunctionWithName :name constantValues :[MTLFunctionConstantValues new ]error :& err ]; 144 }else { 145MTLFunctionConstantValues * cv = [MTLFunctionConstantValues new ]; 146for (const auto& v :c .vals ) { 147int32_t iv = (int32_t )v .v ; 148bool bv = v .v != 0 ; 149uint32_t uv = v .v ; 150switch (v .type ) { 151case 0 : [cv setConstantValue :& iv type :MTLDataTypeInt atIndex :v .index ];break ; 152case 1 : [cv setConstantValue :& bv type :MTLDataTypeBool atIndex :v .index ];break ; 153default : [cv setConstantValue :& uv type :MTLDataTypeUInt atIndex :v .index ];break ; 154 } 155 } 156f = [impl_ -> libs [lib ]newFunctionWithName :name constantValues :cv error :& err ]; 157 } 158if (!f ) { 159std ::fprintf (stderr ,"mtl: no function %s %s\n" ,fn .c_str (),err ? [[err localizedDescription ]UTF8String ] :"" ); 160std ::exit (3 ); 161 } 162MTLComputePipelineDescriptor * d = [MTLComputePipelineDescriptor new ]; 163d .computeFunction = f ; 164d .supportIndirectCommandBuffers = YES ; 165id < MTLComputePipelineState > ps = [impl_ -> dev newComputePipelineStateWithDescriptor :d 166options :MTLPipelineOptionNone 167reflection :nil 168error :& err ]; 169if (!ps ) { 170std ::fprintf (stderr ,"mtl: pipeline %s: %s\n" ,fn .c_str (), [[err localizedDescription ]UTF8String ]); 171std ::exit (3 ); 172 } 173Pipeline p ; 174p .handle = (__bridge_retained void * )ps ; 175p .max_threads = (int )ps .maxTotalThreadsPerThreadgroup ; 176if (const char * cap = std ::getenv ("STRATA_METAL_MAX_THREADS_CAP" )) {// test hook, see require_fit 177const int lim = std ::atoi (cap ); 178if (lim > 0 && lim < p .max_threads )p .max_threads = lim ; 179 } 180p .simd_width = (int )ps .threadExecutionWidth ; 181p .static_tg_mem = (int )ps .staticThreadgroupMemoryLength ; 182p .name = fn ; 183if (!c .vals .empty ()) { 184p .name += "{" ; 185for (size_t i = 0 ;i < c .vals .size ();++ i ) 186p .name += (i ?"," :"" )+ std ::to_string (c .vals [i ].index )+ "=" + std ::to_string ((int )c .vals [i ].v ); 187p .name += "}" ; 188 } 189g_device_name = [[impl_ -> dev name ]UTF8String ]; 190return p ; 191} 192 193void require_fit (const Pipeline & p ,uint32_t threads ,const char * where ) { 194if (threads == 0 || (int64_t )threads <= (int64_t )p .max_threads )return ; 195std ::fprintf (stderr , 196"strata metal: the kernel %s can run at most %d threads per threadgroup on this GPU (%s), but the %s asks " 197"for %u.\nMetal skips such a dispatch without any error, so every answer would be wrong; stopping here " 198"instead. Please report this (the GPU, macOS version and this line) at " 199"https://github.com/Niko1221/Strata/issues . (#2323)\n" , 200p .name .empty () ?"?" :p .name .c_str (),p .max_threads ,g_device_name .c_str (),where ,threads ); 201std ::fflush (stderr ); 202std ::exit (6 ); 203} 204 205Buffer Context ::alloc (size_t bytes ) { 206id < MTLBuffer > b = [impl_ -> dev newBufferWithLength :bytes options :MTLResourceStorageModeShared ]; 207if (!b ) { 208std ::fprintf (stderr ,"mtl: alloc %zu failed\n" ,bytes ); 209std ::exit (4 ); 210 } 211std ::memset ([b contents ],0 ,bytes ); 212allocated_ += bytes ; 213Buffer r ; 214r .handle = (__bridge_retained void * )b ; 215r .ptr = [b contents ]; 216r .bytes = bytes ; 217return r ; 218} 219 220Buffer Context ::wrap (void * p ,size_t bytes ,size_t max_span ) { 221const size_t pg = 16384 ,maxlen = [impl_ -> dev maxBufferLength ] /pg * pg ; 222if (bytes <=maxlen || std ::getenv ("STRATA_METAL_WRAP_SPLIT" )&& std ::string (std ::getenv ("STRATA_METAL_WRAP_SPLIT" ))== "0" ) 223return wrap (p ,bytes ); 224const size_t span = (max_span + pg - 1 ) /pg * pg ; 225if (span >=maxlen /2 ) { 226std ::fprintf (stderr ,"mtl: wrap %zu: a tensor of %zu bytes does not fit the chunks\n" ,bytes ,max_span ); 227std ::exit (4 ); 228 } 229Buffer r ; 230r .chunks = std ::make_shared < std ::vector < void * >> (); 231r .stride = maxlen - span ; 232for (size_t base = 0 ;base < bytes ;base += r .stride ) { 233const size_t len = std ::min (maxlen , (bytes - base + pg - 1 ) /pg * pg ); 234id < MTLBuffer > b = [impl_ -> dev newBufferWithBytesNoCopy :(uint8_t * )p + base length :len 235options :MTLResourceStorageModeShared deallocator :nil ]; 236if (!b ) { 237std ::fprintf (stderr ,"mtl: wrap chunk %zu+%zu failed\n" ,base ,len ); 238std ::exit (4 ); 239 } 240r .chunks -> push_back ((__bridge_retained void * )b ); 241if (base + len >=bytes )break ; 242 } 243allocated_ += bytes ; 244r .handle = (* r .chunks )[0 ]; 245r .ptr = p ; 246r .bytes = bytes ; 247std ::fprintf (stderr ,"mtl: wrapped %.2f GB as %zu overlapping buffers (maxBufferLength %.2f GB, overlap %.2f GB)\n" , 248bytes /1e9 ,r .chunks -> size (),maxlen /1e9 ,span /1e9 ); 249return r ; 250} 251 252Buffer Context ::wrap (void * p ,size_t bytes ) { 253id < MTLBuffer > b = [impl_ -> dev newBufferWithBytesNoCopy :p length :bytes options :MTLResourceStorageModeShared deallocator :nil ]; 254if (!b ) { 255std ::fprintf (stderr ,"mtl: wrap %zu failed\n" ,bytes ); 256std ::exit (4 ); 257 } 258allocated_ += bytes ; 259Buffer r ; 260r .handle = (__bridge_retained void * )b ; 261r .ptr = p ; 262r .bytes = bytes ; 263return r ; 264} 265 266void Context ::free (Buffer & b ) { 267if (b .chunks ) { 268for (void * h :* b .chunks ) {id < MTLBuffer > x = (__bridge_transfer id < MTLBuffer > )h ;x = nil ; } 269b = Buffer {}; 270return ; 271 } 272if (b .handle ) { 273id < MTLBuffer > x = (__bridge_transfer id < MTLBuffer > )b .handle ; 274x = nil ; 275 } 276b = Buffer {}; 277} 278 279static void encode (id < MTLComputeCommandEncoder > enc ,const Dispatch & d ) { 280require_fit (d ,"dispatch" ); 281 [enc setComputePipelineState :P (d .p )]; 282for (size_t i = 0 ;i < d .args .size ();++ i ) { 283const Arg & a = d .args [i ]; 284if (a .buf ) { 285size_t o ; 286id < MTLBuffer > mb = BO (* a .buf ,a .off ,o ); 287 [enc setBuffer :mb offset :o atIndex :i ]; 288 } 289else 290 [enc setBytes :a .bytes .data ()length :a .bytes .size ()atIndex :i ]; 291 } 292if (d .tg_mem ) [enc setThreadgroupMemoryLength :(d .tg_mem + 15 ) /16 * 16 atIndex :0 ]; 293if (d .indirect ) 294 [enc dispatchThreadgroupsWithIndirectBuffer :B (* d .indirect ) 295indirectBufferOffset :d .ind_off 296threadsPerThreadgroup :MTLSizeMake (d .tg [0 ],d .tg [1 ],d .tg [2 ])]; 297else 298 [enc dispatchThreadgroups :MTLSizeMake (d .grid [0 ],d .grid [1 ],d .grid [2 ]) 299threadsPerThreadgroup :MTLSizeMake (d .tg [0 ],d .tg [1 ],d .tg [2 ])]; 300} 301 302double Context ::run (const std ::vector < Dispatch > & ds ,int reps ,bool concurrent ,bool barrier_between ) { 303@autoreleasepool { 304id < MTLCommandBuffer > cb = [impl_ -> q commandBufferWithUnretainedReferences ]; 305id < MTLComputeCommandEncoder > enc = 306 [cb computeCommandEncoderWithDispatchType :concurrent ?MTLDispatchTypeConcurrent :MTLDispatchTypeSerial ]; 307for (int r = 0 ;r < reps ;++ r ) 308for (const auto& d :ds ) { 309encode (enc ,d ); 310if (barrier_between ) [enc memoryBarrierWithScope :MTLBarrierScopeBuffers ]; 311 } 312 [enc endEncoding ]; 313 [cb commit ]; 314 [cb waitUntilCompleted ]; 315if (cb .status != MTLCommandBufferStatusCompleted ) { 316std ::fprintf (stderr ,"mtl: command buffer failed: %s\n" , [[cb .error localizedDescription ]UTF8String ]); 317std ::exit (5 ); 318 } 319return cb .GPUEndTime - cb .GPUStartTime ; 320 } 321} 322 323double Context ::run_graph (const std ::vector < Dispatch > & ds ,size_t count ) { 324// The wait spins on the buffer's status for up to 20 ms before it blocks: waitUntilCompleted's thread wake costs ~0.5 ms 325// a window (M5 Max, Q2_0 decode: +5% tok/s, same tokens). STRATA_METAL_SPIN=0: the blocking wait. 326static const bool spin = !(std ::getenv ("STRATA_METAL_SPIN" )&& std ::string (std ::getenv ("STRATA_METAL_SPIN" ))== "0" ); 327@autoreleasepool { 328id < MTLCommandBuffer > cb = [impl_ -> q commandBufferWithUnretainedReferences ]; 329id < MTLComputeCommandEncoder > enc = [cb computeCommandEncoderWithDispatchType :MTLDispatchTypeConcurrent ]; 330const size_t nd = std ::min (count ,ds .size ()); 331for (size_t i = 0 ;i < nd ;++ i ) { 332if (i > 0 && ds [i ].barrier ) [enc memoryBarrierWithScope :MTLBarrierScopeBuffers ]; 333encode (enc ,ds [i ]); 334 } 335 [enc endEncoding ]; 336 [cb commit ]; 337if (spin ) { 338const autot0 = std ::chrono ::steady_clock ::now (); 339while (cb .status < MTLCommandBufferStatusCompleted && 340std ::chrono ::duration < double > (std ::chrono ::steady_clock ::now ()- t0 ).count ()< 20e-3 ) {} 341 } 342if (cb .status < MTLCommandBufferStatusCompleted ) [cb waitUntilCompleted ]; 343if (cb .status != MTLCommandBufferStatusCompleted ) { 344std ::fprintf (stderr ,"mtl: command buffer failed: %s\n" , [[cb .error localizedDescription ]UTF8String ]); 345std ::exit (5 ); 346 } 347return cb .GPUEndTime - cb .GPUStartTime ; 348 } 349} 350 351void * Context ::run_graph_async (const std ::vector < Dispatch > & ds ) { 352@autoreleasepool { 353if (impl_ -> q2 == nil )impl_ -> q2 = [impl_ -> dev newCommandQueue ]; 354id < MTLCommandBuffer > cb = [impl_ -> q2 commandBufferWithUnretainedReferences ]; 355id < MTLComputeCommandEncoder > enc = [cb computeCommandEncoderWithDispatchType :MTLDispatchTypeConcurrent ]; 356for (size_t i = 0 ;i < ds .size ();++ i ) { 357if (i > 0 && ds [i ].barrier ) [enc memoryBarrierWithScope :MTLBarrierScopeBuffers ]; 358encode (enc ,ds [i ]); 359 } 360 [enc endEncoding ]; 361 [cb commit ]; 362return (__bridge_retained void * )cb ; 363 } 364} 365 366double Context ::wait_async (void * token ) { 367if (token == nullptr )return 0.0 ; 368@autoreleasepool { 369id < MTLCommandBuffer > cb = (__bridge_transfer id < MTLCommandBuffer > )token ; 370if (cb .status < MTLCommandBufferStatusCompleted ) [cb waitUntilCompleted ]; 371if (cb .status != MTLCommandBufferStatusCompleted ) { 372std ::fprintf (stderr ,"mtl: command buffer failed: %s\n" , [[cb .error localizedDescription ]UTF8String ]); 373std ::exit (5 ); 374 } 375return cb .GPUEndTime - cb .GPUStartTime ; 376 } 377} 378 379double Context ::run_graph_seg (const std ::vector < Dispatch > & ds ,const std ::vector < int > & cuts ,void (* at_cut )(void * ,int ), 380void * user ) { 381@autoreleasepool { 382if (impl_ -> ev == nil )impl_ -> ev = [impl_ -> dev newSharedEvent ]; 383id < MTLSharedEvent > ev = impl_ -> ev ; 384const uint64_t base = impl_ -> ev_v ; 385id < MTLCommandBuffer > cb = [impl_ -> q commandBufferWithUnretainedReferences ]; 386size_t i = 0 ; 387for (size_t s = 0 ;s <=cuts .size ();++ s ) { 388const size_t end = s < cuts .size () ? (size_t )cuts [s ] :ds .size (); 389id < MTLComputeCommandEncoder > enc = [cb computeCommandEncoderWithDispatchType :MTLDispatchTypeConcurrent ]; 390const size_t first = i ; 391for (;i < end ;++ i ) { 392if (i > first && ds [i ].barrier ) [enc memoryBarrierWithScope :MTLBarrierScopeBuffers ]; 393encode (enc ,ds [i ]); 394 } 395 [enc endEncoding ]; 396if (s < cuts .size ()) { 397 [cb encodeSignalEvent :ev value :base + 2 * s + 1 ]; 398 [cb encodeWaitForEvent :ev value :base + 2 * s + 2 ]; 399 } 400 } 401 [cb commit ]; 402for (size_t s = 0 ;s < cuts .size ();++ s ) { 403const uint64_t want = base + 2 * s + 1 ; 404while (ev .signaledValue < want ) { 405if (cb .status >=MTLCommandBufferStatusCompleted )break ;// an error: the wait below reports it 406 } 407at_cut (user , (int )s ); 408ev .signaledValue = base + 2 * s + 2 ; 409 } 410impl_ -> ev_v = base + 2 * cuts .size ()+ 2 ; 411 [cb waitUntilCompleted ]; 412if (cb .status != MTLCommandBufferStatusCompleted ) { 413std ::fprintf (stderr ,"mtl: command buffer failed: %s\n" , [[cb .error localizedDescription ]UTF8String ]); 414std ::exit (5 ); 415 } 416return cb .GPUEndTime - cb .GPUStartTime ; 417 } 418} 419 420double Context ::run_wall (const std ::vector < Dispatch > & ds ,int reps ,double * gpu_seconds ) { 421double gpu = 0 ; 422const double t0 = now_s (); 423for (int r = 0 ;r < reps ;++ r ) { 424@autoreleasepool { 425id < MTLCommandBuffer > cb = [impl_ -> q commandBufferWithUnretainedReferences ]; 426id < MTLComputeCommandEncoder > enc = [cb computeCommandEncoder ]; 427for (const auto& d :ds )encode (enc ,d ); 428 [enc endEncoding ]; 429 [cb commit ]; 430 [cb waitUntilCompleted ]; 431gpu += cb .GPUEndTime - cb .GPUStartTime ; 432 } 433 } 434if (gpu_seconds )* gpu_seconds = gpu ; 435return now_s ()- t0 ; 436} 437 438void Context ::warm (const std ::vector < Dispatch > & ds ,double seconds ) { 439const double t0 = now_s (); 440while (now_s ()- t0 < seconds )run (ds ); 441} 442 443double Context ::run_icb (const std ::vector < Dispatch > & ds ,int reps ,bool barrier_between ) { 444@autoreleasepool { 445size_t maxb = 1 ; 446for (const auto& d :ds )maxb = std ::max (maxb ,d .args .size ()); 447MTLIndirectCommandBufferDescriptor * desc = [MTLIndirectCommandBufferDescriptor new ]; 448desc .commandTypes = MTLIndirectCommandTypeConcurrentDispatch ; 449desc .inheritBuffers = NO ; 450desc .inheritPipelineState = NO ; 451desc .maxKernelBufferBindCount = maxb ; 452id < MTLIndirectCommandBuffer > icb = [impl_ -> dev newIndirectCommandBufferWithDescriptor :desc 453maxCommandCount :ds .size () 454options :0 ]; 455NSMutableSet * used = [NSMutableSet new ]; 456for (size_t i = 0 ;i < ds .size ();++ i ) { 457const Dispatch & d = ds [i ]; 458require_fit (d ,"indirect-command dispatch" ); 459id < MTLIndirectComputeCommand > c = [icb indirectComputeCommandAtIndex :i ]; 460 [c setComputePipelineState :P (d .p )]; 461for (size_t a = 0 ;a < d .args .size ();++ a ) { 462if (!d .args [a ].buf ) { 463std ::fprintf (stderr ,"mtl: run_icb needs buffer arguments only\n" ); 464std ::exit (5 ); 465 } 466size_t o ; 467id < MTLBuffer > mb = BO (* d .args [a ].buf ,d .args [a ].off ,o ); 468 [c setKernelBuffer :mb offset :o atIndex :a ]; 469 [used addObject :mb ]; 470 } 471if (d .tg_mem ) [c setThreadgroupMemoryLength :(d .tg_mem + 15 ) /16 * 16 atIndex :0 ]; 472 [c concurrentDispatchThreadgroups :MTLSizeMake (d .grid [0 ],d .grid [1 ],d .grid [2 ]) 473threadsPerThreadgroup :MTLSizeMake (d .tg [0 ],d .tg [1 ],d .tg [2 ])]; 474if (barrier_between ) [c setBarrier ]; 475 } 476id < MTLCommandBuffer > cb = [impl_ -> q commandBufferWithUnretainedReferences ]; 477id < MTLComputeCommandEncoder > enc = [cb computeCommandEncoderWithDispatchType :MTLDispatchTypeConcurrent ]; 478for (id < MTLBuffer > b in used ) [enc useResource :b usage :MTLResourceUsageRead |MTLResourceUsageWrite ]; 479for (int r = 0 ;r < reps ;++ r ) { 480 [enc executeCommandsInBuffer :icb withRange :NSMakeRange (0 ,ds .size ())]; 481if (barrier_between ) [enc memoryBarrierWithScope :MTLBarrierScopeBuffers ]; 482 } 483 [enc endEncoding ]; 484 [cb commit ]; 485 [cb waitUntilCompleted ]; 486if (cb .status != MTLCommandBufferStatusCompleted ) { 487std ::fprintf (stderr ,"mtl: icb command buffer failed: %s\n" , [[cb .error localizedDescription ]UTF8String ]); 488std ::exit (5 ); 489 } 490return cb .GPUEndTime - cb .GPUStartTime ; 491 } 492} 493 494}// namespace mtl